import { _extends } from "./chunk-H4GSM2WL.js"; import { subscribeWithSelector } from "./chunk-XGWIEMTH.js"; import { Events } from "./chunk-OAEA5FZL.js"; import { require_client } from "./chunk-AFNBKP7P.js"; import { create } from "./chunk-QJTQF54Q.js"; import { addAfterEffect, addEffect, applyProps, clear, context, createPortal, extend, preload, require_with_selector, suspend, useFrame, useInstanceHandle, useLoader, useThree } from "./chunk-JRJA23OI.js"; import { AddEquation, AdditiveBlending, AlwaysStencilFunc, AmbientLight, AnimationClip, AnimationMixer, AudioListener, AudioLoader, BackSide, BatchedMesh, Bone, Box2, Box3, BoxGeometry, BufferAttribute, BufferGeometry, ByteType, Camera, CameraHelper, CanvasTexture, CatmullRomCurve3, ClampToEdgeWrapping, Clock, Color, CompressedTexture, CubeCamera, CubeReflectionMapping, CubeTextureLoader, CubicBezierCurve3, Curve, CurvePath, CustomBlending, CylinderGeometry, DataTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EdgesGeometry, EllipseCurve, EqualStencilFunc, EquirectangularReflectionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float32BufferAttribute, FloatType, FrontSide, Frustum, GridHelper, Group, HalfFloatType, IcosahedronGeometry, ImageBitmapLoader, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, KeepStencilOp, Line, Line3, LineBasicMaterial, LineLoop, LineSegments, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, Loader, LoaderUtils, LoadingManager, MOUSE, Material, MathUtils, Matrix3, Matrix4, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MirroredRepeatWrapping, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NoBlending, NoToneMapping, NormalBlending, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, OctahedronGeometry, OneFactor, OneMinusSrcAlphaFactor, OrthographicCamera, Path, PerspectiveCamera, Plane, PlaneGeometry, PointLight, Points, PointsMaterial, PropertyBinding, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_4x4_Format, RGBA_ASTC_6x6_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, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RedFormat, RedIntegerFormat, RepeatWrapping, ReplaceStencilOp, SRGBColorSpace, Scene, ShaderChunk, ShaderMaterial, Shape, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Sphere, SphereGeometry, Spherical, SpotLight, SrcAlphaFactor, TOUCH, Texture, TextureLoader, TorusGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShortType, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGLCubeRenderTarget, WebGLRenderTarget, WebGLRenderer, WireframeGeometry, ZeroFactor } from "./chunk-INS7YHTD.js"; import "./chunk-QURGMCZB.js"; import "./chunk-LTNRPUSL.js"; import "./chunk-YLZ34CCM.js"; import "./chunk-642Z5WD3.js"; import "./chunk-USXRE7Q2.js"; import { require_react } from "./chunk-ZNKPWGXJ.js"; import { __commonJS, __toESM } from "./chunk-G3PMV62Z.js"; // node_modules/stats.js/build/stats.min.js var require_stats_min = __commonJS({ "node_modules/stats.js/build/stats.min.js"(exports2, module2) { (function(f2, e2) { "object" === typeof exports2 && "undefined" !== typeof module2 ? module2.exports = e2() : "function" === typeof define && define.amd ? define(e2) : f2.Stats = e2(); })(exports2, function() { var f2 = function() { function e2(a7) { c2.appendChild(a7.dom); return a7; } function u(a7) { for (var d2 = 0; d2 < c2.children.length; d2++) c2.children[d2].style.display = d2 === a7 ? "block" : "none"; l2 = a7; } var l2 = 0, c2 = document.createElement("div"); c2.style.cssText = "position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000"; c2.addEventListener("click", function(a7) { a7.preventDefault(); u(++l2 % c2.children.length); }, false); var k = (performance || Date).now(), g = k, a6 = 0, r2 = e2(new f2.Panel("FPS", "#0ff", "#002")), h = e2(new f2.Panel("MS", "#0f0", "#020")); if (self.performance && self.performance.memory) var t3 = e2(new f2.Panel("MB", "#f08", "#201")); u(0); return { REVISION: 16, dom: c2, addPanel: e2, showPanel: u, begin: function() { k = (performance || Date).now(); }, end: function() { a6++; var c5 = (performance || Date).now(); h.update(c5 - k, 200); if (c5 > g + 1e3 && (r2.update(1e3 * a6 / (c5 - g), 100), g = c5, a6 = 0, t3)) { var d2 = performance.memory; t3.update(d2.usedJSHeapSize / 1048576, d2.jsHeapSizeLimit / 1048576); } return c5; }, update: function() { k = this.end(); }, domElement: c2, setMode: u }; }; f2.Panel = function(e2, f3, l2) { var c2 = Infinity, k = 0, g = Math.round, a6 = g(window.devicePixelRatio || 1), r2 = 80 * a6, h = 48 * a6, t3 = 3 * a6, v5 = 2 * a6, d2 = 3 * a6, m = 15 * a6, n2 = 74 * a6, p2 = 30 * a6, q = document.createElement("canvas"); q.width = r2; q.height = h; q.style.cssText = "width:80px;height:48px"; var b5 = q.getContext("2d"); b5.font = "bold " + 9 * a6 + "px Helvetica,Arial,sans-serif"; b5.textBaseline = "top"; b5.fillStyle = l2; b5.fillRect(0, 0, r2, h); b5.fillStyle = f3; b5.fillText(e2, t3, v5); b5.fillRect(d2, m, n2, p2); b5.fillStyle = l2; b5.globalAlpha = 0.9; b5.fillRect(d2, m, n2, p2); return { dom: q, update: function(h2, w) { c2 = Math.min(c2, h2); k = Math.max(k, h2); b5.fillStyle = l2; b5.globalAlpha = 1; b5.fillRect(0, 0, r2, m); b5.fillStyle = f3; b5.fillText(g(h2) + " " + e2 + " (" + g(c2) + "-" + g(k) + ")", t3, v5); b5.drawImage(q, d2 + a6, m, n2 - a6, p2, d2, m, n2 - a6, p2); b5.fillRect(d2 + n2 - a6, m, a6, p2); b5.fillStyle = l2; b5.globalAlpha = 0.9; b5.fillRect(d2 + n2 - a6, m, a6, g((1 - h2 / w) * p2)); } }; }; return f2; }); } }); // node_modules/@react-three/drei/web/Html.js var React = __toESM(require_react()); var ReactDOM = __toESM(require_client()); var v1 = new Vector3(); var v2 = new Vector3(); var v3 = new Vector3(); var v4 = new Vector2(); function defaultCalculatePosition(el, camera, size2) { const objectPos = v1.setFromMatrixPosition(el.matrixWorld); objectPos.project(camera); const widthHalf = size2.width / 2; const heightHalf = size2.height / 2; return [objectPos.x * widthHalf + widthHalf, -(objectPos.y * heightHalf) + heightHalf]; } function isObjectBehindCamera(el, camera) { const objectPos = v1.setFromMatrixPosition(el.matrixWorld); const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); const deltaCamObj = objectPos.sub(cameraPos); const camDir = camera.getWorldDirection(v3); return deltaCamObj.angleTo(camDir) > Math.PI / 2; } function isObjectVisible(el, camera, raycaster, occlude) { const elPos = v1.setFromMatrixPosition(el.matrixWorld); const screenPos = elPos.clone(); screenPos.project(camera); v4.set(screenPos.x, screenPos.y); raycaster.setFromCamera(v4, camera); const intersects = raycaster.intersectObjects(occlude, true); if (intersects.length) { const intersectionDistance = intersects[0].distance; const pointDistance = elPos.distanceTo(raycaster.ray.origin); return pointDistance < intersectionDistance; } return true; } function objectScale(el, camera) { if (camera instanceof OrthographicCamera) { return camera.zoom; } else if (camera instanceof PerspectiveCamera) { const objectPos = v1.setFromMatrixPosition(el.matrixWorld); const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); const vFOV = camera.fov * Math.PI / 180; const dist = objectPos.distanceTo(cameraPos); const scaleFOV = 2 * Math.tan(vFOV / 2) * dist; return 1 / scaleFOV; } else { return 1; } } function objectZIndex(el, camera, zIndexRange) { if (camera instanceof PerspectiveCamera || camera instanceof OrthographicCamera) { const objectPos = v1.setFromMatrixPosition(el.matrixWorld); const cameraPos = v2.setFromMatrixPosition(camera.matrixWorld); const dist = objectPos.distanceTo(cameraPos); const A = (zIndexRange[1] - zIndexRange[0]) / (camera.far - camera.near); const B = zIndexRange[1] - A * camera.far; return Math.round(A * dist + B); } return void 0; } var epsilon = (value) => Math.abs(value) < 1e-10 ? 0 : value; function getCSSMatrix(matrix6, multipliers, prepend = "") { let matrix3d = "matrix3d("; for (let i4 = 0; i4 !== 16; i4++) { matrix3d += epsilon(multipliers[i4] * matrix6.elements[i4]) + (i4 !== 15 ? "," : ")"); } return prepend + matrix3d; } var getCameraCSSMatrix = /* @__PURE__ */ ((multipliers) => { return (matrix6) => getCSSMatrix(matrix6, multipliers); })([1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1]); var getObjectCSSMatrix = /* @__PURE__ */ ((scaleMultipliers) => { return (matrix6, factor) => getCSSMatrix(matrix6, scaleMultipliers(factor), "translate(-50%,-50%)"); })((f2) => [1 / f2, 1 / f2, 1 / f2, 1, -1 / f2, -1 / f2, -1 / f2, -1, 1 / f2, 1 / f2, 1 / f2, 1, 1, 1, 1, 1]); function isRefObject(ref) { return ref && typeof ref === "object" && "current" in ref; } var Html = React.forwardRef(({ children, eps: eps2 = 1e-3, style, className, prepend, center: center3, fullscreen, portal, distanceFactor, sprite = false, transform = false, occlude, onOcclude, castShadow, receiveShadow, material, geometry: geometry3, zIndexRange = [16777271, 0], calculatePosition = defaultCalculatePosition, as = "div", wrapperClass, pointerEvents = "auto", ...props }, ref) => { const { gl, camera, scene, size: size2, raycaster, events, viewport } = useThree(); const [el] = React.useState(() => document.createElement(as)); const root = React.useRef(null); const group = React.useRef(null); const oldZoom = React.useRef(0); const oldPosition = React.useRef([0, 0]); const transformOuterRef = React.useRef(null); const transformInnerRef = React.useRef(null); const target2 = (portal == null ? void 0 : portal.current) || events.connected || gl.domElement.parentNode; const occlusionMeshRef = React.useRef(null); const isMeshSizeSet = React.useRef(false); const isRayCastOcclusion = React.useMemo(() => { return occlude && occlude !== "blending" || Array.isArray(occlude) && occlude.length && isRefObject(occlude[0]); }, [occlude]); React.useLayoutEffect(() => { const el2 = gl.domElement; if (occlude && occlude === "blending") { el2.style.zIndex = `${Math.floor(zIndexRange[0] / 2)}`; el2.style.position = "absolute"; el2.style.pointerEvents = "none"; } else { el2.style.zIndex = null; el2.style.position = null; el2.style.pointerEvents = null; } }, [occlude]); React.useLayoutEffect(() => { if (group.current) { const currentRoot = root.current = ReactDOM.createRoot(el); scene.updateMatrixWorld(); if (transform) { el.style.cssText = `position:absolute;top:0;left:0;pointer-events:none;overflow:hidden;`; } else { const vec = calculatePosition(group.current, camera, size2); el.style.cssText = `position:absolute;top:0;left:0;transform:translate3d(${vec[0]}px,${vec[1]}px,0);transform-origin:0 0;`; } if (target2) { if (prepend) target2.prepend(el); else target2.appendChild(el); } return () => { if (target2) target2.removeChild(el); currentRoot.unmount(); }; } }, [target2, transform]); React.useLayoutEffect(() => { if (wrapperClass) el.className = wrapperClass; }, [wrapperClass]); const styles2 = React.useMemo(() => { if (transform) { return { position: "absolute", top: 0, left: 0, width: size2.width, height: size2.height, transformStyle: "preserve-3d", pointerEvents: "none" }; } else { return { position: "absolute", transform: center3 ? "translate3d(-50%,-50%,0)" : "none", ...fullscreen && { top: -size2.height / 2, left: -size2.width / 2, width: size2.width, height: size2.height }, ...style }; } }, [style, center3, fullscreen, size2, transform]); const transformInnerStyles = React.useMemo(() => ({ position: "absolute", pointerEvents }), [pointerEvents]); React.useLayoutEffect(() => { isMeshSizeSet.current = false; if (transform) { var _root$current; (_root$current = root.current) == null || _root$current.render(React.createElement("div", { ref: transformOuterRef, style: styles2 }, React.createElement("div", { ref: transformInnerRef, style: transformInnerStyles }, React.createElement("div", { ref, className, style, children })))); } else { var _root$current2; (_root$current2 = root.current) == null || _root$current2.render(React.createElement("div", { ref, style: styles2, className, children })); } }); const visible = React.useRef(true); useFrame((gl2) => { if (group.current) { camera.updateMatrixWorld(); group.current.updateWorldMatrix(true, false); const vec = transform ? oldPosition.current : calculatePosition(group.current, camera, size2); if (transform || Math.abs(oldZoom.current - camera.zoom) > eps2 || Math.abs(oldPosition.current[0] - vec[0]) > eps2 || Math.abs(oldPosition.current[1] - vec[1]) > eps2) { const isBehindCamera = isObjectBehindCamera(group.current, camera); let raytraceTarget = false; if (isRayCastOcclusion) { if (Array.isArray(occlude)) { raytraceTarget = occlude.map((item) => item.current); } else if (occlude !== "blending") { raytraceTarget = [scene]; } } const previouslyVisible = visible.current; if (raytraceTarget) { const isvisible = isObjectVisible(group.current, camera, raycaster, raytraceTarget); visible.current = isvisible && !isBehindCamera; } else { visible.current = !isBehindCamera; } if (previouslyVisible !== visible.current) { if (onOcclude) onOcclude(!visible.current); else el.style.display = visible.current ? "block" : "none"; } const halfRange = Math.floor(zIndexRange[0] / 2); const zRange = occlude ? isRayCastOcclusion ? [zIndexRange[0], halfRange] : [halfRange - 1, 0] : zIndexRange; el.style.zIndex = `${objectZIndex(group.current, camera, zRange)}`; if (transform) { const [widthHalf, heightHalf] = [size2.width / 2, size2.height / 2]; const fov = camera.projectionMatrix.elements[5] * heightHalf; const { isOrthographicCamera: isOrthographicCamera3, top, left, bottom, right } = camera; const cameraMatrix = getCameraCSSMatrix(camera.matrixWorldInverse); const cameraTransform = isOrthographicCamera3 ? `scale(${fov})translate(${epsilon(-(right + left) / 2)}px,${epsilon((top + bottom) / 2)}px)` : `translateZ(${fov}px)`; let matrix6 = group.current.matrixWorld; if (sprite) { matrix6 = camera.matrixWorldInverse.clone().transpose().copyPosition(matrix6).scale(group.current.scale); matrix6.elements[3] = matrix6.elements[7] = matrix6.elements[11] = 0; matrix6.elements[15] = 1; } el.style.width = size2.width + "px"; el.style.height = size2.height + "px"; el.style.perspective = isOrthographicCamera3 ? "" : `${fov}px`; if (transformOuterRef.current && transformInnerRef.current) { transformOuterRef.current.style.transform = `${cameraTransform}${cameraMatrix}translate(${widthHalf}px,${heightHalf}px)`; transformInnerRef.current.style.transform = getObjectCSSMatrix(matrix6, 1 / ((distanceFactor || 10) / 400)); } } else { const scale5 = distanceFactor === void 0 ? 1 : objectScale(group.current, camera) * distanceFactor; el.style.transform = `translate3d(${vec[0]}px,${vec[1]}px,0) scale(${scale5})`; } oldPosition.current = vec; oldZoom.current = camera.zoom; } } if (!isRayCastOcclusion && occlusionMeshRef.current && !isMeshSizeSet.current) { if (transform) { if (transformOuterRef.current) { const el2 = transformOuterRef.current.children[0]; if (el2 != null && el2.clientWidth && el2 != null && el2.clientHeight) { const { isOrthographicCamera: isOrthographicCamera3 } = camera; if (isOrthographicCamera3 || geometry3) { if (props.scale) { if (!Array.isArray(props.scale)) { occlusionMeshRef.current.scale.setScalar(1 / props.scale); } else if (props.scale instanceof Vector3) { occlusionMeshRef.current.scale.copy(props.scale.clone().divideScalar(1)); } else { occlusionMeshRef.current.scale.set(1 / props.scale[0], 1 / props.scale[1], 1 / props.scale[2]); } } } else { const ratio = (distanceFactor || 10) / 400; const w = el2.clientWidth * ratio; const h = el2.clientHeight * ratio; occlusionMeshRef.current.scale.set(w, h, 1); } isMeshSizeSet.current = true; } } } else { const ele = el.children[0]; if (ele != null && ele.clientWidth && ele != null && ele.clientHeight) { const ratio = 1 / viewport.factor; const w = ele.clientWidth * ratio; const h = ele.clientHeight * ratio; occlusionMeshRef.current.scale.set(w, h, 1); isMeshSizeSet.current = true; } occlusionMeshRef.current.lookAt(gl2.camera.position); } } }); const shaders = React.useMemo(() => ({ vertexShader: !transform ? ( /* glsl */ ` /* This shader is from the THREE's SpriteMaterial. We need to turn the backing plane into a Sprite (make it always face the camera) if "transfrom" is false. */ #include void main() { vec2 center = vec2(0., 1.); float rotation = 0.0; // This is somewhat arbitrary, but it seems to work well // Need to figure out how to derive this dynamically if it even matters float size = 0.03; vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ); vec2 scale; scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) ); scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) ); bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale * size; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; } ` ) : void 0, fragmentShader: ( /* glsl */ ` void main() { gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); } ` ) }), [transform]); return React.createElement("group", _extends({}, props, { ref: group }), occlude && !isRayCastOcclusion && React.createElement("mesh", { castShadow, receiveShadow, ref: occlusionMeshRef }, geometry3 || React.createElement("planeGeometry", null), material || React.createElement("shaderMaterial", { side: DoubleSide, vertexShader: shaders.vertexShader, fragmentShader: shaders.fragmentShader }))); }); // node_modules/@react-three/drei/web/CycleRaycast.js var React2 = __toESM(require_react()); function CycleRaycast({ onChanged, portal, preventDefault = true, scroll = true, keyCode = 9 }) { const cycle = React2.useRef(0); const setEvents = useThree((state) => state.setEvents); const get = useThree((state) => state.get); const gl = useThree((state) => state.gl); React2.useEffect(() => { var _portal$current; let hits = []; let lastEvent = void 0; const prev = get().events.filter; const target2 = (_portal$current = portal == null ? void 0 : portal.current) !== null && _portal$current !== void 0 ? _portal$current : gl.domElement.parentNode; const renderStatus = () => target2 && onChanged && onChanged(hits, Math.round(cycle.current) % hits.length); setEvents({ filter: (intersections, state) => { let clone2 = [...intersections]; if (clone2.length !== hits.length || !hits.every((hit) => clone2.map((e2) => e2.object.uuid).includes(hit.object.uuid))) { cycle.current = 0; hits = clone2; renderStatus(); } if (prev) clone2 = prev(clone2, state); for (let i4 = 0; i4 < Math.round(cycle.current) % clone2.length; i4++) { const first2 = clone2.shift(); clone2 = [...clone2, first2]; } return clone2; } }); const refresh = (fn) => { var _get$events$handlers, _get$events$handlers2; cycle.current = fn(cycle.current); (_get$events$handlers = get().events.handlers) == null || _get$events$handlers.onPointerCancel(void 0); (_get$events$handlers2 = get().events.handlers) == null || _get$events$handlers2.onPointerMove(lastEvent); renderStatus(); }; const tabEvent = (event) => { if ((event.keyCode || event.which) === keyCode) { if (preventDefault) event.preventDefault(); if (hits.length > 1) refresh((current) => current + 1); } }; const wheelEvent = (event) => { if (preventDefault) event.preventDefault(); let delta = 0; if (!event) event = window.event; if (event.wheelDelta) delta = event.wheelDelta / 120; else if (event.detail) delta = -event.detail / 3; if (hits.length > 1) refresh((current) => Math.abs(current - delta)); }; const moveEvent = (event) => lastEvent = event; document.addEventListener("pointermove", moveEvent, { passive: true }); if (scroll) document.addEventListener("wheel", wheelEvent); if (keyCode !== void 0) document.addEventListener("keydown", tabEvent); return () => { setEvents({ filter: prev }); if (keyCode !== void 0) document.removeEventListener("keydown", tabEvent); if (scroll) document.removeEventListener("wheel", wheelEvent); document.removeEventListener("pointermove", moveEvent); }; }, [gl, get, setEvents, preventDefault, scroll, keyCode]); return null; } // node_modules/@react-three/drei/web/useCursor.js var React3 = __toESM(require_react()); function useCursor(hovered, onPointerOver = "pointer", onPointerOut = "auto", container = document.body) { React3.useEffect(() => { if (hovered) { container.style.cursor = onPointerOver; return () => void (container.style.cursor = onPointerOut); } }, [hovered]); } // node_modules/@react-three/drei/web/Loader.js var React5 = __toESM(require_react()); // node_modules/@react-three/drei/core/Progress.js var React4 = __toESM(require_react()); var saveLastTotalLoaded = 0; var useProgress = create((set) => { DefaultLoadingManager.onStart = (item, loaded, total) => { set({ active: true, item, loaded, total, progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 }); }; DefaultLoadingManager.onLoad = () => { set({ active: false }); }; DefaultLoadingManager.onError = (item) => set((state) => ({ errors: [...state.errors, item] })); DefaultLoadingManager.onProgress = (item, loaded, total) => { if (loaded === total) { saveLastTotalLoaded = total; } set({ active: true, item, loaded, total, progress: (loaded - saveLastTotalLoaded) / (total - saveLastTotalLoaded) * 100 || 100 }); }; return { errors: [], active: false, progress: 0, item: "", loaded: 0, total: 0 }; }); function Progress({ children }) { const result = useProgress(); return React4.createElement(React4.Fragment, null, children == null ? void 0 : children(result)); } // node_modules/@react-three/drei/web/Loader.js var defaultDataInterpolation = (p2) => `Loading ${p2.toFixed(2)}%`; function Loader2({ containerStyles, innerStyles, barStyles, dataStyles, dataInterpolation = defaultDataInterpolation, initialState = (active) => active }) { const { active, progress } = useProgress(); const progressRef = React5.useRef(0); const rafRef = React5.useRef(0); const progressSpanRef = React5.useRef(null); const [shown, setShown] = React5.useState(initialState(active)); React5.useEffect(() => { let t3; if (active !== shown) t3 = setTimeout(() => setShown(active), 300); return () => clearTimeout(t3); }, [shown, active]); const updateProgress = React5.useCallback(() => { if (!progressSpanRef.current) return; progressRef.current += (progress - progressRef.current) / 2; if (progressRef.current > 0.95 * progress || progress === 100) progressRef.current = progress; progressSpanRef.current.innerText = dataInterpolation(progressRef.current); if (progressRef.current < progress) rafRef.current = requestAnimationFrame(updateProgress); }, [dataInterpolation, progress]); React5.useEffect(() => { updateProgress(); return () => cancelAnimationFrame(rafRef.current); }, [updateProgress]); return shown ? React5.createElement("div", { style: { ...styles.container, opacity: active ? 1 : 0, ...containerStyles } }, React5.createElement("div", null, React5.createElement("div", { style: { ...styles.inner, ...innerStyles } }, React5.createElement("div", { style: { ...styles.bar, transform: `scaleX(${progress / 100})`, ...barStyles } }), React5.createElement("span", { ref: progressSpanRef, style: { ...styles.data, ...dataStyles } })))) : null; } var styles = { container: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%", background: "#171717", display: "flex", alignItems: "center", justifyContent: "center", transition: "opacity 300ms ease", zIndex: 1e3 }, inner: { width: 100, height: 3, background: "#272727", textAlign: "center" }, bar: { height: 3, width: "100%", background: "white", transition: "transform 200ms", transformOrigin: "left center" }, data: { display: "inline-block", position: "relative", fontVariantNumeric: "tabular-nums", marginTop: "0.8em", color: "#f0f0f0", fontSize: "0.6em", fontFamily: `-apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Helvetica Neue", Helvetica, Arial, Roboto, Ubuntu, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"`, whiteSpace: "nowrap" } }; // node_modules/@react-three/drei/web/DragControls.js var React7 = __toESM(require_react()); // node_modules/@use-gesture/core/dist/maths-0ab39ae9.esm.js function clamp(v5, min, max2) { return Math.max(min, Math.min(v5, max2)); } var V = { toVector(v5, fallback) { if (v5 === void 0) v5 = fallback; return Array.isArray(v5) ? v5 : [v5, v5]; }, add(v13, v22) { return [v13[0] + v22[0], v13[1] + v22[1]]; }, sub(v13, v22) { return [v13[0] - v22[0], v13[1] - v22[1]]; }, addTo(v13, v22) { v13[0] += v22[0]; v13[1] += v22[1]; }, subTo(v13, v22) { v13[0] -= v22[0]; v13[1] -= v22[1]; } }; function rubberband(distance3, dimension, constant) { if (dimension === 0 || Math.abs(dimension) === Infinity) return Math.pow(distance3, constant * 5); return distance3 * dimension * constant / (dimension + constant * distance3); } function rubberbandIfOutOfBounds(position2, min, max2, constant = 0.15) { if (constant === 0) return clamp(position2, min, max2); if (position2 < min) return -rubberband(min - position2, max2 - min, constant) + min; if (position2 > max2) return +rubberband(position2 - max2, max2 - min, constant) + max2; return position2; } function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) { const [[X0, X1], [Y0, Y1]] = bounds; return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)]; } // node_modules/@use-gesture/core/dist/actions-fe213e88.esm.js function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== void 0) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(e2, r2) { var t3 = Object.keys(e2); if (Object.getOwnPropertySymbols) { var o2 = Object.getOwnPropertySymbols(e2); r2 && (o2 = o2.filter(function(r3) { return Object.getOwnPropertyDescriptor(e2, r3).enumerable; })), t3.push.apply(t3, o2); } return t3; } function _objectSpread2(e2) { for (var r2 = 1; r2 < arguments.length; r2++) { var t3 = null != arguments[r2] ? arguments[r2] : {}; r2 % 2 ? ownKeys(Object(t3), true).forEach(function(r3) { _defineProperty(e2, r3, t3[r3]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t3)) : ownKeys(Object(t3)).forEach(function(r3) { Object.defineProperty(e2, r3, Object.getOwnPropertyDescriptor(t3, r3)); }); } return e2; } var EVENT_TYPE_MAP = { pointer: { start: "down", change: "move", end: "up" }, mouse: { start: "down", change: "move", end: "up" }, touch: { start: "start", change: "move", end: "end" }, gesture: { start: "start", change: "change", end: "end" } }; function capitalize(string) { if (!string) return ""; return string[0].toUpperCase() + string.slice(1); } var actionsWithoutCaptureSupported = ["enter", "leave"]; function hasCapture(capture = false, actionKey) { return capture && !actionsWithoutCaptureSupported.includes(actionKey); } function toHandlerProp(device, action = "", capture = false) { const deviceProps = EVENT_TYPE_MAP[device]; const actionKey = deviceProps ? deviceProps[action] || action : action; return "on" + capitalize(device) + capitalize(actionKey) + (hasCapture(capture, actionKey) ? "Capture" : ""); } var pointerCaptureEvents = ["gotpointercapture", "lostpointercapture"]; function parseProp(prop) { let eventKey = prop.substring(2).toLowerCase(); const passive = !!~eventKey.indexOf("passive"); if (passive) eventKey = eventKey.replace("passive", ""); const captureKey = pointerCaptureEvents.includes(eventKey) ? "capturecapture" : "capture"; const capture = !!~eventKey.indexOf(captureKey); if (capture) eventKey = eventKey.replace("capture", ""); return { device: eventKey, capture, passive }; } function toDomEventType(device, action = "") { const deviceProps = EVENT_TYPE_MAP[device]; const actionKey = deviceProps ? deviceProps[action] || action : action; return device + actionKey; } function isTouch(event) { return "touches" in event; } function getPointerType(event) { if (isTouch(event)) return "touch"; if ("pointerType" in event) return event.pointerType; return "mouse"; } function getCurrentTargetTouchList(event) { return Array.from(event.touches).filter((e2) => { var _event$currentTarget, _event$currentTarget$; return e2.target === event.currentTarget || ((_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 || (_event$currentTarget$ = _event$currentTarget.contains) === null || _event$currentTarget$ === void 0 ? void 0 : _event$currentTarget$.call(_event$currentTarget, e2.target)); }); } function getTouchList(event) { return event.type === "touchend" || event.type === "touchcancel" ? event.changedTouches : event.targetTouches; } function getValueEvent(event) { return isTouch(event) ? getTouchList(event)[0] : event; } function distanceAngle(P1, P2) { try { const dx = P2.clientX - P1.clientX; const dy = P2.clientY - P1.clientY; const cx = (P2.clientX + P1.clientX) / 2; const cy = (P2.clientY + P1.clientY) / 2; const distance3 = Math.hypot(dx, dy); const angle = -(Math.atan2(dx, dy) * 180) / Math.PI; const origin2 = [cx, cy]; return { angle, distance: distance3, origin: origin2 }; } catch (_unused) { } return null; } function touchIds(event) { return getCurrentTargetTouchList(event).map((touch) => touch.identifier); } function touchDistanceAngle(event, ids) { const [P1, P2] = Array.from(event.touches).filter((touch) => ids.includes(touch.identifier)); return distanceAngle(P1, P2); } function pointerId(event) { const valueEvent = getValueEvent(event); return isTouch(event) ? valueEvent.identifier : valueEvent.pointerId; } function pointerValues(event) { const valueEvent = getValueEvent(event); return [valueEvent.clientX, valueEvent.clientY]; } var LINE_HEIGHT = 40; var PAGE_HEIGHT = 800; function wheelValues(event) { let { deltaX, deltaY, deltaMode } = event; if (deltaMode === 1) { deltaX *= LINE_HEIGHT; deltaY *= LINE_HEIGHT; } else if (deltaMode === 2) { deltaX *= PAGE_HEIGHT; deltaY *= PAGE_HEIGHT; } return [deltaX, deltaY]; } function scrollValues(event) { var _ref, _ref2; const { scrollX, scrollY, scrollLeft, scrollTop } = event.currentTarget; return [(_ref = scrollX !== null && scrollX !== void 0 ? scrollX : scrollLeft) !== null && _ref !== void 0 ? _ref : 0, (_ref2 = scrollY !== null && scrollY !== void 0 ? scrollY : scrollTop) !== null && _ref2 !== void 0 ? _ref2 : 0]; } function getEventDetails(event) { const payload = {}; if ("buttons" in event) payload.buttons = event.buttons; if ("shiftKey" in event) { const { shiftKey, altKey, metaKey, ctrlKey } = event; Object.assign(payload, { shiftKey, altKey, metaKey, ctrlKey }); } return payload; } function call(v5, ...args) { if (typeof v5 === "function") { return v5(...args); } else { return v5; } } function noop() { } function chain(...fns) { if (fns.length === 0) return noop; if (fns.length === 1) return fns[0]; return function() { let result; for (const fn of fns) { result = fn.apply(this, arguments) || result; } return result; }; } function assignDefault(value, fallback) { return Object.assign({}, fallback, value || {}); } var BEFORE_LAST_KINEMATICS_DELAY = 32; var Engine = class { constructor(ctrl, args, key) { this.ctrl = ctrl; this.args = args; this.key = key; if (!this.state) { this.state = {}; this.computeValues([0, 0]); this.computeInitial(); if (this.init) this.init(); this.reset(); } } get state() { return this.ctrl.state[this.key]; } set state(state) { this.ctrl.state[this.key] = state; } get shared() { return this.ctrl.state.shared; } get eventStore() { return this.ctrl.gestureEventStores[this.key]; } get timeoutStore() { return this.ctrl.gestureTimeoutStores[this.key]; } get config() { return this.ctrl.config[this.key]; } get sharedConfig() { return this.ctrl.config.shared; } get handler() { return this.ctrl.handlers[this.key]; } reset() { const { state, shared, ingKey, args } = this; shared[ingKey] = state._active = state.active = state._blocked = state._force = false; state._step = [false, false]; state.intentional = false; state._movement = [0, 0]; state._distance = [0, 0]; state._direction = [0, 0]; state._delta = [0, 0]; state._bounds = [[-Infinity, Infinity], [-Infinity, Infinity]]; state.args = args; state.axis = void 0; state.memo = void 0; state.elapsedTime = state.timeDelta = 0; state.direction = [0, 0]; state.distance = [0, 0]; state.overflow = [0, 0]; state._movementBound = [false, false]; state.velocity = [0, 0]; state.movement = [0, 0]; state.delta = [0, 0]; state.timeStamp = 0; } start(event) { const state = this.state; const config = this.config; if (!state._active) { this.reset(); this.computeInitial(); state._active = true; state.target = event.target; state.currentTarget = event.currentTarget; state.lastOffset = config.from ? call(config.from, state) : state.offset; state.offset = state.lastOffset; state.startTime = state.timeStamp = event.timeStamp; } } computeValues(values) { const state = this.state; state._values = values; state.values = this.config.transform(values); } computeInitial() { const state = this.state; state._initial = state._values; state.initial = state.values; } compute(event) { const { state, config, shared } = this; state.args = this.args; let dt = 0; if (event) { state.event = event; if (config.preventDefault && event.cancelable) state.event.preventDefault(); state.type = event.type; shared.touches = this.ctrl.pointerIds.size || this.ctrl.touchIds.size; shared.locked = !!document.pointerLockElement; Object.assign(shared, getEventDetails(event)); shared.down = shared.pressed = shared.buttons % 2 === 1 || shared.touches > 0; dt = event.timeStamp - state.timeStamp; state.timeStamp = event.timeStamp; state.elapsedTime = state.timeStamp - state.startTime; } if (state._active) { const _absoluteDelta = state._delta.map(Math.abs); V.addTo(state._distance, _absoluteDelta); } if (this.axisIntent) this.axisIntent(event); const [_m0, _m13] = state._movement; const [t0, t1] = config.threshold; const { _step, values } = state; if (config.hasCustomTransform) { if (_step[0] === false) _step[0] = Math.abs(_m0) >= t0 && values[0]; if (_step[1] === false) _step[1] = Math.abs(_m13) >= t1 && values[1]; } else { if (_step[0] === false) _step[0] = Math.abs(_m0) >= t0 && Math.sign(_m0) * t0; if (_step[1] === false) _step[1] = Math.abs(_m13) >= t1 && Math.sign(_m13) * t1; } state.intentional = _step[0] !== false || _step[1] !== false; if (!state.intentional) return; const movement = [0, 0]; if (config.hasCustomTransform) { const [v0, v13] = values; movement[0] = _step[0] !== false ? v0 - _step[0] : 0; movement[1] = _step[1] !== false ? v13 - _step[1] : 0; } else { movement[0] = _step[0] !== false ? _m0 - _step[0] : 0; movement[1] = _step[1] !== false ? _m13 - _step[1] : 0; } if (this.restrictToAxis && !state._blocked) this.restrictToAxis(movement); const previousOffset = state.offset; const gestureIsActive = state._active && !state._blocked || state.active; if (gestureIsActive) { state.first = state._active && !state.active; state.last = !state._active && state.active; state.active = shared[this.ingKey] = state._active; if (event) { if (state.first) { if ("bounds" in config) state._bounds = call(config.bounds, state); if (this.setup) this.setup(); } state.movement = movement; this.computeOffset(); } } const [ox, oy] = state.offset; const [[x0, x1], [y0, y1]] = state._bounds; state.overflow = [ox < x0 ? -1 : ox > x1 ? 1 : 0, oy < y0 ? -1 : oy > y1 ? 1 : 0]; state._movementBound[0] = state.overflow[0] ? state._movementBound[0] === false ? state._movement[0] : state._movementBound[0] : false; state._movementBound[1] = state.overflow[1] ? state._movementBound[1] === false ? state._movement[1] : state._movementBound[1] : false; const rubberband2 = state._active ? config.rubberband || [0, 0] : [0, 0]; state.offset = computeRubberband(state._bounds, state.offset, rubberband2); state.delta = V.sub(state.offset, previousOffset); this.computeMovement(); if (gestureIsActive && (!state.last || dt > BEFORE_LAST_KINEMATICS_DELAY)) { state.delta = V.sub(state.offset, previousOffset); const absoluteDelta = state.delta.map(Math.abs); V.addTo(state.distance, absoluteDelta); state.direction = state.delta.map(Math.sign); state._direction = state._delta.map(Math.sign); if (!state.first && dt > 0) { state.velocity = [absoluteDelta[0] / dt, absoluteDelta[1] / dt]; state.timeDelta = dt; } } } emit() { const state = this.state; const shared = this.shared; const config = this.config; if (!state._active) this.clean(); if ((state._blocked || !state.intentional) && !state._force && !config.triggerAllEvents) return; const memo = this.handler(_objectSpread2(_objectSpread2(_objectSpread2({}, shared), state), {}, { [this.aliasKey]: state.values })); if (memo !== void 0) state.memo = memo; } clean() { this.eventStore.clean(); this.timeoutStore.clean(); } }; function selectAxis([dx, dy], threshold) { const absDx = Math.abs(dx); const absDy = Math.abs(dy); if (absDx > absDy && absDx > threshold) { return "x"; } if (absDy > absDx && absDy > threshold) { return "y"; } return void 0; } var CoordinatesEngine = class extends Engine { constructor(...args) { super(...args); _defineProperty(this, "aliasKey", "xy"); } reset() { super.reset(); this.state.axis = void 0; } init() { this.state.offset = [0, 0]; this.state.lastOffset = [0, 0]; } computeOffset() { this.state.offset = V.add(this.state.lastOffset, this.state.movement); } computeMovement() { this.state.movement = V.sub(this.state.offset, this.state.lastOffset); } axisIntent(event) { const state = this.state; const config = this.config; if (!state.axis && event) { const threshold = typeof config.axisThreshold === "object" ? config.axisThreshold[getPointerType(event)] : config.axisThreshold; state.axis = selectAxis(state._movement, threshold); } state._blocked = (config.lockDirection || !!config.axis) && !state.axis || !!config.axis && config.axis !== state.axis; } restrictToAxis(v5) { if (this.config.axis || this.config.lockDirection) { switch (this.state.axis) { case "x": v5[1] = 0; break; case "y": v5[0] = 0; break; } } } }; var identity = (v5) => v5; var DEFAULT_RUBBERBAND = 0.15; var commonConfigResolver = { enabled(value = true) { return value; }, eventOptions(value, _k, config) { return _objectSpread2(_objectSpread2({}, config.shared.eventOptions), value); }, preventDefault(value = false) { return value; }, triggerAllEvents(value = false) { return value; }, rubberband(value = 0) { switch (value) { case true: return [DEFAULT_RUBBERBAND, DEFAULT_RUBBERBAND]; case false: return [0, 0]; default: return V.toVector(value); } }, from(value) { if (typeof value === "function") return value; if (value != null) return V.toVector(value); }, transform(value, _k, config) { const transform = value || config.shared.transform; this.hasCustomTransform = !!transform; if (true) { const originalTransform = transform || identity; return (v5) => { const r2 = originalTransform(v5); if (!isFinite(r2[0]) || !isFinite(r2[1])) { console.warn(`[@use-gesture]: config.transform() must produce a valid result, but it was: [${r2[0]},${[1]}]`); } return r2; }; } return transform || identity; }, threshold(value) { return V.toVector(value, 0); } }; if (true) { Object.assign(commonConfigResolver, { domTarget(value) { if (value !== void 0) { throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`); } return NaN; }, lockDirection(value) { if (value !== void 0) { throw Error(`[@use-gesture]: \`lockDirection\` option has been merged with \`axis\`. Use it as in \`{ axis: 'lock' }\``); } return NaN; }, initial(value) { if (value !== void 0) { throw Error(`[@use-gesture]: \`initial\` option has been renamed to \`from\`.`); } return NaN; } }); } var DEFAULT_AXIS_THRESHOLD = 0; var coordinatesConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { axis(_v4, _k, { axis }) { this.lockDirection = axis === "lock"; if (!this.lockDirection) return axis; }, axisThreshold(value = DEFAULT_AXIS_THRESHOLD) { return value; }, bounds(value = {}) { if (typeof value === "function") { return (state) => coordinatesConfigResolver.bounds(value(state)); } if ("current" in value) { return () => value.current; } if (typeof HTMLElement === "function" && value instanceof HTMLElement) { return value; } const { left = -Infinity, right = Infinity, top = -Infinity, bottom = Infinity } = value; return [[left, right], [top, bottom]]; } }); var KEYS_DELTA_MAP = { ArrowRight: (displacement, factor = 1) => [displacement * factor, 0], ArrowLeft: (displacement, factor = 1) => [-1 * displacement * factor, 0], ArrowUp: (displacement, factor = 1) => [0, -1 * displacement * factor], ArrowDown: (displacement, factor = 1) => [0, displacement * factor] }; var DragEngine = class extends CoordinatesEngine { constructor(...args) { super(...args); _defineProperty(this, "ingKey", "dragging"); } reset() { super.reset(); const state = this.state; state._pointerId = void 0; state._pointerActive = false; state._keyboardActive = false; state._preventScroll = false; state._delayed = false; state.swipe = [0, 0]; state.tap = false; state.canceled = false; state.cancel = this.cancel.bind(this); } setup() { const state = this.state; if (state._bounds instanceof HTMLElement) { const boundRect = state._bounds.getBoundingClientRect(); const targetRect = state.currentTarget.getBoundingClientRect(); const _bounds = { left: boundRect.left - targetRect.left + state.offset[0], right: boundRect.right - targetRect.right + state.offset[0], top: boundRect.top - targetRect.top + state.offset[1], bottom: boundRect.bottom - targetRect.bottom + state.offset[1] }; state._bounds = coordinatesConfigResolver.bounds(_bounds); } } cancel() { const state = this.state; if (state.canceled) return; state.canceled = true; state._active = false; setTimeout(() => { this.compute(); this.emit(); }, 0); } setActive() { this.state._active = this.state._pointerActive || this.state._keyboardActive; } clean() { this.pointerClean(); this.state._pointerActive = false; this.state._keyboardActive = false; super.clean(); } pointerDown(event) { const config = this.config; const state = this.state; if (event.buttons != null && (Array.isArray(config.pointerButtons) ? !config.pointerButtons.includes(event.buttons) : config.pointerButtons !== -1 && config.pointerButtons !== event.buttons)) return; const ctrlIds = this.ctrl.setEventIds(event); if (config.pointerCapture) { event.target.setPointerCapture(event.pointerId); } if (ctrlIds && ctrlIds.size > 1 && state._pointerActive) return; this.start(event); this.setupPointer(event); state._pointerId = pointerId(event); state._pointerActive = true; this.computeValues(pointerValues(event)); this.computeInitial(); if (config.preventScrollAxis && getPointerType(event) !== "mouse") { state._active = false; this.setupScrollPrevention(event); } else if (config.delay > 0) { this.setupDelayTrigger(event); if (config.triggerAllEvents) { this.compute(event); this.emit(); } } else { this.startPointerDrag(event); } } startPointerDrag(event) { const state = this.state; state._active = true; state._preventScroll = true; state._delayed = false; this.compute(event); this.emit(); } pointerMove(event) { const state = this.state; const config = this.config; if (!state._pointerActive) return; const id = pointerId(event); if (state._pointerId !== void 0 && id !== state._pointerId) return; const _values = pointerValues(event); if (document.pointerLockElement === event.target) { state._delta = [event.movementX, event.movementY]; } else { state._delta = V.sub(_values, state._values); this.computeValues(_values); } V.addTo(state._movement, state._delta); this.compute(event); if (state._delayed && state.intentional) { this.timeoutStore.remove("dragDelay"); state.active = false; this.startPointerDrag(event); return; } if (config.preventScrollAxis && !state._preventScroll) { if (state.axis) { if (state.axis === config.preventScrollAxis || config.preventScrollAxis === "xy") { state._active = false; this.clean(); return; } else { this.timeoutStore.remove("startPointerDrag"); this.startPointerDrag(event); return; } } else { return; } } this.emit(); } pointerUp(event) { this.ctrl.setEventIds(event); try { if (this.config.pointerCapture && event.target.hasPointerCapture(event.pointerId)) { ; event.target.releasePointerCapture(event.pointerId); } } catch (_unused) { if (true) { console.warn(`[@use-gesture]: If you see this message, it's likely that you're using an outdated version of \`@react-three/fiber\`. Please upgrade to the latest version.`); } } const state = this.state; const config = this.config; if (!state._active || !state._pointerActive) return; const id = pointerId(event); if (state._pointerId !== void 0 && id !== state._pointerId) return; this.state._pointerActive = false; this.setActive(); this.compute(event); const [dx, dy] = state._distance; state.tap = dx <= config.tapsThreshold && dy <= config.tapsThreshold; if (state.tap && config.filterTaps) { state._force = true; } else { const [_dx, _dy] = state._delta; const [_mx, _my] = state._movement; const [svx, svy] = config.swipe.velocity; const [sx, sy] = config.swipe.distance; const sdt = config.swipe.duration; if (state.elapsedTime < sdt) { const _vx = Math.abs(_dx / state.timeDelta); const _vy = Math.abs(_dy / state.timeDelta); if (_vx > svx && Math.abs(_mx) > sx) state.swipe[0] = Math.sign(_dx); if (_vy > svy && Math.abs(_my) > sy) state.swipe[1] = Math.sign(_dy); } } this.emit(); } pointerClick(event) { if (!this.state.tap && event.detail > 0) { event.preventDefault(); event.stopPropagation(); } } setupPointer(event) { const config = this.config; const device = config.device; if (true) { try { if (device === "pointer" && config.preventScrollDelay === void 0) { const currentTarget = "uv" in event ? event.sourceEvent.currentTarget : event.currentTarget; const style = window.getComputedStyle(currentTarget); if (style.touchAction === "auto") { console.warn(`[@use-gesture]: The drag target has its \`touch-action\` style property set to \`auto\`. It is recommended to add \`touch-action: 'none'\` so that the drag gesture behaves correctly on touch-enabled devices. For more information read this: https://use-gesture.netlify.app/docs/extras/#touch-action. This message will only show in development mode. It won't appear in production. If this is intended, you can ignore it.`, currentTarget); } } } catch (_unused2) { } } if (config.pointerLock) { event.currentTarget.requestPointerLock(); } if (!config.pointerCapture) { this.eventStore.add(this.sharedConfig.window, device, "change", this.pointerMove.bind(this)); this.eventStore.add(this.sharedConfig.window, device, "end", this.pointerUp.bind(this)); this.eventStore.add(this.sharedConfig.window, device, "cancel", this.pointerUp.bind(this)); } } pointerClean() { if (this.config.pointerLock && document.pointerLockElement === this.state.currentTarget) { document.exitPointerLock(); } } preventScroll(event) { if (this.state._preventScroll && event.cancelable) { event.preventDefault(); } } setupScrollPrevention(event) { this.state._preventScroll = false; persistEvent(event); const remove = this.eventStore.add(this.sharedConfig.window, "touch", "change", this.preventScroll.bind(this), { passive: false }); this.eventStore.add(this.sharedConfig.window, "touch", "end", remove); this.eventStore.add(this.sharedConfig.window, "touch", "cancel", remove); this.timeoutStore.add("startPointerDrag", this.startPointerDrag.bind(this), this.config.preventScrollDelay, event); } setupDelayTrigger(event) { this.state._delayed = true; this.timeoutStore.add("dragDelay", () => { this.state._step = [0, 0]; this.startPointerDrag(event); }, this.config.delay); } keyDown(event) { const deltaFn = KEYS_DELTA_MAP[event.key]; if (deltaFn) { const state = this.state; const factor = event.shiftKey ? 10 : event.altKey ? 0.1 : 1; this.start(event); state._delta = deltaFn(this.config.keyboardDisplacement, factor); state._keyboardActive = true; V.addTo(state._movement, state._delta); this.compute(event); this.emit(); } } keyUp(event) { if (!(event.key in KEYS_DELTA_MAP)) return; this.state._keyboardActive = false; this.setActive(); this.compute(event); this.emit(); } bind(bindFunction) { const device = this.config.device; bindFunction(device, "start", this.pointerDown.bind(this)); if (this.config.pointerCapture) { bindFunction(device, "change", this.pointerMove.bind(this)); bindFunction(device, "end", this.pointerUp.bind(this)); bindFunction(device, "cancel", this.pointerUp.bind(this)); bindFunction("lostPointerCapture", "", this.pointerUp.bind(this)); } if (this.config.keys) { bindFunction("key", "down", this.keyDown.bind(this)); bindFunction("key", "up", this.keyUp.bind(this)); } if (this.config.filterTaps) { bindFunction("click", "", this.pointerClick.bind(this), { capture: true, passive: false }); } } }; function persistEvent(event) { "persist" in event && typeof event.persist === "function" && event.persist(); } var isBrowser = typeof window !== "undefined" && window.document && window.document.createElement; function supportsTouchEvents() { return isBrowser && "ontouchstart" in window; } function isTouchScreen() { return supportsTouchEvents() || isBrowser && window.navigator.maxTouchPoints > 1; } function supportsPointerEvents() { return isBrowser && "onpointerdown" in window; } function supportsPointerLock() { return isBrowser && "exitPointerLock" in window.document; } function supportsGestureEvents() { try { return "constructor" in GestureEvent; } catch (e2) { return false; } } var SUPPORT = { isBrowser, gesture: supportsGestureEvents(), touch: supportsTouchEvents(), touchscreen: isTouchScreen(), pointer: supportsPointerEvents(), pointerLock: supportsPointerLock() }; var DEFAULT_PREVENT_SCROLL_DELAY = 250; var DEFAULT_DRAG_DELAY = 180; var DEFAULT_SWIPE_VELOCITY = 0.5; var DEFAULT_SWIPE_DISTANCE = 50; var DEFAULT_SWIPE_DURATION = 250; var DEFAULT_KEYBOARD_DISPLACEMENT = 10; var DEFAULT_DRAG_AXIS_THRESHOLD = { mouse: 0, touch: 0, pen: 8 }; var dragConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { device(_v4, _k, { pointer: { touch = false, lock = false, mouse = false } = {} }) { this.pointerLock = lock && SUPPORT.pointerLock; if (SUPPORT.touch && touch) return "touch"; if (this.pointerLock) return "mouse"; if (SUPPORT.pointer && !mouse) return "pointer"; if (SUPPORT.touch) return "touch"; return "mouse"; }, preventScrollAxis(value, _k, { preventScroll }) { this.preventScrollDelay = typeof preventScroll === "number" ? preventScroll : preventScroll || preventScroll === void 0 && value ? DEFAULT_PREVENT_SCROLL_DELAY : void 0; if (!SUPPORT.touchscreen || preventScroll === false) return void 0; return value ? value : preventScroll !== void 0 ? "y" : void 0; }, pointerCapture(_v4, _k, { pointer: { capture = true, buttons = 1, keys = true } = {} }) { this.pointerButtons = buttons; this.keys = keys; return !this.pointerLock && this.device === "pointer" && capture; }, threshold(value, _k, { filterTaps = false, tapsThreshold = 3, axis = void 0 }) { const threshold = V.toVector(value, filterTaps ? tapsThreshold : axis ? 1 : 0); this.filterTaps = filterTaps; this.tapsThreshold = tapsThreshold; return threshold; }, swipe({ velocity = DEFAULT_SWIPE_VELOCITY, distance: distance3 = DEFAULT_SWIPE_DISTANCE, duration = DEFAULT_SWIPE_DURATION } = {}) { return { velocity: this.transform(V.toVector(velocity)), distance: this.transform(V.toVector(distance3)), duration }; }, delay(value = 0) { switch (value) { case true: return DEFAULT_DRAG_DELAY; case false: return 0; default: return value; } }, axisThreshold(value) { if (!value) return DEFAULT_DRAG_AXIS_THRESHOLD; return _objectSpread2(_objectSpread2({}, DEFAULT_DRAG_AXIS_THRESHOLD), value); }, keyboardDisplacement(value = DEFAULT_KEYBOARD_DISPLACEMENT) { return value; } }); if (true) { Object.assign(dragConfigResolver, { useTouch(value) { if (value !== void 0) { throw Error(`[@use-gesture]: \`useTouch\` option has been renamed to \`pointer.touch\`. Use it as in \`{ pointer: { touch: true } }\`.`); } return NaN; }, experimental_preventWindowScrollY(value) { if (value !== void 0) { throw Error(`[@use-gesture]: \`experimental_preventWindowScrollY\` option has been renamed to \`preventScroll\`.`); } return NaN; }, swipeVelocity(value) { if (value !== void 0) { throw Error(`[@use-gesture]: \`swipeVelocity\` option has been renamed to \`swipe.velocity\`. Use it as in \`{ swipe: { velocity: 0.5 } }\`.`); } return NaN; }, swipeDistance(value) { if (value !== void 0) { throw Error(`[@use-gesture]: \`swipeDistance\` option has been renamed to \`swipe.distance\`. Use it as in \`{ swipe: { distance: 50 } }\`.`); } return NaN; }, swipeDuration(value) { if (value !== void 0) { throw Error(`[@use-gesture]: \`swipeDuration\` option has been renamed to \`swipe.duration\`. Use it as in \`{ swipe: { duration: 250 } }\`.`); } return NaN; } }); } function clampStateInternalMovementToBounds(state) { const [ox, oy] = state.overflow; const [dx, dy] = state._delta; const [dirx, diry] = state._direction; if (ox < 0 && dx > 0 && dirx < 0 || ox > 0 && dx < 0 && dirx > 0) { state._movement[0] = state._movementBound[0]; } if (oy < 0 && dy > 0 && diry < 0 || oy > 0 && dy < 0 && diry > 0) { state._movement[1] = state._movementBound[1]; } } var SCALE_ANGLE_RATIO_INTENT_DEG = 30; var PINCH_WHEEL_RATIO = 100; var PinchEngine = class extends Engine { constructor(...args) { super(...args); _defineProperty(this, "ingKey", "pinching"); _defineProperty(this, "aliasKey", "da"); } init() { this.state.offset = [1, 0]; this.state.lastOffset = [1, 0]; this.state._pointerEvents = /* @__PURE__ */ new Map(); } reset() { super.reset(); const state = this.state; state._touchIds = []; state.canceled = false; state.cancel = this.cancel.bind(this); state.turns = 0; } computeOffset() { const { type, movement, lastOffset } = this.state; if (type === "wheel") { this.state.offset = V.add(movement, lastOffset); } else { this.state.offset = [(1 + movement[0]) * lastOffset[0], movement[1] + lastOffset[1]]; } } computeMovement() { const { offset, lastOffset } = this.state; this.state.movement = [offset[0] / lastOffset[0], offset[1] - lastOffset[1]]; } axisIntent() { const state = this.state; const [_m0, _m13] = state._movement; if (!state.axis) { const axisMovementDifference = Math.abs(_m0) * SCALE_ANGLE_RATIO_INTENT_DEG - Math.abs(_m13); if (axisMovementDifference < 0) state.axis = "angle"; else if (axisMovementDifference > 0) state.axis = "scale"; } } restrictToAxis(v5) { if (this.config.lockDirection) { if (this.state.axis === "scale") v5[1] = 0; else if (this.state.axis === "angle") v5[0] = 0; } } cancel() { const state = this.state; if (state.canceled) return; setTimeout(() => { state.canceled = true; state._active = false; this.compute(); this.emit(); }, 0); } touchStart(event) { this.ctrl.setEventIds(event); const state = this.state; const ctrlTouchIds = this.ctrl.touchIds; if (state._active) { if (state._touchIds.every((id) => ctrlTouchIds.has(id))) return; } if (ctrlTouchIds.size < 2) return; this.start(event); state._touchIds = Array.from(ctrlTouchIds).slice(0, 2); const payload = touchDistanceAngle(event, state._touchIds); if (!payload) return; this.pinchStart(event, payload); } pointerStart(event) { if (event.buttons != null && event.buttons % 2 !== 1) return; this.ctrl.setEventIds(event); event.target.setPointerCapture(event.pointerId); const state = this.state; const _pointerEvents = state._pointerEvents; const ctrlPointerIds = this.ctrl.pointerIds; if (state._active) { if (Array.from(_pointerEvents.keys()).every((id) => ctrlPointerIds.has(id))) return; } if (_pointerEvents.size < 2) { _pointerEvents.set(event.pointerId, event); } if (state._pointerEvents.size < 2) return; this.start(event); const payload = distanceAngle(...Array.from(_pointerEvents.values())); if (!payload) return; this.pinchStart(event, payload); } pinchStart(event, payload) { const state = this.state; state.origin = payload.origin; this.computeValues([payload.distance, payload.angle]); this.computeInitial(); this.compute(event); this.emit(); } touchMove(event) { if (!this.state._active) return; const payload = touchDistanceAngle(event, this.state._touchIds); if (!payload) return; this.pinchMove(event, payload); } pointerMove(event) { const _pointerEvents = this.state._pointerEvents; if (_pointerEvents.has(event.pointerId)) { _pointerEvents.set(event.pointerId, event); } if (!this.state._active) return; const payload = distanceAngle(...Array.from(_pointerEvents.values())); if (!payload) return; this.pinchMove(event, payload); } pinchMove(event, payload) { const state = this.state; const prev_a = state._values[1]; const delta_a = payload.angle - prev_a; let delta_turns = 0; if (Math.abs(delta_a) > 270) delta_turns += Math.sign(delta_a); this.computeValues([payload.distance, payload.angle - 360 * delta_turns]); state.origin = payload.origin; state.turns = delta_turns; state._movement = [state._values[0] / state._initial[0] - 1, state._values[1] - state._initial[1]]; this.compute(event); this.emit(); } touchEnd(event) { this.ctrl.setEventIds(event); if (!this.state._active) return; if (this.state._touchIds.some((id) => !this.ctrl.touchIds.has(id))) { this.state._active = false; this.compute(event); this.emit(); } } pointerEnd(event) { const state = this.state; this.ctrl.setEventIds(event); try { event.target.releasePointerCapture(event.pointerId); } catch (_unused) { } if (state._pointerEvents.has(event.pointerId)) { state._pointerEvents.delete(event.pointerId); } if (!state._active) return; if (state._pointerEvents.size < 2) { state._active = false; this.compute(event); this.emit(); } } gestureStart(event) { if (event.cancelable) event.preventDefault(); const state = this.state; if (state._active) return; this.start(event); this.computeValues([event.scale, event.rotation]); state.origin = [event.clientX, event.clientY]; this.compute(event); this.emit(); } gestureMove(event) { if (event.cancelable) event.preventDefault(); if (!this.state._active) return; const state = this.state; this.computeValues([event.scale, event.rotation]); state.origin = [event.clientX, event.clientY]; const _previousMovement = state._movement; state._movement = [event.scale - 1, event.rotation]; state._delta = V.sub(state._movement, _previousMovement); this.compute(event); this.emit(); } gestureEnd(event) { if (!this.state._active) return; this.state._active = false; this.compute(event); this.emit(); } wheel(event) { const modifierKey = this.config.modifierKey; if (modifierKey && (Array.isArray(modifierKey) ? !modifierKey.find((k) => event[k]) : !event[modifierKey])) return; if (!this.state._active) this.wheelStart(event); else this.wheelChange(event); this.timeoutStore.add("wheelEnd", this.wheelEnd.bind(this)); } wheelStart(event) { this.start(event); this.wheelChange(event); } wheelChange(event) { const isR3f = "uv" in event; if (!isR3f) { if (event.cancelable) { event.preventDefault(); } if (!event.defaultPrevented) { console.warn(`[@use-gesture]: To properly support zoom on trackpads, try using the \`target\` option. This message will only appear in development mode.`); } } const state = this.state; state._delta = [-wheelValues(event)[1] / PINCH_WHEEL_RATIO * state.offset[0], 0]; V.addTo(state._movement, state._delta); clampStateInternalMovementToBounds(state); this.state.origin = [event.clientX, event.clientY]; this.compute(event); this.emit(); } wheelEnd() { if (!this.state._active) return; this.state._active = false; this.compute(); this.emit(); } bind(bindFunction) { const device = this.config.device; if (!!device) { bindFunction(device, "start", this[device + "Start"].bind(this)); bindFunction(device, "change", this[device + "Move"].bind(this)); bindFunction(device, "end", this[device + "End"].bind(this)); bindFunction(device, "cancel", this[device + "End"].bind(this)); bindFunction("lostPointerCapture", "", this[device + "End"].bind(this)); } if (this.config.pinchOnWheel) { bindFunction("wheel", "", this.wheel.bind(this), { passive: false }); } } }; var pinchConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, { device(_v4, _k, { shared, pointer: { touch = false } = {} }) { const sharedConfig = shared; if (sharedConfig.target && !SUPPORT.touch && SUPPORT.gesture) return "gesture"; if (SUPPORT.touch && touch) return "touch"; if (SUPPORT.touchscreen) { if (SUPPORT.pointer) return "pointer"; if (SUPPORT.touch) return "touch"; } }, bounds(_v4, _k, { scaleBounds = {}, angleBounds = {} }) { const _scaleBounds = (state) => { const D = assignDefault(call(scaleBounds, state), { min: -Infinity, max: Infinity }); return [D.min, D.max]; }; const _angleBounds = (state) => { const A = assignDefault(call(angleBounds, state), { min: -Infinity, max: Infinity }); return [A.min, A.max]; }; if (typeof scaleBounds !== "function" && typeof angleBounds !== "function") return [_scaleBounds(), _angleBounds()]; return (state) => [_scaleBounds(state), _angleBounds(state)]; }, threshold(value, _k, config) { this.lockDirection = config.axis === "lock"; const threshold = V.toVector(value, this.lockDirection ? [0.1, 3] : 0); return threshold; }, modifierKey(value) { if (value === void 0) return "ctrlKey"; return value; }, pinchOnWheel(value = true) { return value; } }); var MoveEngine = class extends CoordinatesEngine { constructor(...args) { super(...args); _defineProperty(this, "ingKey", "moving"); } move(event) { if (this.config.mouseOnly && event.pointerType !== "mouse") return; if (!this.state._active) this.moveStart(event); else this.moveChange(event); this.timeoutStore.add("moveEnd", this.moveEnd.bind(this)); } moveStart(event) { this.start(event); this.computeValues(pointerValues(event)); this.compute(event); this.computeInitial(); this.emit(); } moveChange(event) { if (!this.state._active) return; const values = pointerValues(event); const state = this.state; state._delta = V.sub(values, state._values); V.addTo(state._movement, state._delta); this.computeValues(values); this.compute(event); this.emit(); } moveEnd(event) { if (!this.state._active) return; this.state._active = false; this.compute(event); this.emit(); } bind(bindFunction) { bindFunction("pointer", "change", this.move.bind(this)); bindFunction("pointer", "leave", this.moveEnd.bind(this)); } }; var moveConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { mouseOnly: (value = true) => value }); var ScrollEngine = class extends CoordinatesEngine { constructor(...args) { super(...args); _defineProperty(this, "ingKey", "scrolling"); } scroll(event) { if (!this.state._active) this.start(event); this.scrollChange(event); this.timeoutStore.add("scrollEnd", this.scrollEnd.bind(this)); } scrollChange(event) { if (event.cancelable) event.preventDefault(); const state = this.state; const values = scrollValues(event); state._delta = V.sub(values, state._values); V.addTo(state._movement, state._delta); this.computeValues(values); this.compute(event); this.emit(); } scrollEnd() { if (!this.state._active) return; this.state._active = false; this.compute(); this.emit(); } bind(bindFunction) { bindFunction("scroll", "", this.scroll.bind(this)); } }; var scrollConfigResolver = coordinatesConfigResolver; var WheelEngine = class extends CoordinatesEngine { constructor(...args) { super(...args); _defineProperty(this, "ingKey", "wheeling"); } wheel(event) { if (!this.state._active) this.start(event); this.wheelChange(event); this.timeoutStore.add("wheelEnd", this.wheelEnd.bind(this)); } wheelChange(event) { const state = this.state; state._delta = wheelValues(event); V.addTo(state._movement, state._delta); clampStateInternalMovementToBounds(state); this.compute(event); this.emit(); } wheelEnd() { if (!this.state._active) return; this.state._active = false; this.compute(); this.emit(); } bind(bindFunction) { bindFunction("wheel", "", this.wheel.bind(this)); } }; var wheelConfigResolver = coordinatesConfigResolver; var HoverEngine = class extends CoordinatesEngine { constructor(...args) { super(...args); _defineProperty(this, "ingKey", "hovering"); } enter(event) { if (this.config.mouseOnly && event.pointerType !== "mouse") return; this.start(event); this.computeValues(pointerValues(event)); this.compute(event); this.emit(); } leave(event) { if (this.config.mouseOnly && event.pointerType !== "mouse") return; const state = this.state; if (!state._active) return; state._active = false; const values = pointerValues(event); state._movement = state._delta = V.sub(values, state._values); this.computeValues(values); this.compute(event); state.delta = state.movement; this.emit(); } bind(bindFunction) { bindFunction("pointer", "enter", this.enter.bind(this)); bindFunction("pointer", "leave", this.leave.bind(this)); } }; var hoverConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, { mouseOnly: (value = true) => value }); var EngineMap = /* @__PURE__ */ new Map(); var ConfigResolverMap = /* @__PURE__ */ new Map(); function registerAction(action) { EngineMap.set(action.key, action.engine); ConfigResolverMap.set(action.key, action.resolver); } var dragAction = { key: "drag", engine: DragEngine, resolver: dragConfigResolver }; var hoverAction = { key: "hover", engine: HoverEngine, resolver: hoverConfigResolver }; var moveAction = { key: "move", engine: MoveEngine, resolver: moveConfigResolver }; var pinchAction = { key: "pinch", engine: PinchEngine, resolver: pinchConfigResolver }; var scrollAction = { key: "scroll", engine: ScrollEngine, resolver: scrollConfigResolver }; var wheelAction = { key: "wheel", engine: WheelEngine, resolver: wheelConfigResolver }; // node_modules/@use-gesture/react/dist/use-gesture-react.esm.js var import_react = __toESM(require_react()); // node_modules/@use-gesture/core/dist/use-gesture-core.esm.js function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target2 = {}; var sourceKeys = Object.keys(source); var key, i4; for (i4 = 0; i4 < sourceKeys.length; i4++) { key = sourceKeys[i4]; if (excluded.indexOf(key) >= 0) continue; target2[key] = source[key]; } return target2; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target2 = _objectWithoutPropertiesLoose(source, excluded); var key, i4; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i4 = 0; i4 < sourceSymbolKeys.length; i4++) { key = sourceSymbolKeys[i4]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target2[key] = source[key]; } } return target2; } var sharedConfigResolver = { target(value) { if (value) { return () => "current" in value ? value.current : value; } return void 0; }, enabled(value = true) { return value; }, window(value = SUPPORT.isBrowser ? window : void 0) { return value; }, eventOptions({ passive = true, capture = false } = {}) { return { passive, capture }; }, transform(value) { return value; } }; var _excluded = ["target", "eventOptions", "window", "enabled", "transform"]; function resolveWith(config = {}, resolvers) { const result = {}; for (const [key, resolver] of Object.entries(resolvers)) { switch (typeof resolver) { case "function": if (true) { const r2 = resolver.call(result, config[key], key, config); if (!Number.isNaN(r2)) result[key] = r2; } else { result[key] = resolver.call(result, config[key], key, config); } break; case "object": result[key] = resolveWith(config[key], resolver); break; case "boolean": if (resolver) result[key] = config[key]; break; } } return result; } function parse(newConfig, gestureKey, _config = {}) { const _ref = newConfig, { target: target2, eventOptions, window: window2, enabled, transform } = _ref, rest = _objectWithoutProperties(_ref, _excluded); _config.shared = resolveWith({ target: target2, eventOptions, window: window2, enabled, transform }, sharedConfigResolver); if (gestureKey) { const resolver = ConfigResolverMap.get(gestureKey); _config[gestureKey] = resolveWith(_objectSpread2({ shared: _config.shared }, rest), resolver); } else { for (const key in rest) { const resolver = ConfigResolverMap.get(key); if (resolver) { _config[key] = resolveWith(_objectSpread2({ shared: _config.shared }, rest[key]), resolver); } else if (true) { if (!["drag", "pinch", "scroll", "wheel", "move", "hover"].includes(key)) { if (key === "domTarget") { throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`); } console.warn(`[@use-gesture]: Unknown config key \`${key}\` was used. Please read the documentation for further information.`); } } } } return _config; } var EventStore = class { constructor(ctrl, gestureKey) { _defineProperty(this, "_listeners", /* @__PURE__ */ new Set()); this._ctrl = ctrl; this._gestureKey = gestureKey; } add(element, device, action, handler, options) { const listeners = this._listeners; const type = toDomEventType(device, action); const _options = this._gestureKey ? this._ctrl.config[this._gestureKey].eventOptions : {}; const eventOptions = _objectSpread2(_objectSpread2({}, _options), options); element.addEventListener(type, handler, eventOptions); const remove = () => { element.removeEventListener(type, handler, eventOptions); listeners.delete(remove); }; listeners.add(remove); return remove; } clean() { this._listeners.forEach((remove) => remove()); this._listeners.clear(); } }; var TimeoutStore = class { constructor() { _defineProperty(this, "_timeouts", /* @__PURE__ */ new Map()); } add(key, callback, ms = 140, ...args) { this.remove(key); this._timeouts.set(key, window.setTimeout(callback, ms, ...args)); } remove(key) { const timeout = this._timeouts.get(key); if (timeout) window.clearTimeout(timeout); } clean() { this._timeouts.forEach((timeout) => void window.clearTimeout(timeout)); this._timeouts.clear(); } }; var Controller = class { constructor(handlers) { _defineProperty(this, "gestures", /* @__PURE__ */ new Set()); _defineProperty(this, "_targetEventStore", new EventStore(this)); _defineProperty(this, "gestureEventStores", {}); _defineProperty(this, "gestureTimeoutStores", {}); _defineProperty(this, "handlers", {}); _defineProperty(this, "config", {}); _defineProperty(this, "pointerIds", /* @__PURE__ */ new Set()); _defineProperty(this, "touchIds", /* @__PURE__ */ new Set()); _defineProperty(this, "state", { shared: { shiftKey: false, metaKey: false, ctrlKey: false, altKey: false } }); resolveGestures(this, handlers); } setEventIds(event) { if (isTouch(event)) { this.touchIds = new Set(touchIds(event)); return this.touchIds; } else if ("pointerId" in event) { if (event.type === "pointerup" || event.type === "pointercancel") this.pointerIds.delete(event.pointerId); else if (event.type === "pointerdown") this.pointerIds.add(event.pointerId); return this.pointerIds; } } applyHandlers(handlers, nativeHandlers) { this.handlers = handlers; this.nativeHandlers = nativeHandlers; } applyConfig(config, gestureKey) { this.config = parse(config, gestureKey, this.config); } clean() { this._targetEventStore.clean(); for (const key of this.gestures) { this.gestureEventStores[key].clean(); this.gestureTimeoutStores[key].clean(); } } effect() { if (this.config.shared.target) this.bind(); return () => this._targetEventStore.clean(); } bind(...args) { const sharedConfig = this.config.shared; const props = {}; let target2; if (sharedConfig.target) { target2 = sharedConfig.target(); if (!target2) return; } if (sharedConfig.enabled) { for (const gestureKey of this.gestures) { const gestureConfig = this.config[gestureKey]; const bindFunction = bindToProps(props, gestureConfig.eventOptions, !!target2); if (gestureConfig.enabled) { const Engine2 = EngineMap.get(gestureKey); new Engine2(this, args, gestureKey).bind(bindFunction); } } const nativeBindFunction = bindToProps(props, sharedConfig.eventOptions, !!target2); for (const eventKey in this.nativeHandlers) { nativeBindFunction(eventKey, "", (event) => this.nativeHandlers[eventKey](_objectSpread2(_objectSpread2({}, this.state.shared), {}, { event, args })), void 0, true); } } for (const handlerProp in props) { props[handlerProp] = chain(...props[handlerProp]); } if (!target2) return props; for (const handlerProp in props) { const { device, capture, passive } = parseProp(handlerProp); this._targetEventStore.add(target2, device, "", props[handlerProp], { capture, passive }); } } }; function setupGesture(ctrl, gestureKey) { ctrl.gestures.add(gestureKey); ctrl.gestureEventStores[gestureKey] = new EventStore(ctrl, gestureKey); ctrl.gestureTimeoutStores[gestureKey] = new TimeoutStore(); } function resolveGestures(ctrl, internalHandlers) { if (internalHandlers.drag) setupGesture(ctrl, "drag"); if (internalHandlers.wheel) setupGesture(ctrl, "wheel"); if (internalHandlers.scroll) setupGesture(ctrl, "scroll"); if (internalHandlers.move) setupGesture(ctrl, "move"); if (internalHandlers.pinch) setupGesture(ctrl, "pinch"); if (internalHandlers.hover) setupGesture(ctrl, "hover"); } var bindToProps = (props, eventOptions, withPassiveOption) => (device, action, handler, options = {}, isNative = false) => { var _options$capture, _options$passive; const capture = (_options$capture = options.capture) !== null && _options$capture !== void 0 ? _options$capture : eventOptions.capture; const passive = (_options$passive = options.passive) !== null && _options$passive !== void 0 ? _options$passive : eventOptions.passive; let handlerProp = isNative ? device : toHandlerProp(device, action, capture); if (withPassiveOption && passive) handlerProp += "Passive"; props[handlerProp] = props[handlerProp] || []; props[handlerProp].push(handler); }; var RE_NOT_NATIVE = /^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/; function sortHandlers(_handlers) { const native = {}; const handlers = {}; const actions = /* @__PURE__ */ new Set(); for (let key in _handlers) { if (RE_NOT_NATIVE.test(key)) { actions.add(RegExp.lastMatch); handlers[key] = _handlers[key]; } else { native[key] = _handlers[key]; } } return [handlers, native, actions]; } function registerGesture(actions, handlers, handlerKey, key, internalHandlers, config) { if (!actions.has(handlerKey)) return; if (!EngineMap.has(key)) { if (true) { console.warn(`[@use-gesture]: You've created a custom handler that that uses the \`${key}\` gesture but isn't properly configured. Please add \`${key}Action\` when creating your handler.`); } return; } const startKey = handlerKey + "Start"; const endKey = handlerKey + "End"; const fn = (state) => { let memo = void 0; if (state.first && startKey in handlers) handlers[startKey](state); if (handlerKey in handlers) memo = handlers[handlerKey](state); if (state.last && endKey in handlers) handlers[endKey](state); return memo; }; internalHandlers[key] = fn; config[key] = config[key] || {}; } function parseMergedHandlers(mergedHandlers, mergedConfig) { const [handlers, nativeHandlers, actions] = sortHandlers(mergedHandlers); const internalHandlers = {}; registerGesture(actions, handlers, "onDrag", "drag", internalHandlers, mergedConfig); registerGesture(actions, handlers, "onWheel", "wheel", internalHandlers, mergedConfig); registerGesture(actions, handlers, "onScroll", "scroll", internalHandlers, mergedConfig); registerGesture(actions, handlers, "onPinch", "pinch", internalHandlers, mergedConfig); registerGesture(actions, handlers, "onMove", "move", internalHandlers, mergedConfig); registerGesture(actions, handlers, "onHover", "hover", internalHandlers, mergedConfig); return { handlers: internalHandlers, config: mergedConfig, nativeHandlers }; } // node_modules/@use-gesture/react/dist/use-gesture-react.esm.js function useRecognizers(handlers, config = {}, gestureKey, nativeHandlers) { const ctrl = import_react.default.useMemo(() => new Controller(handlers), []); ctrl.applyHandlers(handlers, nativeHandlers); ctrl.applyConfig(config, gestureKey); import_react.default.useEffect(ctrl.effect.bind(ctrl)); import_react.default.useEffect(() => { return ctrl.clean.bind(ctrl); }, []); if (config.target === void 0) { return ctrl.bind.bind(ctrl); } return void 0; } function createUseGesture(actions) { actions.forEach(registerAction); return function useGesture2(_handlers, _config) { const { handlers, nativeHandlers, config } = parseMergedHandlers(_handlers, _config || {}); return useRecognizers(handlers, config, void 0, nativeHandlers); }; } function useGesture(handlers, config) { const hook = createUseGesture([dragAction, pinchAction, scrollAction, wheelAction, moveAction, hoverAction]); return hook(handlers, config || {}); } // node_modules/@react-three/drei/web/DragControls.js var initialModelPosition = new Vector3(); var mousePosition2D = new Vector2(); var mousePosition3D = new Vector3(); var dragOffset = new Vector3(); var dragPlaneNormal = new Vector3(); var dragPlane = new Plane(); var DragControls = React7.forwardRef(({ autoTransform = true, matrix: matrix6, axisLock, dragLimits, onHover, onDragStart, onDrag, onDragEnd, children, dragConfig, ...props }, fRef) => { const defaultControls = useThree((state) => state.controls); const { camera, size: size2, raycaster, invalidate } = useThree(); const ref = React7.useRef(null); const bind = useGesture({ onHover: ({ hovering }) => onHover && onHover(hovering !== null && hovering !== void 0 ? hovering : false), onDragStart: ({ event }) => { if (defaultControls) defaultControls.enabled = false; const { point } = event; ref.current.matrix.decompose(initialModelPosition, new Quaternion(), new Vector3()); mousePosition3D.copy(point); dragOffset.copy(mousePosition3D).sub(initialModelPosition); onDragStart && onDragStart(initialModelPosition); invalidate(); }, onDrag: ({ xy: [dragX, dragY], intentional }) => { if (!intentional) return; const normalizedMouseX = (dragX - size2.left) / size2.width * 2 - 1; const normalizedMouseY = -((dragY - size2.top) / size2.height) * 2 + 1; mousePosition2D.set(normalizedMouseX, normalizedMouseY); raycaster.setFromCamera(mousePosition2D, camera); if (!axisLock) { camera.getWorldDirection(dragPlaneNormal).negate(); } else { switch (axisLock) { case "x": dragPlaneNormal.set(1, 0, 0); break; case "y": dragPlaneNormal.set(0, 1, 0); break; case "z": dragPlaneNormal.set(0, 0, 1); break; } } dragPlane.setFromNormalAndCoplanarPoint(dragPlaneNormal, mousePosition3D); raycaster.ray.intersectPlane(dragPlane, mousePosition3D); const previousLocalMatrix = ref.current.matrix.clone(); const previousWorldMatrix = ref.current.matrixWorld.clone(); const intendedNewPosition = new Vector3(mousePosition3D.x - dragOffset.x, mousePosition3D.y - dragOffset.y, mousePosition3D.z - dragOffset.z); if (dragLimits) { intendedNewPosition.x = dragLimits[0] ? Math.max(Math.min(intendedNewPosition.x, dragLimits[0][1]), dragLimits[0][0]) : intendedNewPosition.x; intendedNewPosition.y = dragLimits[1] ? Math.max(Math.min(intendedNewPosition.y, dragLimits[1][1]), dragLimits[1][0]) : intendedNewPosition.y; intendedNewPosition.z = dragLimits[2] ? Math.max(Math.min(intendedNewPosition.z, dragLimits[2][1]), dragLimits[2][0]) : intendedNewPosition.z; } if (autoTransform) { ref.current.matrix.setPosition(intendedNewPosition); const deltaLocalMatrix = ref.current.matrix.clone().multiply(previousLocalMatrix.invert()); const deltaWorldMatrix = ref.current.matrix.clone().multiply(previousWorldMatrix.invert()); onDrag && onDrag(ref.current.matrix, deltaLocalMatrix, ref.current.matrixWorld, deltaWorldMatrix); } else { const tempMatrix4 = new Matrix4().copy(ref.current.matrix); tempMatrix4.setPosition(intendedNewPosition); const deltaLocalMatrix = tempMatrix4.clone().multiply(previousLocalMatrix.invert()); const deltaWorldMatrix = tempMatrix4.clone().multiply(previousWorldMatrix.invert()); onDrag && onDrag(tempMatrix4, deltaLocalMatrix, ref.current.matrixWorld, deltaWorldMatrix); } invalidate(); }, onDragEnd: () => { if (defaultControls) defaultControls.enabled = true; onDragEnd && onDragEnd(); invalidate(); } }, { drag: { filterTaps: true, threshold: 1, ...typeof dragConfig === "object" ? dragConfig : {} } }); React7.useImperativeHandle(fRef, () => ref.current, []); React7.useLayoutEffect(() => { if (!matrix6) return; ref.current.matrix = matrix6; }, [matrix6]); return React7.createElement("group", _extends({ ref }, bind(), { matrix: matrix6, matrixAutoUpdate: false }, props), children); }); // node_modules/@react-three/drei/web/ScrollControls.js var React8 = __toESM(require_react()); var ReactDOM2 = __toESM(require_client()); // node_modules/maath/dist/objectSpread2-284232a6.esm.js function _defineProperty2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function(sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread22(target2) { for (var i4 = 1; i4 < arguments.length; i4++) { var source = arguments[i4] != null ? arguments[i4] : {}; if (i4 % 2) { ownKeys2(Object(source), true).forEach(function(key) { _defineProperty2(target2, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source)); } else { ownKeys2(Object(source)).forEach(function(key) { Object.defineProperty(target2, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target2; } // node_modules/maath/dist/isNativeReflectConstruct-5594d075.esm.js function _setPrototypeOf(o2, p2) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o3, p3) { o3.__proto__ = p3; return o3; }; return _setPrototypeOf(o2, p2); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { })); return true; } catch (e2) { return false; } } // node_modules/maath/dist/matrix-baa530bf.esm.js function determinant2() { for (var _len = arguments.length, terms = new Array(_len), _key = 0; _key < _len; _key++) { terms[_key] = arguments[_key]; } var a6 = terms[0], b5 = terms[1], c2 = terms[2], d2 = terms[3]; return a6 * d2 - b5 * c2; } function determinant3() { for (var _len2 = arguments.length, terms = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { terms[_key2] = arguments[_key2]; } var a6 = terms[0], b5 = terms[1], c2 = terms[2], d2 = terms[3], e2 = terms[4], f2 = terms[5], g = terms[6], h = terms[7], i4 = terms[8]; return a6 * e2 * i4 + b5 * f2 * g + c2 * d2 * h - c2 * e2 * g - b5 * d2 * i4 - a6 * f2 * h; } function determinant4() { for (var _len3 = arguments.length, terms = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { terms[_key3] = arguments[_key3]; } terms[0]; terms[1]; terms[2]; terms[3]; terms[4]; terms[5]; terms[6]; terms[7]; terms[8]; terms[9]; terms[10]; terms[11]; terms[12]; terms[13]; terms[14]; } function getMinor(matrix6, r2, c2) { var _matrixTranspose = matrix6.clone().transpose(); var x = []; var l2 = _matrixTranspose.elements.length; var n2 = Math.sqrt(l2); for (var i4 = 0; i4 < l2; i4++) { var element = _matrixTranspose.elements[i4]; var row = Math.floor(i4 / n2); var col3 = i4 % n2; if (row !== r2 - 1 && col3 !== c2 - 1) { x.push(element); } } return determinant3.apply(void 0, x); } function matrixSum3(m1, m2) { var sum = []; var m1Array = m1.toArray(); var m2Array = m2.toArray(); for (var i4 = 0; i4 < m1Array.length; i4++) { sum[i4] = m1Array[i4] + m2Array[i4]; } return new Matrix3().fromArray(sum); } var matrix = Object.freeze({ __proto__: null, determinant2, determinant3, determinant4, getMinor, matrixSum3 }); // node_modules/maath/dist/triangle-b62b9067.esm.js function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i4) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i4 && _arr.length === i4) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i4 = 0, arr2 = new Array(len); i4 < len; i4++) arr2[i4] = arr[i4]; return arr2; } function _unsupportedIterableToArray(o2, minLen) { if (!o2) return; if (typeof o2 === "string") return _arrayLikeToArray(o2, minLen); var n2 = Object.prototype.toString.call(o2).slice(8, -1); if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name; if (n2 === "Map" || n2 === "Set") return Array.from(o2); if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return _arrayLikeToArray(o2, minLen); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _slicedToArray(arr, i4) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i4) || _unsupportedIterableToArray(arr, i4) || _nonIterableRest(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct2(Parent2, args2, Class2) { var a6 = [null]; a6.push.apply(a6, args2); var Constructor = Function.bind.apply(Parent2, a6); var instance2 = new Constructor(); if (Class2) _setPrototypeOf(instance2, Class2.prototype); return instance2; }; } return _construct.apply(null, arguments); } function isPointInTriangle(point, triangle4) { var _triangle$ = _slicedToArray(triangle4[0], 2), ax = _triangle$[0], ay = _triangle$[1]; var _triangle$2 = _slicedToArray(triangle4[1], 2), bx = _triangle$2[0], by = _triangle$2[1]; var _triangle$3 = _slicedToArray(triangle4[2], 2), cx = _triangle$3[0], cy = _triangle$3[1]; var _point = _slicedToArray(point, 2), px = _point[0], py = _point[1]; var matrix6 = new Matrix4(); matrix6.set(ax, ay, ax * ax + ay * ay, 1, bx, by, bx * bx + by * by, 1, cx, cy, cx * cx + cy * cy, 1, px, py, px * px + py * py, 1); return matrix6.determinant() <= 0; } function triangleDeterminant(triangle4) { var _triangle$4 = _slicedToArray(triangle4[0], 2), x1 = _triangle$4[0], y1 = _triangle$4[1]; var _triangle$5 = _slicedToArray(triangle4[1], 2), x2 = _triangle$5[0], y2 = _triangle$5[1]; var _triangle$6 = _slicedToArray(triangle4[2], 2), x3 = _triangle$6[0], y3 = _triangle$6[1]; return determinant3(x1, y1, 1, x2, y2, 1, x3, y3, 1); } function arePointsCollinear(points) { return triangleDeterminant(points) === 0; } function isTriangleClockwise(triangle4) { return triangleDeterminant(triangle4) < 0; } function getCircumcircle(triangle4) { var _triangle$7 = _slicedToArray(triangle4[0], 2), ax = _triangle$7[0], ay = _triangle$7[1]; var _triangle$8 = _slicedToArray(triangle4[1], 2), bx = _triangle$8[0], by = _triangle$8[1]; var _triangle$9 = _slicedToArray(triangle4[2], 2), cx = _triangle$9[0], cy = _triangle$9[1]; if (arePointsCollinear(triangle4)) return null; var m = new Matrix4(); m.set(1, 1, 1, 1, ax * ax + ay * ay, ax, ay, 1, bx * bx + by * by, bx, by, 1, cx * cx + cy * cy, cx, cy, 1); var m11 = getMinor(m, 1, 1); var m13 = getMinor(m, 1, 3); var m12 = getMinor(m, 1, 2); var m14 = getMinor(m, 1, 4); var x0 = 0.5 * (m12 / m11); var y0 = 0.5 * (m13 / m11); var r2 = x0 * x0 + y0 * y0 + m14 / m11; return { x: Math.abs(x0) === 0 ? 0 : x0, y: Math.abs(y0) === 0 ? 0 : -y0, r: Math.sqrt(r2) }; } function isPointInCircumcircle(point, triangle4) { var _ref = Array.isArray(triangle4[0]) ? triangle4[0] : triangle4[0].toArray(), _ref2 = _slicedToArray(_ref, 2), ax = _ref2[0], ay = _ref2[1]; var _ref3 = Array.isArray(triangle4[1]) ? triangle4[1] : triangle4[1].toArray(), _ref4 = _slicedToArray(_ref3, 2), bx = _ref4[0], by = _ref4[1]; var _ref5 = Array.isArray(triangle4[2]) ? triangle4[2] : triangle4[2].toArray(), _ref6 = _slicedToArray(_ref5, 2), cx = _ref6[0], cy = _ref6[1]; var _point2 = _slicedToArray(point, 2), px = _point2[0], py = _point2[1]; if (arePointsCollinear(triangle4)) throw new Error("Collinear points don't form a triangle"); var x1mpx = ax - px; var aympy = ay - py; var bxmpx = bx - px; var bympy = by - py; var cxmpx = cx - px; var cympy = cy - py; var d2 = determinant3(x1mpx, aympy, x1mpx * x1mpx + aympy * aympy, bxmpx, bympy, bxmpx * bxmpx + bympy * bympy, cxmpx, cympy, cxmpx * cxmpx + cympy * cympy); if (d2 === 0) { return true; } return !isTriangleClockwise(triangle4) ? d2 > 0 : d2 < 0; } var mv1 = new Vector2(); var mv2 = new Vector2(); function doThreePointsMakeARight(points) { var _points$map = points.map(function(p4) { if (Array.isArray(p4)) { return _construct(Vector2, _toConsumableArray(p4)); } return p4; }), _points$map2 = _slicedToArray(_points$map, 3), p1 = _points$map2[0], p2 = _points$map2[1], p3 = _points$map2[2]; if (arePointsCollinear(points)) return false; var p2p1 = mv1.subVectors(p2, p1); var p3p1 = mv2.subVectors(p3, p1); var cross2 = p3p1.cross(p2p1); return cross2 > 0; } var triangle = Object.freeze({ __proto__: null, isPointInTriangle, triangleDeterminant, arePointsCollinear, isTriangleClockwise, getCircumcircle, isPointInCircumcircle, doThreePointsMakeARight }); // node_modules/maath/dist/misc-19a3ec46.esm.js function clamp2(value, min, max2) { return Math.max(min, Math.min(max2, value)); } function repeat(t3, length3) { return clamp2(t3 - Math.floor(t3 / length3) * length3, 0, length3); } function deltaAngle(current, target2) { var delta = repeat(target2 - current, Math.PI * 2); if (delta > Math.PI) delta -= Math.PI * 2; return delta; } function degToRad(degrees) { return degrees / 180 * Math.PI; } function radToDeg(radians) { return radians * 180 / Math.PI; } function fibonacciOnSphere(buffer2, _ref) { var _ref$radius = _ref.radius, radius = _ref$radius === void 0 ? 1 : _ref$radius; var samples = buffer2.length / 3; var offset = 2 / samples; var increment = Math.PI * (3 - 2.2360679775); for (var i4 = 0; i4 < buffer2.length; i4 += 3) { var y = i4 * offset - 1 + offset / 2; var distance3 = Math.sqrt(1 - Math.pow(y, 2)); var phi = i4 % samples * increment; var x = Math.cos(phi) * distance3; var z = Math.sin(phi) * distance3; buffer2[i4] = x * radius; buffer2[i4 + 1] = y * radius; buffer2[i4 + 2] = z * radius; } } function vectorEquals(a6, b5) { var eps2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : Number.EPSILON; return Math.abs(a6.x - b5.x) < eps2 && Math.abs(a6.y - b5.y) < eps2 && Math.abs(a6.z - b5.z) < eps2; } function lexicographic(a6, b5) { if (a6.x === b5.x) { if (typeof a6.z !== "undefined") { if (a6.y === b5.y) { return a6.z - b5.z; } } return a6.y - b5.y; } return a6.x - b5.x; } function convexHull(_points) { var points = _points.sort(lexicographic); var lUpper = [points[0], points[1]]; for (var i4 = 2; i4 < points.length; i4++) { lUpper.push(points[i4]); while (lUpper.length > 2 && doThreePointsMakeARight(_toConsumableArray(lUpper.slice(-3)))) { lUpper.splice(lUpper.length - 2, 1); } } var lLower = [points[points.length - 1], points[points.length - 2]]; for (var _i = points.length - 3; _i >= 0; _i--) { lLower.push(points[_i]); while (lLower.length > 2 && doThreePointsMakeARight(_toConsumableArray(lLower.slice(-3)))) { lLower.splice(lLower.length - 2, 1); } } lLower.splice(0, 1); lLower.splice(lLower.length - 1, 1); var c2 = [].concat(lUpper, lLower); return c2; } function remap(x, _ref2, _ref3) { var _ref4 = _slicedToArray(_ref2, 2), low1 = _ref4[0], high1 = _ref4[1]; var _ref5 = _slicedToArray(_ref3, 2), low2 = _ref5[0], high2 = _ref5[1]; return low2 + (x - low1) * (high2 - low2) / (high1 - low1); } function fade(t3) { return t3 * t3 * t3 * (t3 * (t3 * 6 - 15) + 10); } function lerp(v0, v13, t3) { return v0 * (1 - t3) + v13 * t3; } function inverseLerp(v0, v13, t3) { return (t3 - v0) / (v13 - v0); } function normalize(x, y, z) { var m = Math.sqrt(x * x + y * y + z * z); return [x / m, y / m, z / m]; } function pointOnCubeToPointOnSphere(x, y, z) { var x2 = x * x; var y2 = y * y; var z2 = z * z; var nx = x * Math.sqrt(1 - (y2 + z2) / 2 + y2 * z2 / 3); var ny = y * Math.sqrt(1 - (z2 + x2) / 2 + z2 * x2 / 3); var nz = z * Math.sqrt(1 - (x2 + y2) / 2 + x2 * y2 / 3); return [nx, ny, nz]; } function rotateVectorOnVector(a6, b5) { var v5 = new Vector3().crossVectors(a6, b5); var c2 = a6.dot(b5); var i4 = new Matrix3().identity(); var vx = new Matrix3().set(0, -v5.z, v5.y, v5.z, 0, -v5.x, -v5.y, v5.x, 0); var vxsquared = new Matrix3().multiplyMatrices(vx, vx).multiplyScalar(1 / (1 + c2)); var _final = matrixSum3(matrixSum3(i4, vx), vxsquared); return _final; } function pointToCoordinate(x, y, z) { var lat = Math.asin(y); var lon = Math.atan2(x, -z); return [lat, lon]; } function coordinateToPoint(lat, lon) { var y = Math.sin(lat); var r2 = Math.cos(lat); var x = Math.sin(lon) * r2; var z = -Math.cos(lon) * r2; return [x, y, z]; } function planeSegmentIntersection(plane, segment) { var _segment = _slicedToArray(segment, 2), a6 = _segment[0], b5 = _segment[1]; var matrix6 = rotateVectorOnVector(plane.normal, new Vector3(0, 1, 0)); var t3 = inverseLerp(a6.clone().applyMatrix3(matrix6).y, b5.clone().applyMatrix3(matrix6).y, 0); return new Vector3().lerpVectors(a6, b5, t3); } function pointToPlaneDistance(p2, plane) { var d2 = plane.normal.dot(p2); return d2; } function getIndexFrom3D(coords, sides) { var _coords = _slicedToArray(coords, 3), ix = _coords[0], iy = _coords[1], iz = _coords[2]; var _sides = _slicedToArray(sides, 2), rx = _sides[0], ry = _sides[1]; return iz * rx * ry + iy * rx + ix; } function get3DFromIndex(index2, size2) { var _size = _slicedToArray(size2, 2), rx = _size[0], ry = _size[1]; var a6 = rx * ry; var z = index2 / a6; var b5 = index2 - a6 * z; var y = b5 / rx; var x = b5 % rx; return [x, y, z]; } function getIndexFrom2D(coords, size2) { return coords[0] + size2[0] * coords[1]; } function get2DFromIndex(index2, columns) { var x = index2 % columns; var y = Math.floor(index2 / columns); return [x, y]; } var misc = Object.freeze({ __proto__: null, clamp: clamp2, repeat, deltaAngle, degToRad, radToDeg, fibonacciOnSphere, vectorEquals, lexicographic, convexHull, remap, fade, lerp, inverseLerp, normalize, pointOnCubeToPointOnSphere, rotateVectorOnVector, pointToCoordinate, coordinateToPoint, planeSegmentIntersection, pointToPlaneDistance, getIndexFrom3D, get3DFromIndex, getIndexFrom2D, get2DFromIndex }); // node_modules/maath/dist/vector2-d2bf51f1.esm.js function zero() { return [0, 0]; } function one() { return [1, 1]; } function add(a6, b5) { return [a6[0] + b5[0], a6[1] + b5[1]]; } function addValue(a6, n2) { return [a6[0] + n2, a6[1] + n2]; } function sub(a6, b5) { return [a6[0] - b5[0], a6[1] - b5[1]]; } function subValue(a6, n2) { return [a6[0] - n2, a6[1] - n2]; } function scale(a6, n2) { return [a6[0] * n2, a6[1] * n2]; } function dot(a6, b5) { return a6[0] * b5[0] + a6[1] * b5[1]; } function lengthSqr(a6) { return a6[0] * a6[0] + a6[1] * a6[1]; } function length(a6) { return Math.sqrt(a6[0] * a6[0] + a6[1] * a6[1]); } function distance(a6, b5) { return Math.sqrt((a6[0] - b5[0]) * (a6[0] - b5[0]) + (a6[1] - b5[1]) * (a6[1] - b5[1])); } var vector2 = Object.freeze({ __proto__: null, zero, one, add, addValue, sub, subValue, scale, dot, lengthSqr, length, distance }); // node_modules/maath/dist/vector3-0a088b7f.esm.js function zero2() { return [0, 0, 0]; } function one2() { return [1, 1, 1]; } function add2(a6, b5) { return [a6[0] + b5[0], a6[1] + b5[1], a6[2] + b5[2]]; } function addValue2(a6, n2) { return [a6[0] + n2, a6[1] + n2, a6[2] + n2]; } function sub2(a6, b5) { return [a6[0] - b5[0], a6[1] - b5[1], a6[2] - b5[2]]; } function subValue2(a6, n2) { return [a6[0] - n2, a6[1] - n2, a6[2] - n2]; } function scale2(a6, n2) { return [a6[0] * n2, a6[1] * n2, a6[2] * n2]; } function dot2(a6, b5) { return a6[0] * b5[0] + a6[1] * b5[1] + a6[2] * b5[2]; } function cross(a6, b5) { var x = a6[1] * b5[2] - a6[2] * b5[1]; var y = a6[2] * b5[0] - a6[0] * b5[2]; var z = a6[0] * b5[1] - a6[1] * b5[0]; return [x, y, z]; } function lengthSqr2(a6) { return a6[0] * a6[0] + a6[1] * a6[1] + a6[2] * a6[2]; } function length2(a6) { return Math.sqrt(a6[0] * a6[0] + a6[1] * a6[1] + a6[2] * a6[2]); } function distance2(a6, b5) { return Math.sqrt((a6[0] - b5[0]) * (a6[0] - b5[0]) + (a6[1] - b5[1]) * (a6[1] - b5[1]) + (a6[2] - b5[2]) * (a6[2] - b5[2])); } var vector3 = Object.freeze({ __proto__: null, zero: zero2, one: one2, add: add2, addValue: addValue2, sub: sub2, subValue: subValue2, scale: scale2, dot: dot2, cross, lengthSqr: lengthSqr2, length: length2, distance: distance2 }); // node_modules/maath/dist/buffer-59a95d05.esm.js function swizzle(buffer2) { var stride = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 3; var swizzle2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "xyz"; var o2 = { x: 0, y: 0, z: 0 }; for (var _i = 0; _i < buffer2.length; _i += stride) { o2.x = buffer2[_i]; o2.y = buffer2[_i + 1]; o2.z = buffer2[_i + 2]; var _swizzle$split = swizzle2.split(""), _swizzle$split2 = _slicedToArray(_swizzle$split, 3), x = _swizzle$split2[0], y = _swizzle$split2[1], z = _swizzle$split2[2]; buffer2[_i] = o2[x]; buffer2[_i + 1] = o2[y]; if (stride === 3) { buffer2[_i + 2] = o2[z]; } } return buffer2; } function addAxis(buffer2, size2) { var valueGenerator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : function() { return Math.random(); }; var newSize = size2 + 1; var newBuffer = new Float32Array(buffer2.length / size2 * newSize); for (var _i2 = 0; _i2 < buffer2.length; _i2 += size2) { var _j = _i2 / size2 * newSize; newBuffer[_j] = buffer2[_i2]; newBuffer[_j + 1] = buffer2[_i2 + 1]; if (size2 === 2) { newBuffer[_j + 2] = valueGenerator(_j); } if (size2 === 3) { newBuffer[_j + 2] = buffer2[_i2 + 2]; newBuffer[_j + 3] = valueGenerator(_j); } } return newBuffer; } function lerp2(bufferA, bufferB, _final, t3) { for (var _i3 = 0; _i3 < bufferA.length; _i3++) { _final[_i3] = lerp(bufferA[_i3], bufferB[_i3], t3); } } function translate(buffer2, translationVector) { var stride = translationVector.length; for (var _i4 = 0; _i4 < buffer2.length; _i4 += stride) { buffer2[_i4] += translationVector[0]; buffer2[_i4 + 1] += translationVector[1]; buffer2[_i4 + 2] += translationVector[2]; } return buffer2; } function rotate(buffer2, rotation3) { var defaultRotation = { center: [0, 0, 0], q: new Quaternion().identity() }; var v5 = new Vector3(); var _defaultRotation$rota = _objectSpread22(_objectSpread22({}, defaultRotation), rotation3), q = _defaultRotation$rota.q, center3 = _defaultRotation$rota.center; for (var _i5 = 0; _i5 < buffer2.length; _i5 += 3) { v5.set(buffer2[_i5] - center3[0], buffer2[_i5 + 1] - center3[1], buffer2[_i5 + 2] - center3[2]); v5.applyQuaternion(q); buffer2[_i5] = v5.x + center3[0]; buffer2[_i5 + 1] = v5.y + center3[1]; buffer2[_i5 + 2] = v5.z + center3[1]; } return buffer2; } function map(buffer2, stride, callback) { for (var _i6 = 0, _j2 = 0; _i6 < buffer2.length; _i6 += stride, _j2++) { if (stride === 3) { var res = callback([buffer2[_i6], buffer2[_i6 + 1], buffer2[_i6 + 2]], _j2); buffer2.set(res, _i6); } else { buffer2.set(callback([buffer2[_i6], buffer2[_i6 + 1]], _j2), _i6); } } return buffer2; } function reduce(b5, stride, callback, acc) { for (var _i7 = 0, _j3 = 0; _i7 < b5.length; _i7 += stride, _j3++) { if (stride === 2) { acc = callback(acc, [b5[_i7], b5[_i7 + 1]], _j3); } else { acc = callback(acc, [b5[_i7], b5[_i7 + 1], b5[_i7 + 2]], _j3); } } return acc; } function expand(b5, stride, opts) { var defaultExpandOptions = { center: [0, 0, 0] }; var _defaultExpandOptions = _objectSpread22(_objectSpread22({}, defaultExpandOptions), opts), center3 = _defaultExpandOptions.center, distance3 = _defaultExpandOptions.distance; for (var _i8 = 0; _i8 < b5.length; _i8 += stride) { b5[_i8] = (b5[_i8] - center3[0]) * (1 + distance3) + center3[0]; b5[_i8 + 1] = (b5[_i8 + 1] - center3[1]) * (1 + distance3) + center3[1]; if (stride === 3) { b5[_i8 + 2] = (b5[_i8 + 2] - center3[1]) * (1 + distance3) + center3[2]; } } return b5; } function center(myBuffer, stride) { return reduce(myBuffer, stride, function(acc, point) { if (stride === 3) { acc = add2(acc, point); } else { acc = add(acc, point); } return acc; }, zero()); } function sort(myBuffer, stride, callback) { var indices = Int16Array.from({ length: myBuffer.length / stride }, function(_, i4) { return i4; }); indices.sort(function(a6, b5) { var pa = myBuffer.slice(a6 * stride, a6 * stride + stride); var pb = myBuffer.slice(b5 * stride, b5 * stride + stride); return callback(pa, pb); }); var prevBuffer = myBuffer.slice(0); for (var _i9 = 0; _i9 < indices.length; _i9++) { var _j4 = indices[_i9]; myBuffer.set(prevBuffer.slice(_j4 * stride, _j4 * stride + stride), _i9 * 3); } return myBuffer; } var buffer = Object.freeze({ __proto__: null, swizzle, addAxis, lerp: lerp2, translate, rotate, map, reduce, expand, center, sort }); // node_modules/maath/dist/classCallCheck-9098b006.esm.js function _classCallCheck(instance2, Constructor) { if (!(instance2 instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // node_modules/maath/dist/index-0332b2ed.esm.js function _defineProperties(target2, props) { for (var i4 = 0; i4 < props.length; i4++) { var descriptor = props[i4]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target2, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var Grad = function Grad2(x, y, z) { var _this = this; _classCallCheck(this, Grad2); _defineProperty2(this, "dot2", function(x2, y2) { return _this.x * x2 + _this.y * y2; }); _defineProperty2(this, "dot3", function(x2, y2, z2) { return _this.x * x2 + _this.y * y2 + _this.z * z2; }); this.x = x; this.y = y; this.z = z; }; var grad3 = [new Grad(1, 1, 0), new Grad(-1, 1, 0), new Grad(1, -1, 0), new Grad(-1, -1, 0), new Grad(1, 0, 1), new Grad(-1, 0, 1), new Grad(1, 0, -1), new Grad(-1, 0, -1), new Grad(0, 1, 1), new Grad(0, -1, 1), new Grad(0, 1, -1), new Grad(0, -1, -1)]; 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]; var perm = new Array(512); var gradP = new Array(512); var seed = function seed2(_seed) { if (_seed > 0 && _seed < 1) { _seed *= 65536; } _seed = Math.floor(_seed); if (_seed < 256) { _seed |= _seed << 8; } for (var i4 = 0; i4 < 256; i4++) { var v5; if (i4 & 1) { v5 = p[i4] ^ _seed & 255; } else { v5 = p[i4] ^ _seed >> 8 & 255; } perm[i4] = perm[i4 + 256] = v5; gradP[i4] = gradP[i4 + 256] = grad3[v5 % 12]; } }; seed(0); var F2 = 0.5 * (Math.sqrt(3) - 1); var G2 = (3 - Math.sqrt(3)) / 6; var F3 = 1 / 3; var G3 = 1 / 6; var simplex2 = function simplex22(xin, yin) { var n0, n1, n2; var s2 = (xin + yin) * F2; var i4 = Math.floor(xin + s2); var j = Math.floor(yin + s2); var t3 = (i4 + j) * G2; var x0 = xin - i4 + t3; var y0 = yin - j + t3; var i1, j1; if (x0 > y0) { i1 = 1; j1 = 0; } else { i1 = 0; j1 = 1; } var x1 = x0 - i1 + G2; var y1 = y0 - j1 + G2; var x2 = x0 - 1 + 2 * G2; var y2 = y0 - 1 + 2 * G2; i4 &= 255; j &= 255; var gi0 = gradP[i4 + perm[j]]; var gi1 = gradP[i4 + i1 + perm[j + j1]]; var gi2 = gradP[i4 + 1 + perm[j + 1]]; var t0 = 0.5 - x0 * x0 - y0 * y0; if (t0 < 0) { n0 = 0; } else { t0 *= t0; n0 = t0 * t0 * gi0.dot2(x0, y0); } var t1 = 0.5 - x1 * x1 - y1 * y1; if (t1 < 0) { n1 = 0; } else { t1 *= t1; n1 = t1 * t1 * gi1.dot2(x1, y1); } var t22 = 0.5 - x2 * x2 - y2 * y2; if (t22 < 0) { n2 = 0; } else { t22 *= t22; n2 = t22 * t22 * gi2.dot2(x2, y2); } return 70 * (n0 + n1 + n2); }; var simplex3 = function simplex32(xin, yin, zin) { var n0, n1, n2, n3; var s2 = (xin + yin + zin) * F3; var i4 = Math.floor(xin + s2); var j = Math.floor(yin + s2); var k = Math.floor(zin + s2); var t3 = (i4 + j + k) * G3; var x0 = xin - i4 + t3; var y0 = yin - j + t3; var z0 = zin - k + t3; var i1, j1, k1; var i22, j2, k2; if (x0 >= y0) { if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i22 = 1; j2 = 1; k2 = 0; } else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i22 = 1; j2 = 0; k2 = 1; } else { i1 = 0; j1 = 0; k1 = 1; i22 = 1; j2 = 0; k2 = 1; } } else { if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i22 = 0; j2 = 1; k2 = 1; } else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i22 = 0; j2 = 1; k2 = 1; } else { i1 = 0; j1 = 1; k1 = 0; i22 = 1; j2 = 1; k2 = 0; } } var x1 = x0 - i1 + G3; var y1 = y0 - j1 + G3; var z1 = z0 - k1 + G3; var x2 = x0 - i22 + 2 * G3; var y2 = y0 - j2 + 2 * G3; var z2 = z0 - k2 + 2 * G3; var x3 = x0 - 1 + 3 * G3; var y3 = y0 - 1 + 3 * G3; var z3 = z0 - 1 + 3 * G3; i4 &= 255; j &= 255; k &= 255; var gi0 = gradP[i4 + perm[j + perm[k]]]; var gi1 = gradP[i4 + i1 + perm[j + j1 + perm[k + k1]]]; var gi2 = gradP[i4 + i22 + perm[j + j2 + perm[k + k2]]]; var gi3 = gradP[i4 + 1 + perm[j + 1 + perm[k + 1]]]; var t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0; if (t0 < 0) { n0 = 0; } else { t0 *= t0; n0 = t0 * t0 * gi0.dot3(x0, y0, z0); } var t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; if (t1 < 0) { n1 = 0; } else { t1 *= t1; n1 = t1 * t1 * gi1.dot3(x1, y1, z1); } var t22 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2; if (t22 < 0) { n2 = 0; } else { t22 *= t22; n2 = t22 * t22 * gi2.dot3(x2, y2, z2); } var t32 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; if (t32 < 0) { n3 = 0; } else { t32 *= t32; n3 = t32 * t32 * gi3.dot3(x3, y3, z3); } return 32 * (n0 + n1 + n2 + n3); }; var perlin2 = function perlin22(x, y) { var X = Math.floor(x), Y = Math.floor(y); x = x - X; y = y - Y; X = X & 255; Y = Y & 255; var n00 = gradP[X + perm[Y]].dot2(x, y); var n01 = gradP[X + perm[Y + 1]].dot2(x, y - 1); var n10 = gradP[X + 1 + perm[Y]].dot2(x - 1, y); var n11 = gradP[X + 1 + perm[Y + 1]].dot2(x - 1, y - 1); var u = fade(x); return lerp(lerp(n00, n10, u), lerp(n01, n11, u), fade(y)); }; var perlin3 = function perlin32(x, y, z) { var X = Math.floor(x), Y = Math.floor(y), Z = Math.floor(z); x = x - X; y = y - Y; z = z - Z; X = X & 255; Y = Y & 255; Z = Z & 255; var n000 = gradP[X + perm[Y + perm[Z]]].dot3(x, y, z); var n001 = gradP[X + perm[Y + perm[Z + 1]]].dot3(x, y, z - 1); var n010 = gradP[X + perm[Y + 1 + perm[Z]]].dot3(x, y - 1, z); var n011 = gradP[X + perm[Y + 1 + perm[Z + 1]]].dot3(x, y - 1, z - 1); var n100 = gradP[X + 1 + perm[Y + perm[Z]]].dot3(x - 1, y, z); var n101 = gradP[X + 1 + perm[Y + perm[Z + 1]]].dot3(x - 1, y, z - 1); var n110 = gradP[X + 1 + perm[Y + 1 + perm[Z]]].dot3(x - 1, y - 1, z); var n111 = gradP[X + 1 + perm[Y + 1 + perm[Z + 1]]].dot3(x - 1, y - 1, z - 1); var u = fade(x); var v5 = fade(y); var w = fade(z); return lerp(lerp(lerp(n000, n100, u), lerp(n001, n101, u), w), lerp(lerp(n010, n110, u), lerp(n011, n111, u), w), v5); }; var noise = Object.freeze({ __proto__: null, seed, simplex2, simplex3, perlin2, perlin3 }); var TAU = Math.PI * 2; var FlashGen = (function() { function FlashGen2(props) { _classCallCheck(this, FlashGen2); _defineProperty2(this, "nextBurstTime", 0); _defineProperty2(this, "nextFlashEndTime", 0); _defineProperty2(this, "flashesDone", 0); _defineProperty2(this, "isFlashing", false); _defineProperty2(this, "currentCount", 0); _defineProperty2(this, "flashIntensity", 0); _defineProperty2(this, "isDecaying", false); _defineProperty2(this, "autoBurst", true); _defineProperty2(this, "decaySpeed", 40); _defineProperty2(this, "minInterval", 5e3); _defineProperty2(this, "maxInterval", 1e4); _defineProperty2(this, "minDuration", 50); _defineProperty2(this, "maxDuration", 300); _defineProperty2(this, "count", 5); Object.assign(this, props); } _createClass(FlashGen2, [{ key: "scheduleNextBurst", value: function scheduleNextBurst(currentTime) { var burstInterval = Math.random() * (this.maxInterval - this.minInterval) + this.minInterval; this.nextBurstTime = currentTime + burstInterval / 1e3; this.flashesDone = 0; this.isFlashing = false; } }, { key: "burst", value: function burst() { this.nextBurstTime = 0; this.flashesDone = 0; this.isFlashing = false; } }, { key: "update", value: function update2(currentTime, delta) { if (currentTime > this.nextBurstTime && this.currentCount === 0) { this.currentCount = Math.floor(Math.random() * this.count) + 1; } if (this.flashesDone < this.currentCount && currentTime > this.nextBurstTime) { if (!this.isFlashing) { this.isFlashing = true; this.flashIntensity = 1; var flashDuration = Math.random() * (this.maxDuration - this.minDuration) + this.minDuration; this.nextFlashEndTime = currentTime + flashDuration / 1e3; } else if (this.isFlashing && currentTime > this.nextFlashEndTime) { this.isFlashing = false; this.isDecaying = true; this.flashesDone++; if (this.flashesDone >= this.currentCount) { this.currentCount = 0; if (this.autoBurst) this.scheduleNextBurst(currentTime); } } } if (this.isDecaying) { this.flashIntensity -= delta * this.decaySpeed; this.flashIntensity = Math.max(0, Math.min(1, this.flashIntensity)); if (this.flashIntensity <= 0) { this.isDecaying = false; this.flashIntensity = 0; } } return this.flashIntensity; } }]); return FlashGen2; })(); function normalizeSeed(seed3) { if (typeof seed3 === "number") { seed3 = Math.abs(seed3); } else if (typeof seed3 === "string") { var string = seed3; seed3 = 0; for (var i4 = 0; i4 < string.length; i4++) { seed3 = (seed3 + (i4 + 1) * (string.charCodeAt(i4) % 96)) % 2147483647; } } if (seed3 === 0) { seed3 = 311; } return seed3; } function lcgRandom(seed3) { var state = normalizeSeed(seed3); return function() { var result = state * 48271 % 2147483647; state = result; return result / 2147483647; }; } var Generator = function Generator2(_seed) { var _this = this; _classCallCheck(this, Generator2); _defineProperty2(this, "seed", 0); _defineProperty2(this, "init", function(seed3) { _this.seed = seed3; _this.value = lcgRandom(seed3); }); _defineProperty2(this, "value", lcgRandom(this.seed)); this.init(_seed); }; var defaultGen = new Generator(Math.random()); var defaultSphere = { radius: 1, center: [0, 0, 0] }; function onSphere(buffer2, sphere) { var rng = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : defaultGen; var _defaultSphere$sphere = _objectSpread22(_objectSpread22({}, defaultSphere), sphere), radius = _defaultSphere$sphere.radius, center3 = _defaultSphere$sphere.center; for (var i4 = 0; i4 < buffer2.length; i4 += 3) { var u = rng.value(); var v5 = rng.value(); var theta = Math.acos(2 * v5 - 1); var phi = TAU * u; buffer2[i4] = Math.sin(theta) * Math.cos(phi) * radius + center3[0]; buffer2[i4 + 1] = Math.sin(theta) * Math.sin(phi) * radius + center3[1]; buffer2[i4 + 2] = Math.cos(theta) * radius + center3[2]; } return buffer2; } function inSphere(buffer2, sphere) { var rng = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : defaultGen; var _defaultSphere$sphere2 = _objectSpread22(_objectSpread22({}, defaultSphere), sphere), radius = _defaultSphere$sphere2.radius, center3 = _defaultSphere$sphere2.center; for (var i4 = 0; i4 < buffer2.length; i4 += 3) { var u = Math.pow(rng.value(), 1 / 3); var x = rng.value() * 2 - 1; var y = rng.value() * 2 - 1; var z = rng.value() * 2 - 1; var mag = Math.sqrt(x * x + y * y + z * z); x = u * x / mag; y = u * y / mag; z = u * z / mag; buffer2[i4] = x * radius + center3[0]; buffer2[i4 + 1] = y * radius + center3[1]; buffer2[i4 + 2] = z * radius + center3[2]; } return buffer2; } var defaultCircle = { radius: 1, center: [0, 0] }; function inCircle(buffer2, circle) { var rng = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : defaultGen; var _defaultCircle$circle = _objectSpread22(_objectSpread22({}, defaultCircle), circle), radius = _defaultCircle$circle.radius, center3 = _defaultCircle$circle.center; for (var i4 = 0; i4 < buffer2.length; i4 += 2) { var r2 = radius * Math.sqrt(rng.value()); var theta = rng.value() * TAU; buffer2[i4] = Math.sin(theta) * r2 + center3[0]; buffer2[i4 + 1] = Math.cos(theta) * r2 + center3[1]; } return buffer2; } function onCircle(buffer2, circle) { var rng = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : defaultGen; var _defaultCircle$circle2 = _objectSpread22(_objectSpread22({}, defaultCircle), circle), radius = _defaultCircle$circle2.radius, center3 = _defaultCircle$circle2.center; for (var i4 = 0; i4 < buffer2.length; i4 += 2) { var theta = rng.value() * TAU; buffer2[i4] = Math.sin(theta) * radius + center3[0]; buffer2[i4 + 1] = Math.cos(theta) * radius + center3[1]; } return buffer2; } var defaultRect = { sides: 1, center: [0, 0] }; function inRect(buffer2, rect) { var rng = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : defaultGen; var _defaultRect$rect = _objectSpread22(_objectSpread22({}, defaultRect), rect), sides = _defaultRect$rect.sides, center3 = _defaultRect$rect.center; var sideX = typeof sides === "number" ? sides : sides[0]; var sideY = typeof sides === "number" ? sides : sides[1]; for (var i4 = 0; i4 < buffer2.length; i4 += 2) { buffer2[i4] = (rng.value() - 0.5) * sideX + center3[0]; buffer2[i4 + 1] = (rng.value() - 0.5) * sideY + center3[1]; } return buffer2; } function onRect(buffer2, rect) { return buffer2; } function inBox(buffer2, box) { var rng = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : defaultGen; var _defaultBox$box = _objectSpread22(_objectSpread22({}, defaultBox), box), sides = _defaultBox$box.sides, center3 = _defaultBox$box.center; var sideX = typeof sides === "number" ? sides : sides[0]; var sideY = typeof sides === "number" ? sides : sides[1]; var sideZ = typeof sides === "number" ? sides : sides[2]; for (var i4 = 0; i4 < buffer2.length; i4 += 3) { buffer2[i4] = (rng.value() - 0.5) * sideX + center3[0]; buffer2[i4 + 1] = (rng.value() - 0.5) * sideY + center3[1]; buffer2[i4 + 2] = (rng.value() - 0.5) * sideZ + center3[2]; } return buffer2; } var defaultBox = { sides: 1, center: [0, 0, 0] }; function onBox(buffer2, box) { var rng = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : defaultGen; var _defaultBox$box2 = _objectSpread22(_objectSpread22({}, defaultBox), box), sides = _defaultBox$box2.sides, center3 = _defaultBox$box2.center; var sideX = typeof sides === "number" ? sides : sides[0]; var sideY = typeof sides === "number" ? sides : sides[1]; var sideZ = typeof sides === "number" ? sides : sides[2]; for (var i4 = 0; i4 < buffer2.length; i4 += 3) { buffer2[i4] = (rng.value() - 0.5) * sideX + center3[0]; buffer2[i4 + 1] = (rng.value() - 0.5) * sideY + center3[1]; buffer2[i4 + 2] = (rng.value() - 0.5) * sideZ + center3[2]; } return buffer2; } var index = Object.freeze({ __proto__: null, FlashGen, Generator, onSphere, inSphere, inCircle, onCircle, inRect, onRect, inBox, onBox, noise }); // node_modules/maath/dist/easing-0f4db1c0.esm.js var rsqw = function rsqw2(t3) { var delta = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0.01; var a6 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1; var f2 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 1 / (2 * Math.PI); return a6 / Math.atan(1 / delta) * Math.atan(Math.sin(2 * Math.PI * t3 * f2) / delta); }; var exp = function exp2(t3) { return 1 / (1 + t3 + 0.48 * t3 * t3 + 0.235 * t3 * t3 * t3); }; var linear = function linear2(t3) { return t3; }; var sine = { "in": function _in(x) { return 1 - Math.cos(x * Math.PI / 2); }, out: function out(x) { return Math.sin(x * Math.PI / 2); }, inOut: function inOut(x) { return -(Math.cos(Math.PI * x) - 1) / 2; } }; var cubic = { "in": function _in2(x) { return x * x * x; }, out: function out2(x) { return 1 - Math.pow(1 - x, 3); }, inOut: function inOut2(x) { return x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2; } }; var quint = { "in": function _in3(x) { return x * x * x * x * x; }, out: function out3(x) { return 1 - Math.pow(1 - x, 5); }, inOut: function inOut3(x) { return x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2; } }; var circ = { "in": function _in4(x) { return 1 - Math.sqrt(1 - Math.pow(x, 2)); }, out: function out4(x) { return Math.sqrt(1 - Math.pow(x - 1, 2)); }, inOut: function inOut4(x) { return x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2; } }; var quart = { "in": function _in5(t3) { return t3 * t3 * t3 * t3; }, out: function out5(t3) { return 1 - --t3 * t3 * t3 * t3; }, inOut: function inOut5(t3) { return t3 < 0.5 ? 8 * t3 * t3 * t3 * t3 : 1 - 8 * --t3 * t3 * t3 * t3; } }; var expo = { "in": function _in6(x) { return x === 0 ? 0 : Math.pow(2, 10 * x - 10); }, out: function out6(x) { return x === 1 ? 1 : 1 - Math.pow(2, -10 * x); }, inOut: function inOut6(x) { return x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2; } }; function damp(current, prop, target2) { var smoothTime = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0.25; var delta = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 0.01; var maxSpeed = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : Infinity; var easing2 = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : exp; var eps2 = arguments.length > 7 && arguments[7] !== void 0 ? arguments[7] : 1e-3; var vel = "velocity_" + prop; if (current.__damp === void 0) current.__damp = {}; if (current.__damp[vel] === void 0) current.__damp[vel] = 0; if (Math.abs(current[prop] - target2) <= eps2) { current[prop] = target2; return false; } smoothTime = Math.max(1e-4, smoothTime); var omega = 2 / smoothTime; var t3 = easing2(omega * delta); var change = current[prop] - target2; var originalTo = target2; var maxChange = maxSpeed * smoothTime; change = Math.min(Math.max(change, -maxChange), maxChange); target2 = current[prop] - change; var temp5 = (current.__damp[vel] + omega * change) * delta; current.__damp[vel] = (current.__damp[vel] - omega * temp5) * t3; var output = target2 + (change + temp5) * t3; if (originalTo - current[prop] > 0 === output > originalTo) { output = originalTo; current.__damp[vel] = (output - originalTo) / delta; } current[prop] = output; return true; } var isCamera = function isCamera2(v5) { return v5 && v5.isCamera; }; var isLight = function isLight2(v5) { return v5 && v5.isLight; }; var vl3d = new Vector3(); var _q1 = new Quaternion(); var _q2 = new Quaternion(); var _m1 = new Matrix4(); var _position = new Vector3(); function dampLookAt(current, target2, smoothTime, delta, maxSpeed, easing2, eps2) { if (typeof target2 === "number") vl3d.setScalar(target2); else if (Array.isArray(target2)) vl3d.set(target2[0], target2[1], target2[2]); else vl3d.copy(target2); var parent = current.parent; current.updateWorldMatrix(true, false); _position.setFromMatrixPosition(current.matrixWorld); if (isCamera(current) || isLight(current)) _m1.lookAt(_position, vl3d, current.up); else _m1.lookAt(vl3d, _position, current.up); dampQ(current.quaternion, _q2.setFromRotationMatrix(_m1), smoothTime, delta, maxSpeed, easing2, eps2); if (parent) { _m1.extractRotation(parent.matrixWorld); _q1.setFromRotationMatrix(_m1); dampQ(current.quaternion, _q2.copy(current.quaternion).premultiply(_q1.invert()), smoothTime, delta, maxSpeed, easing2, eps2); } } function dampAngle(current, prop, target2, smoothTime, delta, maxSpeed, easing2, eps2) { return damp(current, prop, current[prop] + deltaAngle(current[prop], target2), smoothTime, delta, maxSpeed, easing2, eps2); } var v2d = new Vector2(); var a2; var b2; function damp2(current, target2, smoothTime, delta, maxSpeed, easing2, eps2) { if (typeof target2 === "number") v2d.setScalar(target2); else if (Array.isArray(target2)) v2d.set(target2[0], target2[1]); else v2d.copy(target2); a2 = damp(current, "x", v2d.x, smoothTime, delta, maxSpeed, easing2, eps2); b2 = damp(current, "y", v2d.y, smoothTime, delta, maxSpeed, easing2, eps2); return a2 || b2; } var v3d = new Vector3(); var a3; var b3; var c3; function damp3(current, target2, smoothTime, delta, maxSpeed, easing2, eps2) { if (typeof target2 === "number") v3d.setScalar(target2); else if (Array.isArray(target2)) v3d.set(target2[0], target2[1], target2[2]); else v3d.copy(target2); a3 = damp(current, "x", v3d.x, smoothTime, delta, maxSpeed, easing2, eps2); b3 = damp(current, "y", v3d.y, smoothTime, delta, maxSpeed, easing2, eps2); c3 = damp(current, "z", v3d.z, smoothTime, delta, maxSpeed, easing2, eps2); return a3 || b3 || c3; } var v4d = new Vector4(); var a4; var b4; var c4; var d4; function damp4(current, target2, smoothTime, delta, maxSpeed, easing2, eps2) { if (typeof target2 === "number") v4d.setScalar(target2); else if (Array.isArray(target2)) v4d.set(target2[0], target2[1], target2[2], target2[3]); else v4d.copy(target2); a4 = damp(current, "x", v4d.x, smoothTime, delta, maxSpeed, easing2, eps2); b4 = damp(current, "y", v4d.y, smoothTime, delta, maxSpeed, easing2, eps2); c4 = damp(current, "z", v4d.z, smoothTime, delta, maxSpeed, easing2, eps2); d4 = damp(current, "w", v4d.w, smoothTime, delta, maxSpeed, easing2, eps2); return a4 || b4 || c4 || d4; } var rot = new Euler(); var aE; var bE; var cE; function dampE(current, target2, smoothTime, delta, maxSpeed, easing2, eps2) { if (Array.isArray(target2)) rot.set(target2[0], target2[1], target2[2], target2[3]); else rot.copy(target2); aE = dampAngle(current, "x", rot.x, smoothTime, delta, maxSpeed, easing2, eps2); bE = dampAngle(current, "y", rot.y, smoothTime, delta, maxSpeed, easing2, eps2); cE = dampAngle(current, "z", rot.z, smoothTime, delta, maxSpeed, easing2, eps2); return aE || bE || cE; } var col = new Color(); var aC; var bC; var cC; function dampC(current, target2, smoothTime, delta, maxSpeed, easing2, eps2) { if (target2 instanceof Color) col.copy(target2); else if (Array.isArray(target2)) col.setRGB(target2[0], target2[1], target2[2]); else col.set(target2); aC = damp(current, "r", col.r, smoothTime, delta, maxSpeed, easing2, eps2); bC = damp(current, "g", col.g, smoothTime, delta, maxSpeed, easing2, eps2); cC = damp(current, "b", col.b, smoothTime, delta, maxSpeed, easing2, eps2); return aC || bC || cC; } var qt = new Quaternion(); var v4result = new Vector4(); var v4velocity = new Vector4(); var v4error = new Vector4(); var aQ; var bQ; var cQ; var dQ; function dampQ(current, target2, smoothTime, delta, maxSpeed, easing2, eps2) { var cur = current; if (Array.isArray(target2)) qt.set(target2[0], target2[1], target2[2], target2[3]); else qt.copy(target2); var multi = current.dot(qt) > 0 ? 1 : -1; qt.x *= multi; qt.y *= multi; qt.z *= multi; qt.w *= multi; aQ = damp(current, "x", qt.x, smoothTime, delta, maxSpeed, easing2, eps2); bQ = damp(current, "y", qt.y, smoothTime, delta, maxSpeed, easing2, eps2); cQ = damp(current, "z", qt.z, smoothTime, delta, maxSpeed, easing2, eps2); dQ = damp(current, "w", qt.w, smoothTime, delta, maxSpeed, easing2, eps2); v4result.set(current.x, current.y, current.z, current.w).normalize(); v4velocity.set(cur.__damp.velocity_x, cur.__damp.velocity_y, cur.__damp.velocity_z, cur.__damp.velocity_w); v4error.copy(v4result).multiplyScalar(v4velocity.dot(v4result) / v4result.dot(v4result)); cur.__damp.velocity_x -= v4error.x; cur.__damp.velocity_y -= v4error.y; cur.__damp.velocity_z -= v4error.z; cur.__damp.velocity_w -= v4error.w; current.set(v4result.x, v4result.y, v4result.z, v4result.w); return aQ || bQ || cQ || dQ; } var spherical = new Spherical(); var aS; var bS; var cS; function dampS(current, target2, smoothTime, delta, maxSpeed, easing2, eps2) { if (Array.isArray(target2)) spherical.set(target2[0], target2[1], target2[2]); else spherical.copy(target2); aS = damp(current, "radius", spherical.radius, smoothTime, delta, maxSpeed, easing2, eps2); bS = dampAngle(current, "phi", spherical.phi, smoothTime, delta, maxSpeed, easing2, eps2); cS = dampAngle(current, "theta", spherical.theta, smoothTime, delta, maxSpeed, easing2, eps2); return aS || bS || cS; } var mat = new Matrix4(); var mPos = new Vector3(); var mRot = new Quaternion(); var mSca = new Vector3(); var aM; var bM; var cM; function dampM(current, target2, smoothTime, delta, maxSpeed, easing2, eps2) { var cur = current; if (cur.__damp === void 0) { cur.__damp = { position: new Vector3(), rotation: new Quaternion(), scale: new Vector3() }; current.decompose(cur.__damp.position, cur.__damp.rotation, cur.__damp.scale); } if (Array.isArray(target2)) mat.set.apply(mat, _toConsumableArray(target2)); else mat.copy(target2); mat.decompose(mPos, mRot, mSca); aM = damp3(cur.__damp.position, mPos, smoothTime, delta, maxSpeed, easing2, eps2); bM = dampQ(cur.__damp.rotation, mRot, smoothTime, delta, maxSpeed, easing2, eps2); cM = damp3(cur.__damp.scale, mSca, smoothTime, delta, maxSpeed, easing2, eps2); current.compose(cur.__damp.position, cur.__damp.rotation, cur.__damp.scale); return aM || bM || cM; } var easing = Object.freeze({ __proto__: null, rsqw, exp, linear, sine, cubic, quint, circ, quart, expo, damp, dampLookAt, dampAngle, damp2, damp3, damp4, dampE, dampC, dampQ, dampS, dampM }); // node_modules/maath/dist/geometry-0fb11825.esm.js function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o2) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf2(o3) { return o3.__proto__ || Object.getPrototypeOf(o3); }; return _getPrototypeOf(o2); } function _assertThisInitialized(self2) { if (self2 === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self2; } function _possibleConstructorReturn(self2, call3) { if (call3 && (typeof call3 === "object" || typeof call3 === "function")) { return call3; } else if (call3 !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self2); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } var RoundedPlaneGeometry = (function(_THREE$BufferGeometry) { _inherits(RoundedPlaneGeometry2, _THREE$BufferGeometry); var _super = _createSuper(RoundedPlaneGeometry2); function RoundedPlaneGeometry2() { var _this; var width = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 2; var height = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1; var radius = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0.2; var segments = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 16; _classCallCheck(this, RoundedPlaneGeometry2); _this = _super.call(this); _this.parameters = { width, height, radius, segments }; var wi = width / 2 - radius; var hi = height / 2 - radius; var ul = radius / width; var ur = (width - radius) / width; var vl = radius / height; var vh = (height - radius) / height; var positions = [wi, hi, 0, -wi, hi, 0, -wi, -hi, 0, wi, -hi, 0]; var uvs = [ur, vh, ul, vh, ul, vl, ur, vl]; var n2 = [3 * (segments + 1) + 3, 3 * (segments + 1) + 4, segments + 4, segments + 5, 2 * (segments + 1) + 4, 2, 1, 2 * (segments + 1) + 3, 3, 4 * (segments + 1) + 3, 4, 0]; var indices = [n2[0], n2[1], n2[2], n2[0], n2[2], n2[3], n2[4], n2[5], n2[6], n2[4], n2[6], n2[7], n2[8], n2[9], n2[10], n2[8], n2[10], n2[11]]; var phi, cos, sin, xc, yc, uc, vc, idx; for (var i4 = 0; i4 < 4; i4++) { xc = i4 < 1 || i4 > 2 ? wi : -wi; yc = i4 < 2 ? hi : -hi; uc = i4 < 1 || i4 > 2 ? ur : ul; vc = i4 < 2 ? vh : vl; for (var j = 0; j <= segments; j++) { phi = Math.PI / 2 * (i4 + j / segments); cos = Math.cos(phi); sin = Math.sin(phi); positions.push(xc + radius * cos, yc + radius * sin, 0); uvs.push(uc + ul * cos, vc + vl * sin); if (j < segments) { idx = (segments + 1) * i4 + j + 4; indices.push(i4, idx, idx + 1); } } } _this.setIndex(new BufferAttribute(new Uint32Array(indices), 1)); _this.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3)); _this.setAttribute("uv", new BufferAttribute(new Float32Array(uvs), 2)); return _this; } return RoundedPlaneGeometry2; })(BufferGeometry); function applyCylindricalUV(bufferGeometry) { var uvs = []; for (var i4 = 0; i4 < bufferGeometry.attributes.position.array.length / 3; i4++) { var x = bufferGeometry.attributes.position.array[i4 * 3 + 0]; var y = bufferGeometry.attributes.position.array[i4 * 3 + 1]; var z = bufferGeometry.attributes.position.array[i4 * 3 + 2]; uvs.push(Math.atan2(x, z) / Math.PI * 0.5 + 0.5, y / Math.PI * 0.5 + 0.5); } if (bufferGeometry.attributes.uv) delete bufferGeometry.attributes.uv; bufferGeometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); bufferGeometry.attributes.uv.needsUpdate = true; return bufferGeometry; } function applySphereUV(bufferGeometry) { var uvs = []; var vertices = []; for (var i4 = 0; i4 < bufferGeometry.attributes.position.array.length / 3; i4++) { var x = bufferGeometry.attributes.position.array[i4 * 3 + 0]; var y = bufferGeometry.attributes.position.array[i4 * 3 + 1]; var z = bufferGeometry.attributes.position.array[i4 * 3 + 2]; vertices.push(new Vector3(x, y, z)); } var polarVertices = vertices.map(cartesian2polar); for (var _i = 0; _i < polarVertices.length / 3; _i++) { var tri = new Triangle(vertices[_i * 3 + 0], vertices[_i * 3 + 1], vertices[_i * 3 + 2]); var normal2 = tri.getNormal(new Vector3()); for (var f2 = 0; f2 < 3; f2++) { var vertex = polarVertices[_i * 3 + f2]; if (vertex.theta === 0 && (vertex.phi === 0 || vertex.phi === Math.PI)) { var alignedVertice = vertex.phi === 0 ? _i * 3 + 1 : _i * 3 + 0; vertex = { r: vertex.r, phi: vertex.phi, theta: polarVertices[alignedVertice].theta }; } if (vertex.theta === Math.PI && cartesian2polar(normal2).theta < Math.PI / 2) { vertex.theta = -Math.PI; } var canvasPoint = polar2canvas(vertex); uvs.push(1 - canvasPoint.x, 1 - canvasPoint.y); } } if (bufferGeometry.attributes.uv) delete bufferGeometry.attributes.uv; bufferGeometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); bufferGeometry.attributes.uv.needsUpdate = true; return bufferGeometry; } function cartesian2polar(position2) { var r2 = Math.sqrt(position2.x * position2.x + position2.z * position2.z + position2.y * position2.y); return { r: r2, phi: Math.acos(position2.y / r2), theta: Math.atan2(position2.z, position2.x) }; } function polar2canvas(polarPoint) { return { y: polarPoint.phi / Math.PI, x: (polarPoint.theta + Math.PI) / (2 * Math.PI) }; } function applyBoxUV(bufferGeometry) { bufferGeometry.computeBoundingBox(); var bboxSize = bufferGeometry.boundingBox.getSize(new Vector3()); var boxSize = Math.min(bboxSize.x, bboxSize.y, bboxSize.z); var boxGeometry = new BoxGeometry(boxSize, boxSize, boxSize); var cube = new Mesh(boxGeometry); cube.rotation.set(0, 0, 0); cube.updateWorldMatrix(true, false); var transformMatrix = cube.matrix.clone().invert(); var uvBbox = new Box3(new Vector3(-boxSize / 2, -boxSize / 2, -boxSize / 2), new Vector3(boxSize / 2, boxSize / 2, boxSize / 2)); _applyBoxUV(bufferGeometry, transformMatrix, uvBbox, boxSize); bufferGeometry.attributes.uv.needsUpdate = true; return bufferGeometry; } function _applyBoxUV(geom, transformMatrix, bbox, bbox_max_size) { var coords = []; coords.length = 2 * geom.attributes.position.array.length / 3; var makeUVs = function makeUVs2(v02, v14, v23) { v02.applyMatrix4(transformMatrix); v14.applyMatrix4(transformMatrix); v23.applyMatrix4(transformMatrix); var n2 = new Vector3(); n2.crossVectors(v14.clone().sub(v02), v14.clone().sub(v23)).normalize(); n2.x = Math.abs(n2.x); n2.y = Math.abs(n2.y); n2.z = Math.abs(n2.z); var uv0 = new Vector2(); var uv1 = new Vector2(); var uv2 = new Vector2(); if (n2.y > n2.x && n2.y > n2.z) { uv0.x = (v02.x - bbox.min.x) / bbox_max_size; uv0.y = (bbox.max.z - v02.z) / bbox_max_size; uv1.x = (v14.x - bbox.min.x) / bbox_max_size; uv1.y = (bbox.max.z - v14.z) / bbox_max_size; uv2.x = (v23.x - bbox.min.x) / bbox_max_size; uv2.y = (bbox.max.z - v23.z) / bbox_max_size; } else if (n2.x > n2.y && n2.x > n2.z) { uv0.x = (v02.z - bbox.min.z) / bbox_max_size; uv0.y = (v02.y - bbox.min.y) / bbox_max_size; uv1.x = (v14.z - bbox.min.z) / bbox_max_size; uv1.y = (v14.y - bbox.min.y) / bbox_max_size; uv2.x = (v23.z - bbox.min.z) / bbox_max_size; uv2.y = (v23.y - bbox.min.y) / bbox_max_size; } else if (n2.z > n2.y && n2.z > n2.x) { uv0.x = (v02.x - bbox.min.x) / bbox_max_size; uv0.y = (v02.y - bbox.min.y) / bbox_max_size; uv1.x = (v14.x - bbox.min.x) / bbox_max_size; uv1.y = (v14.y - bbox.min.y) / bbox_max_size; uv2.x = (v23.x - bbox.min.x) / bbox_max_size; uv2.y = (v23.y - bbox.min.y) / bbox_max_size; } return { uv0, uv1, uv2 }; }; if (geom.index) { for (var vi = 0; vi < geom.index.array.length; vi += 3) { var idx0 = geom.index.array[vi]; var idx1 = geom.index.array[vi + 1]; var idx2 = geom.index.array[vi + 2]; var vx0 = geom.attributes.position.array[3 * idx0]; var vy0 = geom.attributes.position.array[3 * idx0 + 1]; var vz0 = geom.attributes.position.array[3 * idx0 + 2]; var vx1 = geom.attributes.position.array[3 * idx1]; var vy1 = geom.attributes.position.array[3 * idx1 + 1]; var vz1 = geom.attributes.position.array[3 * idx1 + 2]; var vx2 = geom.attributes.position.array[3 * idx2]; var vy2 = geom.attributes.position.array[3 * idx2 + 1]; var vz2 = geom.attributes.position.array[3 * idx2 + 2]; var v0 = new Vector3(vx0, vy0, vz0); var v13 = new Vector3(vx1, vy1, vz1); var v22 = new Vector3(vx2, vy2, vz2); var uvs = makeUVs(v0, v13, v22); coords[2 * idx0] = uvs.uv0.x; coords[2 * idx0 + 1] = uvs.uv0.y; coords[2 * idx1] = uvs.uv1.x; coords[2 * idx1 + 1] = uvs.uv1.y; coords[2 * idx2] = uvs.uv2.x; coords[2 * idx2 + 1] = uvs.uv2.y; } } else { for (var _vi = 0; _vi < geom.attributes.position.array.length; _vi += 9) { var _vx = geom.attributes.position.array[_vi]; var _vy = geom.attributes.position.array[_vi + 1]; var _vz = geom.attributes.position.array[_vi + 2]; var _vx2 = geom.attributes.position.array[_vi + 3]; var _vy2 = geom.attributes.position.array[_vi + 4]; var _vz2 = geom.attributes.position.array[_vi + 5]; var _vx3 = geom.attributes.position.array[_vi + 6]; var _vy3 = geom.attributes.position.array[_vi + 7]; var _vz3 = geom.attributes.position.array[_vi + 8]; var _v4 = new Vector3(_vx, _vy, _vz); var _v26 = new Vector3(_vx2, _vy2, _vz2); var _v32 = new Vector3(_vx3, _vy3, _vz3); var _uvs = makeUVs(_v4, _v26, _v32); var _idx = _vi / 3; var _idx2 = _idx + 1; var _idx3 = _idx + 2; coords[2 * _idx] = _uvs.uv0.x; coords[2 * _idx + 1] = _uvs.uv0.y; coords[2 * _idx2] = _uvs.uv1.x; coords[2 * _idx2 + 1] = _uvs.uv1.y; coords[2 * _idx3] = _uvs.uv2.x; coords[2 * _idx3 + 1] = _uvs.uv2.y; } } if (geom.attributes.uv) delete geom.attributes.uv; geom.setAttribute("uv", new Float32BufferAttribute(coords, 2)); } var geometry = Object.freeze({ __proto__: null, RoundedPlaneGeometry, applyCylindricalUV, applySphereUV, applyBoxUV }); // node_modules/maath/dist/three-eb2ad8c0.esm.js function bufferToVectors(buffer2) { var stride = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 3; var p2 = []; for (var i4 = 0, j = 0; i4 < buffer2.length; i4 += stride, j++) { if (stride === 3) { p2[j] = new Vector3(buffer2[i4], buffer2[i4 + 1], buffer2[i4 + 2]); } else { p2[j] = new Vector2(buffer2[i4], buffer2[i4 + 1]); } } return p2; } function vectorsToBuffer(vectorArray) { var l2 = vectorArray.length; var stride = vectorArray[0].hasOwnProperty("z") ? 3 : 2; var buffer2 = new Float32Array(l2 * stride); for (var i4 = 0; i4 < l2; i4++) { var j = i4 * stride; buffer2[j] = vectorArray[i4].x; buffer2[j + 1] = vectorArray[i4].y; if (stride === 3) { buffer2[j + 2] = vectorArray[i4].z; } } return buffer2; } var three = Object.freeze({ __proto__: null, bufferToVectors, vectorsToBuffer }); // node_modules/@react-three/drei/web/ScrollControls.js var context2 = React8.createContext(null); function useScroll() { return React8.useContext(context2); } function ScrollControls({ eps: eps2 = 1e-5, enabled = true, infinite, horizontal, pages = 1, distance: distance3 = 1, damping = 0.25, maxSpeed = Infinity, prepend = false, style = {}, children }) { const { get, setEvents, gl, size: size2, invalidate, events } = useThree(); const [el] = React8.useState(() => document.createElement("div")); const [fill] = React8.useState(() => document.createElement("div")); const [fixed] = React8.useState(() => document.createElement("div")); const target2 = gl.domElement.parentNode; const scroll = React8.useRef(0); const state = React8.useMemo(() => { const state2 = { el, eps: eps2, fill, fixed, horizontal, damping, offset: 0, delta: 0, scroll, pages, // 0-1 for a range between from -> from + distance range(from, distance4, margin = 0) { const start = from - margin; const end = start + distance4 + margin * 2; return this.offset < start ? 0 : this.offset > end ? 1 : (this.offset - start) / (end - start); }, // 0-1-0 for a range between from -> from + distance curve(from, distance4, margin = 0) { return Math.sin(this.range(from, distance4, margin) * Math.PI); }, // true/false for a range between from -> from + distance visible(from, distance4, margin = 0) { const start = from - margin; const end = start + distance4 + margin * 2; return this.offset >= start && this.offset <= end; } }; return state2; }, [eps2, damping, horizontal, pages]); React8.useEffect(() => { el.style.position = "absolute"; el.style.width = "100%"; el.style.height = "100%"; el.style[horizontal ? "overflowX" : "overflowY"] = "auto"; el.style[horizontal ? "overflowY" : "overflowX"] = "hidden"; el.style.top = "0px"; el.style.left = "0px"; for (const key in style) { el.style[key] = style[key]; } fixed.style.position = "sticky"; fixed.style.top = "0px"; fixed.style.left = "0px"; fixed.style.width = "100%"; fixed.style.height = "100%"; fixed.style.overflow = "hidden"; el.appendChild(fixed); fill.style.height = horizontal ? "100%" : `${pages * distance3 * 100}%`; fill.style.width = horizontal ? `${pages * distance3 * 100}%` : "100%"; fill.style.pointerEvents = "none"; el.appendChild(fill); if (prepend) target2.prepend(el); else target2.appendChild(el); el[horizontal ? "scrollLeft" : "scrollTop"] = 1; const oldTarget = events.connected || gl.domElement; requestAnimationFrame(() => events.connect == null ? void 0 : events.connect(el)); const oldCompute = get().events.compute; setEvents({ compute(event, state2) { const { left, top } = target2.getBoundingClientRect(); const offsetX = event.clientX - left; const offsetY = event.clientY - top; state2.pointer.set(offsetX / state2.size.width * 2 - 1, -(offsetY / state2.size.height) * 2 + 1); state2.raycaster.setFromCamera(state2.pointer, state2.camera); } }); return () => { target2.removeChild(el); setEvents({ compute: oldCompute }); events.connect == null || events.connect(oldTarget); }; }, [pages, distance3, horizontal, el, fill, fixed, target2]); React8.useEffect(() => { if (events.connected === el) { const containerLength = size2[horizontal ? "width" : "height"]; const scrollLength = el[horizontal ? "scrollWidth" : "scrollHeight"]; const scrollThreshold = scrollLength - containerLength; let current = 0; let disableScroll = true; let firstRun = true; const onScroll = () => { if (!enabled || firstRun) return; invalidate(); current = el[horizontal ? "scrollLeft" : "scrollTop"]; scroll.current = current / scrollThreshold; if (infinite) { if (!disableScroll) { if (current >= scrollThreshold) { const damp5 = 1 - state.offset; el[horizontal ? "scrollLeft" : "scrollTop"] = 1; scroll.current = state.offset = -damp5; disableScroll = true; } else if (current <= 0) { const damp5 = 1 + state.offset; el[horizontal ? "scrollLeft" : "scrollTop"] = scrollLength; scroll.current = state.offset = damp5; disableScroll = true; } } if (disableScroll) setTimeout(() => disableScroll = false, 40); } }; el.addEventListener("scroll", onScroll, { passive: true }); requestAnimationFrame(() => firstRun = false); const onWheel = (e2) => el.scrollLeft += e2.deltaY / 2; if (horizontal) el.addEventListener("wheel", onWheel, { passive: true }); return () => { el.removeEventListener("scroll", onScroll); if (horizontal) el.removeEventListener("wheel", onWheel); }; } }, [el, events, size2, infinite, state, invalidate, horizontal, enabled]); let last = 0; useFrame((_, delta) => { last = state.offset; easing.damp(state, "offset", scroll.current, damping, delta, maxSpeed, void 0, eps2); easing.damp(state, "delta", Math.abs(last - state.offset), damping, delta, maxSpeed, void 0, eps2); if (state.delta > eps2) invalidate(); }); return React8.createElement(context2.Provider, { value: state }, children); } var ScrollCanvas = React8.forwardRef(({ children }, ref) => { const group = React8.useRef(null); React8.useImperativeHandle(ref, () => group.current, []); const state = useScroll(); const { width, height } = useThree((state2) => state2.viewport); useFrame(() => { group.current.position.x = state.horizontal ? -width * (state.pages - 1) * state.offset : 0; group.current.position.y = state.horizontal ? 0 : height * (state.pages - 1) * state.offset; }); return React8.createElement("group", { ref: group }, children); }); var ScrollHtml = React8.forwardRef(({ children, style, ...props }, ref) => { const state = useScroll(); const group = React8.useRef(null); React8.useImperativeHandle(ref, () => group.current, []); const { width, height } = useThree((state2) => state2.size); const fiberState = React8.useContext(context); const root = React8.useMemo(() => ReactDOM2.createRoot(state.fixed), [state.fixed]); useFrame(() => { if (state.delta > state.eps) { group.current.style.transform = `translate3d(${state.horizontal ? -width * (state.pages - 1) * state.offset : 0}px,${state.horizontal ? 0 : height * (state.pages - 1) * -state.offset}px,0)`; } }); root.render(React8.createElement("div", _extends({ ref: group, style: { ...style, position: "absolute", top: 0, left: 0, willChange: "transform" } }, props), React8.createElement(context2.Provider, { value: state }, React8.createElement(context.Provider, { value: fiberState }, children)))); return null; }); var Scroll = React8.forwardRef(({ html, ...props }, ref) => { const El = html ? ScrollHtml : ScrollCanvas; return React8.createElement(El, _extends({ ref }, props)); }); // node_modules/@react-three/drei/web/PresentationControls.js var React9 = __toESM(require_react()); function PresentationControls({ enabled = true, snap, global: global2, domElement, cursor = true, children, speed = 1, rotation: rotation3 = [0, 0, 0], zoom = 1, polar = [0, Math.PI / 2], azimuth = [-Infinity, Infinity], damping = 0.25 }) { const events = useThree((state) => state.events); const gl = useThree((state) => state.gl); const explDomElement = domElement || events.connected || gl.domElement; const { size: size2 } = useThree(); const rPolar = React9.useMemo(() => [rotation3[0] + polar[0], rotation3[0] + polar[1]], [rotation3[0], polar[0], polar[1]]); const rAzimuth = React9.useMemo(() => [rotation3[1] + azimuth[0], rotation3[1] + azimuth[1]], [rotation3[1], azimuth[0], azimuth[1]]); const rInitial = React9.useMemo(() => [MathUtils.clamp(rotation3[0], ...rPolar), MathUtils.clamp(rotation3[1], ...rAzimuth), rotation3[2]], [rotation3[0], rotation3[1], rotation3[2], rPolar, rAzimuth]); React9.useEffect(() => { if (global2 && cursor && enabled) { explDomElement.style.cursor = "grab"; gl.domElement.style.cursor = ""; return () => { explDomElement.style.cursor = "default"; gl.domElement.style.cursor = "default"; }; } }, [global2, cursor, explDomElement, enabled]); const [animation] = React9.useState({ scale: 1, rotation: rInitial, damping }); const ref = React9.useRef(null); useFrame((state, delta) => { easing.damp3(ref.current.scale, animation.scale, animation.damping, delta); easing.dampE(ref.current.rotation, animation.rotation, animation.damping, delta); }); const bind = useGesture({ onHover: ({ last }) => { if (cursor && !global2 && enabled) explDomElement.style.cursor = last ? "auto" : "grab"; }, onDrag: ({ down, delta: [x, y], memo: [oldY, oldX] = animation.rotation || rInitial }) => { if (!enabled) return [y, x]; if (cursor) explDomElement.style.cursor = down ? "grabbing" : "grab"; x = MathUtils.clamp(oldX + x / size2.width * Math.PI * speed, ...rAzimuth); y = MathUtils.clamp(oldY + y / size2.height * Math.PI * speed, ...rPolar); animation.scale = down && y > rPolar[1] / 2 ? zoom : 1; animation.rotation = snap && !down ? rInitial : [y, x, 0]; animation.damping = snap && !down && typeof snap !== "boolean" ? snap : damping; return [y, x]; } }, { target: global2 ? explDomElement : void 0 }); return React9.createElement("group", _extends({ ref }, bind == null ? void 0 : bind()), children); } // node_modules/@react-three/drei/web/KeyboardControls.js var React10 = __toESM(require_react()); var context3 = React10.createContext(null); function KeyboardControls({ map: map2, children, onChange, domElement }) { const key = map2.map((item) => item.name + item.keys).join("-"); const useControls = React10.useMemo(() => { return create(subscribeWithSelector(() => map2.reduce((prev, cur) => ({ ...prev, [cur.name]: false }), {}))); }, [key]); const api = React10.useMemo(() => [useControls.subscribe, useControls.getState, useControls], [key]); const set = useControls.setState; React10.useEffect(() => { const config = map2.map(({ name, keys, up }) => ({ keys, up, fn: (value) => { set({ [name]: value }); if (onChange) onChange(name, value, api[1]()); } })); const keyMap = config.reduce((out7, { keys, fn, up = true }) => { keys.forEach((key2) => out7[key2] = { fn, pressed: false, up }); return out7; }, {}); const downHandler = ({ key: key2, code }) => { const obj = keyMap[key2] || keyMap[code]; if (!obj) return; const { fn, pressed, up } = obj; obj.pressed = true; if (up || !pressed) fn(true); }; const upHandler = ({ key: key2, code }) => { const obj = keyMap[key2] || keyMap[code]; if (!obj) return; const { fn, up } = obj; obj.pressed = false; if (up) fn(false); }; const source = domElement || window; source.addEventListener("keydown", downHandler, { passive: true }); source.addEventListener("keyup", upHandler, { passive: true }); return () => { source.removeEventListener("keydown", downHandler); source.removeEventListener("keyup", upHandler); }; }, [domElement, key]); return React10.createElement(context3.Provider, { value: api, children }); } function useKeyboardControls(sel) { const [sub3, get, store] = React10.useContext(context3); if (sel) return store(sel); else return [sub3, get]; } // node_modules/@react-three/drei/web/Select.js var React12 = __toESM(require_react()); // node_modules/three-stdlib/math/ConvexHull.js var _v1 = new Vector3(); var _line3 = new Line3(); var _plane = new Plane(); var _closestPoint = new Vector3(); var _triangle = new Triangle(); // node_modules/three-stdlib/misc/ConvexObjectBreaker.js var _v12 = new Vector3(); // node_modules/three-stdlib/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(); // node_modules/three-stdlib/_polyfill/constants.js var version = (() => parseInt(REVISION.replace(/\D+/g, "")))(); // node_modules/three-stdlib/_polyfill/uv1.js var UV1 = version >= 125 ? "uv1" : "uv2"; // node_modules/three-stdlib/renderers/CSS2DRenderer.js var _vector = new Vector3(); var _viewMatrix = new Matrix4(); var _viewProjectionMatrix = new Matrix4(); var _a = new Vector3(); var _b = new Vector3(); // node_modules/three-stdlib/renderers/CSS3DRenderer.js var _position2 = new Vector3(); var _quaternion = new Quaternion(); var _scale = new Vector3(); var _matrix = new Matrix4(); var _matrix2 = new Matrix4(); // node_modules/three-stdlib/modifiers/CurveModifier.js var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var CHANNELS = 4; var TEXTURE_WIDTH = 1024; var TEXTURE_HEIGHT = 4; var initSplineTexture = (numberOfCurves = 1) => { const dataArray2 = new Float32Array(TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * CHANNELS); const dataTexture = new DataTexture(dataArray2, TEXTURE_WIDTH, TEXTURE_HEIGHT * numberOfCurves, RGBAFormat, FloatType); dataTexture.wrapS = RepeatWrapping; dataTexture.wrapT = RepeatWrapping; dataTexture.magFilter = NearestFilter; dataTexture.needsUpdate = true; return dataTexture; }; var 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 i4 = 0; i4 < numberOfPoints; i4++) { const rowOffset = Math.floor(i4 / TEXTURE_WIDTH); const rowIndex = i4 % TEXTURE_WIDTH; let pt = points[i4]; setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 0 + rowOffset + TEXTURE_HEIGHT * offset); pt = frenetFrames.tangents[i4]; setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 1 + rowOffset + TEXTURE_HEIGHT * offset); pt = frenetFrames.normals[i4]; setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 2 + rowOffset + TEXTURE_HEIGHT * offset); pt = frenetFrames.binormals[i4]; setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 3 + rowOffset + TEXTURE_HEIGHT * offset); } texture.needsUpdate = true; }; var setTextureValue = (texture, index2, x, y, z, o2) => { const image = texture.image; const { data } = image; const i4 = CHANNELS * TEXTURE_WIDTH * o2; data[index2 * CHANNELS + i4 + 0] = x; data[index2 * CHANNELS + i4 + 1] = y; data[index2 * CHANNELS + i4 + 2] = z; data[index2 * CHANNELS + i4 + 3] = 1; }; var getUniforms = (splineTexture) => ({ 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 } }); 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 vertexShader3 = ( /* glsl */ ` 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 ", "").replace("#include ", "").replace("#include ", "").replace( /void\s*main\s*\(\)\s*\{/, /* glsl */ ` void main() { #include 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 ", /* glsl */ `vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 ); gl_Position = projectionMatrix * mvPosition;` ) ); shader.vertexShader = vertexShader3; }; } var Flow = class { /** * @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) { __publicField(this, "curveArray"); __publicField(this, "curveLengthArray"); __publicField(this, "object3D"); __publicField(this, "splineTexure"); __publicField(this, "uniforms"); const obj3D = mesh.clone(); const splineTexure = initSplineTexture(numberOfCurves); const uniforms = getUniforms(splineTexure); obj3D.traverse((child) => { if (child instanceof Mesh || child instanceof InstancedMesh) { child.material = child.material.clone(); modifyShader(child.material, uniforms, numberOfCurves); } }); this.curveArray = new Array(numberOfCurves); this.curveLengthArray = new Array(numberOfCurves); this.object3D = obj3D; this.splineTexure = splineTexure; this.uniforms = uniforms; } updateCurve(index2, curve) { if (index2 >= this.curveArray.length) throw Error("Index out of range for Flow"); const curveLength = curve.getLength(); this.uniforms.spineLength.value = curveLength; this.curveLengthArray[index2] = curveLength; this.curveArray[index2] = curve; updateSplineTexture(this.splineTexure, curve, index2); } moveAlongCurve(amount) { this.uniforms.pathOffset.value += amount; } }; var matrix2 = new Matrix4(); // node_modules/three-stdlib/utils/BufferGeometryUtils.js function mergeVertices(geometry3, tolerance = 1e-4) { tolerance = Math.max(tolerance, Number.EPSILON); const hashToIndex = {}; const indices = geometry3.getIndex(); const positions = geometry3.getAttribute("position"); const vertexCount = indices ? indices.count : positions.count; let nextIndex = 0; const attributeNames = Object.keys(geometry3.attributes); const attrArrays = {}; const morphAttrsArrays = {}; const newIndices = []; const getters = ["getX", "getY", "getZ", "getW"]; for (let i4 = 0, l2 = attributeNames.length; i4 < l2; i4++) { const name = attributeNames[i4]; attrArrays[name] = []; const morphAttr = geometry3.morphAttributes[name]; if (morphAttr) { morphAttrsArrays[name] = new Array(morphAttr.length).fill(0).map(() => []); } } const decimalShift = Math.log10(1 / tolerance); const shiftMultiplier = Math.pow(10, decimalShift); for (let i4 = 0; i4 < vertexCount; i4++) { const index2 = indices ? indices.getX(i4) : i4; let hash = ""; for (let j = 0, l2 = attributeNames.length; j < l2; j++) { const name = attributeNames[j]; const attribute = geometry3.getAttribute(name); const itemSize = attribute.itemSize; for (let k = 0; k < itemSize; k++) { hash += `${~~(attribute[getters[k]](index2) * shiftMultiplier)},`; } } if (hash in hashToIndex) { newIndices.push(hashToIndex[hash]); } else { for (let j = 0, l2 = attributeNames.length; j < l2; j++) { const name = attributeNames[j]; const attribute = geometry3.getAttribute(name); const morphAttr = geometry3.morphAttributes[name]; const itemSize = attribute.itemSize; const newarray = attrArrays[name]; const newMorphArrays = morphAttrsArrays[name]; for (let k = 0; k < itemSize; k++) { const getterFunc = getters[k]; newarray.push(attribute[getterFunc](index2)); if (morphAttr) { for (let m = 0, ml = morphAttr.length; m < ml; m++) { newMorphArrays[m].push(morphAttr[m][getterFunc](index2)); } } } } hashToIndex[hash] = nextIndex; newIndices.push(nextIndex); nextIndex++; } } const result = geometry3.clone(); for (let i4 = 0, l2 = attributeNames.length; i4 < l2; i4++) { const name = attributeNames[i4]; const oldAttribute = geometry3.getAttribute(name); const buffer2 = new oldAttribute.array.constructor(attrArrays[name]); const attribute = new BufferAttribute(buffer2, oldAttribute.itemSize, oldAttribute.normalized); result.setAttribute(name, attribute); if (name in morphAttrsArrays) { for (let j = 0; j < morphAttrsArrays[name].length; j++) { const oldMorphAttribute = geometry3.morphAttributes[name][j]; const buffer22 = new oldMorphAttribute.array.constructor(morphAttrsArrays[name][j]); const morphAttribute = new BufferAttribute(buffer22, oldMorphAttribute.itemSize, oldMorphAttribute.normalized); result.morphAttributes[name][j] = morphAttribute; } } } result.setIndex(newIndices); return result; } function toTrianglesDrawMode(geometry3, drawMode) { if (drawMode === TrianglesDrawMode) { console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."); return geometry3; } if (drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode) { let index2 = geometry3.getIndex(); if (index2 === null) { const indices = []; const position2 = geometry3.getAttribute("position"); if (position2 !== void 0) { for (let i4 = 0; i4 < position2.count; i4++) { indices.push(i4); } geometry3.setIndex(indices); index2 = geometry3.getIndex(); } else { console.error( "THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible." ); return geometry3; } } const numberOfTriangles = index2.count - 2; const newIndices = []; if (index2) { if (drawMode === TriangleFanDrawMode) { for (let i4 = 1; i4 <= numberOfTriangles; i4++) { newIndices.push(index2.getX(0)); newIndices.push(index2.getX(i4)); newIndices.push(index2.getX(i4 + 1)); } } else { for (let i4 = 0; i4 < numberOfTriangles; i4++) { if (i4 % 2 === 0) { newIndices.push(index2.getX(i4)); newIndices.push(index2.getX(i4 + 1)); newIndices.push(index2.getX(i4 + 2)); } else { newIndices.push(index2.getX(i4 + 2)); newIndices.push(index2.getX(i4 + 1)); newIndices.push(index2.getX(i4)); } } } } if (newIndices.length / 3 !== numberOfTriangles) { console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles."); } const newGeometry = geometry3.clone(); newGeometry.setIndex(newIndices); newGeometry.clearGroups(); return newGeometry; } else { console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:", drawMode); return geometry3; } } function toCreasedNormals(geometry3, 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(v5) { const x = ~~(v5.x * hashMultiplier); const y = ~~(v5.y * hashMultiplier); const z = ~~(v5.z * hashMultiplier); return `${x},${y},${z}`; } const resultGeometry = geometry3.index ? geometry3.toNonIndexed() : geometry3; const posAttr = resultGeometry.attributes.position; const vertexMap = {}; for (let i4 = 0, l2 = posAttr.count / 3; i4 < l2; i4++) { const i32 = 3 * i4; const a6 = verts[0].fromBufferAttribute(posAttr, i32 + 0); const b5 = verts[1].fromBufferAttribute(posAttr, i32 + 1); const c2 = verts[2].fromBufferAttribute(posAttr, i32 + 2); tempVec1.subVectors(c2, b5); tempVec2.subVectors(a6, b5); const normal2 = 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(normal2); } } const normalArray = new Float32Array(posAttr.count * 3); const normAttr = new BufferAttribute(normalArray, 3, false); for (let i4 = 0, l2 = posAttr.count / 3; i4 < l2; i4++) { const i32 = 3 * i4; const a6 = verts[0].fromBufferAttribute(posAttr, i32 + 0); const b5 = verts[1].fromBufferAttribute(posAttr, i32 + 1); const c2 = verts[2].fromBufferAttribute(posAttr, i32 + 2); tempVec1.subVectors(c2, b5); tempVec2.subVectors(a6, b5); 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 k = 0, lk = otherNormals.length; k < lk; k++) { const otherNorm = otherNormals[k]; if (tempNorm.dot(otherNorm) > creaseDot) { tempNorm2.add(otherNorm); } } tempNorm2.normalize(); normAttr.setXYZ(i32 + n2, tempNorm2.x, tempNorm2.y, tempNorm2.z); } } resultGeometry.setAttribute("normal", normAttr); return resultGeometry; } // node_modules/three-stdlib/modifiers/SimplifyModifier.js var cb = new Vector3(); var ab = new Vector3(); // node_modules/three-stdlib/exporters/GLTFExporter.js var __defProp2 = Object.defineProperty; var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField2 = (obj, key, value) => { __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; async function readAsDataURL(blob) { const buffer2 = await blob.arrayBuffer(); const data = btoa(String.fromCharCode(...new Uint8Array(buffer2))); return `data:${blob.type || ""};base64,${data}`; } var _renderer; var fullscreenQuadGeometry; var fullscreenQuadMaterial; var fullscreenQuad; function decompress(texture, maxTextureSize = Infinity, renderer = null) { if (!fullscreenQuadGeometry) fullscreenQuadGeometry = new PlaneGeometry(2, 2, 1, 1); if (!fullscreenQuadMaterial) fullscreenQuadMaterial = new ShaderMaterial({ uniforms: { blitTexture: new Uniform(texture) }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy * 1.0,0.,.999999); } ` ), fragmentShader: ( /* glsl */ ` uniform sampler2D blitTexture; varying vec2 vUv; void main(){ gl_FragColor = vec4(vUv.xy, 0, 1); #ifdef IS_SRGB gl_FragColor = LinearTosRGB( texture2D( blitTexture, vUv) ); #else gl_FragColor = texture2D( blitTexture, vUv); #endif } ` ) }); fullscreenQuadMaterial.uniforms.blitTexture.value = texture; fullscreenQuadMaterial.defines.IS_SRGB = "colorSpace" in texture ? texture.colorSpace === "srgb" : texture.encoding === 3001; fullscreenQuadMaterial.needsUpdate = true; if (!fullscreenQuad) { fullscreenQuad = new Mesh(fullscreenQuadGeometry, fullscreenQuadMaterial); fullscreenQuad.frustrumCulled = false; } const _camera = new PerspectiveCamera(); const _scene = new Scene(); _scene.add(fullscreenQuad); if (!renderer) { renderer = _renderer = new WebGLRenderer({ antialias: false }); } renderer.setSize(Math.min(texture.image.width, maxTextureSize), Math.min(texture.image.height, maxTextureSize)); renderer.clear(); renderer.render(_scene, _camera); const readableTexture = new Texture(renderer.domElement); readableTexture.minFilter = texture.minFilter; readableTexture.magFilter = texture.magFilter; readableTexture.wrapS = texture.wrapS; readableTexture.wrapT = texture.wrapT; readableTexture.name = texture.name; if (_renderer) { _renderer.dispose(); _renderer = null; } return readableTexture; } 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 GLTFExporter2 { constructor() { 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 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); }); } register(callback) { if (this.pluginCallbacks.indexOf(callback) === -1) { this.pluginCallbacks.push(callback); } return this; } unregister(callback) { if (this.pluginCallbacks.indexOf(callback) !== -1) { this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); } return this; } /** * Parse scenes and generate GLTF output * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes * @param {Function} onDone Callback on completed * @param {Function} onError Callback on errors * @param {Object} options options */ parse(input, onDone, onError, options) { const writer = new GLTFWriter(); const plugins = []; for (let i4 = 0, il = this.pluginCallbacks.length; i4 < il; i4++) { plugins.push(this.pluginCallbacks[i4](writer)); } writer.setPlugins(plugins); writer.write(input, onDone, options).catch(onError); } parseAsync(input, options) { const scope = this; return new Promise(function(resolve, reject) { scope.parse(input, resolve, reject, options); }); } } __publicField2(GLTFExporter2, "Utils", { insertKeyframe: function(track, time) { const tolerance = 1e-3; const valueSize = track.getValueSize(); const times = new track.TimeBufferType(track.times.length + 1); const values = new track.ValueBufferType(track.values.length + valueSize); const interpolant = track.createInterpolant(new track.ValueBufferType(valueSize)); let index2; if (track.times.length === 0) { times[0] = time; for (let i4 = 0; i4 < valueSize; i4++) { values[i4] = 0; } index2 = 0; } else if (time < track.times[0]) { if (Math.abs(track.times[0] - time) < tolerance) return 0; times[0] = time; times.set(track.times, 1); values.set(interpolant.evaluate(time), 0); values.set(track.values, valueSize); index2 = 0; } else if (time > track.times[track.times.length - 1]) { if (Math.abs(track.times[track.times.length - 1] - time) < tolerance) { return track.times.length - 1; } times[times.length - 1] = time; times.set(track.times, 0); values.set(track.values, 0); values.set(interpolant.evaluate(time), track.values.length); index2 = times.length - 1; } else { for (let i4 = 0; i4 < track.times.length; i4++) { if (Math.abs(track.times[i4] - time) < tolerance) return i4; if (track.times[i4] < time && track.times[i4 + 1] > time) { times.set(track.times.slice(0, i4 + 1), 0); times[i4 + 1] = time; times.set(track.times.slice(i4 + 1), i4 + 2); values.set(track.values.slice(0, (i4 + 1) * valueSize), 0); values.set(interpolant.evaluate(time), (i4 + 1) * valueSize); values.set(track.values.slice((i4 + 1) * valueSize), (i4 + 2) * valueSize); index2 = i4 + 1; break; } } } track.times = times; track.values = values; return index2; }, mergeMorphTargetTracks: function(clip, root) { const tracks = []; const mergedTracks = {}; const sourceTracks = clip.tracks; for (let i4 = 0; i4 < sourceTracks.length; ++i4) { let sourceTrack = sourceTracks[i4]; 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 values = new mergedTrack.ValueBufferType(targetCount * mergedTrack.times.length); for (let j = 0; j < mergedTrack.times.length; j++) { values[j * targetCount + targetIndex] = mergedTrack.values[j]; } mergedTrack.name = (sourceTrackBinding.nodeName || "") + ".morphTargetInfluences"; mergedTrack.values = values; mergedTracks[sourceTrackNode.uuid] = mergedTrack; tracks.push(mergedTrack); continue; } const sourceInterpolant = sourceTrack.createInterpolant(new sourceTrack.ValueBufferType(1)); mergedTrack = mergedTracks[sourceTrackNode.uuid]; for (let j = 0; j < mergedTrack.times.length; j++) { mergedTrack.values[j * targetCount + targetIndex] = sourceInterpolant.evaluate(mergedTrack.times[j]); } for (let j = 0; j < sourceTrack.times.length; j++) { const keyframeIndex = this.insertKeyframe(mergedTrack, sourceTrack.times[j]); mergedTrack.values[keyframeIndex * targetCount + targetIndex] = sourceTrack.values[j]; } } clip.tracks = tracks; return clip; } }); return GLTFExporter2; })(); 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(text) { return new TextEncoder().encode(text).buffer; } function isIdentityMatrix(matrix6) { return equalArray(matrix6.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 i4 = start; i4 < start + count; i4++) { for (let a6 = 0; a6 < attribute.itemSize; a6++) { let value; if (attribute.itemSize > 4) { value = attribute.array[i4 * attribute.itemSize + a6]; } else { if (a6 === 0) value = attribute.getX(i4); else if (a6 === 1) value = attribute.getY(i4); else if (a6 === 2) value = attribute.getZ(i4); else if (a6 === 3) value = attribute.getW(i4); if (attribute.normalized === true) { value = MathUtils.normalize(value, attribute.array); } } output.min[a6] = Math.min(output.min[a6], value); output.max[a6] = Math.max(output.max[a6], value); } } 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 i4 = arrayBuffer.byteLength; i4 < paddedLength; i4++) { array[i4] = 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" } }; 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() }; } setPlugins(plugins) { this.plugins = plugins; } /** * Parse scenes and generate GLTF output * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes * @param {Function} onDone Callback on completed * @param {Object} options options */ async write(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; } this.processInput(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) { blob.arrayBuffer().then((result) => { const binaryChunk = getPaddedArrayBuffer(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" }); glbBlob.arrayBuffer().then(onDone); }); } else { if (json.buffers && json.buffers.length > 0) { readAsDataURL(blob).then((uri) => { json.buffers[0].uri = uri; 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} object * @return {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(normal2) { const cache = this.cache; if (cache.attributesNormalized.has(normal2)) return false; const v5 = new Vector3(); for (let i4 = 0, il = normal2.count; i4 < il; i4++) { if (Math.abs(v5.fromBufferAttribute(normal2, i4).length() - 1) > 5e-4) return false; } return true; } /** * Creates normalized normal buffer attribute. * * @param {BufferAttribute} normal * @returns {BufferAttribute} * */ createNormalizedNormalAttribute(normal2) { const cache = this.cache; if (cache.attributesNormalized.has(normal2)) return cache.attributesNormalized.get(normal2); const attribute = normal2.clone(); const v5 = new Vector3(); for (let i4 = 0, il = attribute.count; i4 < il; i4++) { v5.fromBufferAttribute(attribute, i4); if (v5.x === 0 && v5.y === 0 && v5.z === 0) { v5.setX(1); } else { v5.normalize(); } attribute.setXYZ(i4, v5.x, v5.y, v5.z); } cache.attributesNormalized.set(normal2, 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; } } buildMetalRoughTexture(metalnessMap, roughnessMap) { if (metalnessMap === roughnessMap) return metalnessMap; function getEncodingConversion(map2) { if ("colorSpace" in map2 ? map2.colorSpace === "srgb" : map2.encoding === 3001) { 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; }; } console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."); if (metalnessMap instanceof CompressedTexture) { metalnessMap = decompress(metalnessMap); } if (roughnessMap instanceof CompressedTexture) { roughnessMap = decompress(roughnessMap); } const metalness = metalnessMap ? metalnessMap.image : null; const roughness = roughnessMap ? roughnessMap.image : null; const width = Math.max(metalness ? metalness.width : 0, roughness ? roughness.width : 0); const height = Math.max(metalness ? metalness.height : 0, roughness ? roughness.height : 0); const canvas = getCanvas(); canvas.width = width; canvas.height = height; const context12 = canvas.getContext("2d"); context12.fillStyle = "#00ffff"; context12.fillRect(0, 0, width, height); const composite = context12.getImageData(0, 0, width, height); if (metalness) { context12.drawImage(metalness, 0, 0, width, height); const convert = getEncodingConversion(metalnessMap); const data = context12.getImageData(0, 0, width, height).data; for (let i4 = 2; i4 < data.length; i4 += 4) { composite.data[i4] = convert(data[i4] / 256) * 256; } } if (roughness) { context12.drawImage(roughness, 0, 0, width, height); const convert = getEncodingConversion(roughnessMap); const data = context12.getImageData(0, 0, width, height).data; for (let i4 = 1; i4 < data.length; i4 += 4) { composite.data[i4] = convert(data[i4] / 256) * 256; } } context12.putImageData(composite, 0, 0); const reference = metalnessMap || roughnessMap; const texture = reference.clone(); texture.source = new Texture(canvas).source; if ("colorSpace" in texture) texture.colorSpace = ""; else texture.encoding = 3e3; 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."); } return texture; } /** * Process a buffer to append to the default one. * @param {ArrayBuffer} buffer * @return {Integer} */ processBuffer(buffer2) { const json = this.json; const buffers = this.buffers; if (!json.buffers) json.buffers = [{ byteLength: 0 }]; buffers.push(buffer2); return 0; } /** * Process and generate a BufferView * @param {BufferAttribute} attribute * @param {number} componentType * @param {number} start * @param {number} count * @param {number} target (Optional) Target usage of the BufferView * @return {Object} */ processBufferView(attribute, componentType, start, count, target2) { 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 (target2 === 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 i4 = start; i4 < start + count; i4++) { for (let a6 = 0; a6 < attribute.itemSize; a6++) { let value; if (attribute.itemSize > 4) { value = attribute.array[i4 * attribute.itemSize + a6]; } else { if (a6 === 0) value = attribute.getX(i4); else if (a6 === 1) value = attribute.getY(i4); else if (a6 === 2) value = attribute.getZ(i4); else if (a6 === 3) value = attribute.getW(i4); if (attribute.normalized === true) { value = MathUtils.normalize(value, attribute.array); } } if (componentType === WEBGL_CONSTANTS.FLOAT) { dataView.setFloat32(offset, value, true); } else if (componentType === WEBGL_CONSTANTS.INT) { dataView.setInt32(offset, value, true); } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_INT) { dataView.setUint32(offset, value, true); } else if (componentType === WEBGL_CONSTANTS.SHORT) { dataView.setInt16(offset, value, true); } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) { dataView.setUint16(offset, value, true); } else if (componentType === WEBGL_CONSTANTS.BYTE) { dataView.setInt8(offset, value); } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) { dataView.setUint8(offset, value); } offset += componentSize; } if (offset % byteStride !== 0) { offset += byteStride - offset % byteStride; } } const bufferViewDef = { buffer: this.processBuffer(dataView.buffer), byteOffset: this.byteOffset, byteLength }; if (target2 !== void 0) bufferViewDef.target = target2; if (target2 === 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} */ processBufferViewImage(blob) { const writer = this; const json = writer.json; if (!json.bufferViews) json.bufferViews = []; return blob.arrayBuffer().then((result) => { const buffer2 = getPaddedArrayBuffer(result); const bufferViewDef = { buffer: writer.processBuffer(buffer2), byteOffset: writer.byteOffset, byteLength: buffer2.byteLength }; writer.byteOffset += buffer2.byteLength; return json.bufferViews.push(bufferViewDef) - 1; }); } /** * Process attribute to generate an accessor * @param {BufferAttribute} attribute Attribute to process * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range * @param {Integer} start (Optional) * @param {Integer} count (Optional) * @return {Integer|null} Index of the processed accessor on the "accessors" array */ processAccessor(attribute, geometry3, start, count) { const json = this.json; const types2 = { 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 = attribute.count; if (count === 0) return null; const minMax = getMinMax(attribute, start, count); let bufferViewTarget; if (geometry3 !== void 0) { bufferViewTarget = attribute === geometry3.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: types2[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 {Integer} format of the image (RGBAFormat) * @param {Boolean} flipY before writing out the image * @param {String} mimeType export format * @return {Integer} 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 key = mimeType + ":flipY/" + flipY.toString(); if (cachedImages[key] !== void 0) return cachedImages[key]; 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"); 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 data = new Uint8ClampedArray(image.height * image.width * 4); for (let i4 = 0; i4 < data.length; i4 += 4) { data[i4 + 0] = image.data[i4 + 0]; data[i4 + 1] = image.data[i4 + 1]; data[i4 + 2] = image.data[i4 + 2]; data[i4 + 3] = image.data[i4 + 3]; } ctx.putImageData(new ImageData(data, image.width, image.height), 0, 0); } else { ctx.drawImage(image, 0, 0, canvas.width, canvas.height); } if (options.binary === true) { pending.push( getToBlobPromise(canvas, mimeType).then((blob) => writer.processBufferViewImage(blob)).then((bufferViewIndex) => { imageDef.bufferView = bufferViewIndex; }) ); } else { if (canvas.toDataURL !== void 0) { imageDef.uri = canvas.toDataURL(mimeType); } else { pending.push( getToBlobPromise(canvas, mimeType).then(readAsDataURL).then((uri) => { imageDef.uri = uri; }) ); } } const index2 = json.images.push(imageDef) - 1; cachedImages[key] = 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 {Integer} 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 {Integer} Index of the processed texture in the "textures" array */ processTexture(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 = decompress(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; this._invokeAll(function(ext) { ext.writeTexture && 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 {Integer|null} Index of the processed material in the "materials" array */ processMaterial(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.5; materialDef.pbrMetallicRoughness.roughnessFactor = 0.5; } if (material.metalnessMap || material.roughnessMap) { const metalRoughTexture = this.buildMetalRoughTexture(material.metalnessMap, material.roughnessMap); const metalRoughMapDef = { index: this.processTexture(metalRoughTexture), channel: metalRoughTexture.channel }; this.applyTextureTransform(metalRoughMapDef, metalRoughTexture); materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; } if (material.map) { const baseColorMapDef = { index: this.processTexture(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: this.processTexture(material.emissiveMap), texCoord: material.emissiveMap.channel }; this.applyTextureTransform(emissiveMapDef, material.emissiveMap); materialDef.emissiveTexture = emissiveMapDef; } } if (material.normalMap) { const normalMapDef = { index: this.processTexture(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: this.processTexture(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); this._invokeAll(function(ext) { ext.writeMaterial && ext.writeMaterial(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 {Integer|null} Index of the processed mesh in the "meshes" array */ processMesh(mesh) { const cache = this.cache; const json = this.json; const meshCacheKeyParts = [mesh.geometry.uuid]; if (Array.isArray(mesh.material)) { for (let i4 = 0, l2 = mesh.material.length; i4 < l2; i4++) { meshCacheKeyParts.push(mesh.material[i4].uuid); } } else { meshCacheKeyParts.push(mesh.material.uuid); } const meshCacheKey = meshCacheKeyParts.join(":"); if (cache.meshes.has(meshCacheKey)) return cache.meshes.get(meshCacheKey); const geometry3 = 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 = { ...version >= 152 ? { uv: "TEXCOORD_0", uv1: "TEXCOORD_1", uv2: "TEXCOORD_2", uv3: "TEXCOORD_3" } : { uv: "TEXCOORD_0", uv2: "TEXCOORD_1" }, color: "COLOR_0", skinWeight: "WEIGHTS_0", skinIndex: "JOINTS_0" }; const originalNormal = geometry3.getAttribute("normal"); if (originalNormal !== void 0 && !this.isNormalizedNormalAttribute(originalNormal)) { console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."); geometry3.setAttribute("normal", this.createNormalizedNormalAttribute(originalNormal)); } let modifiedAttribute = null; for (let attributeName in geometry3.attributes) { if (attributeName.slice(0, 5) === "morph") continue; const attribute = geometry3.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); } const accessor = this.processAccessor(modifiedAttribute || attribute, geometry3); if (accessor !== null) { if (!attributeName.startsWith("_")) { this.detectMeshQuantization(attributeName, attribute); } attributes[attributeName] = accessor; cache.attributes.set(this.getUID(attribute), accessor); } } if (originalNormal !== void 0) geometry3.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 key in mesh.morphTargetDictionary) { reverseDictionary[mesh.morphTargetDictionary[key]] = key; } } for (let i4 = 0; i4 < mesh.morphTargetInfluences.length; ++i4) { const target2 = {}; let warned2 = false; for (const attributeName in geometry3.morphAttributes) { if (attributeName !== "position" && attributeName !== "normal") { if (!warned2) { console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."); warned2 = true; } continue; } const attribute = geometry3.morphAttributes[attributeName][i4]; const gltfAttributeName = attributeName.toUpperCase(); const baseAttribute = geometry3.attributes[attributeName]; if (cache.attributes.has(this.getUID(attribute, true))) { target2[gltfAttributeName] = cache.attributes.get(this.getUID(attribute, true)); continue; } const relativeAttribute = attribute.clone(); if (!geometry3.morphTargetsRelative) { for (let j = 0, jl = attribute.count; j < jl; j++) { for (let a6 = 0; a6 < attribute.itemSize; a6++) { if (a6 === 0) relativeAttribute.setX(j, attribute.getX(j) - baseAttribute.getX(j)); if (a6 === 1) relativeAttribute.setY(j, attribute.getY(j) - baseAttribute.getY(j)); if (a6 === 2) relativeAttribute.setZ(j, attribute.getZ(j) - baseAttribute.getZ(j)); if (a6 === 3) relativeAttribute.setW(j, attribute.getW(j) - baseAttribute.getW(j)); } } } target2[gltfAttributeName] = this.processAccessor(relativeAttribute, geometry3); cache.attributes.set(this.getUID(baseAttribute, true), target2[gltfAttributeName]); } targets.push(target2); weights.push(mesh.morphTargetInfluences[i4]); if (mesh.morphTargetDictionary !== void 0) targetNames.push(reverseDictionary[i4]); } meshDef.weights = weights; if (targetNames.length > 0) { meshDef.extras = {}; meshDef.extras.targetNames = targetNames; } } const isMultiMaterial = Array.isArray(mesh.material); if (isMultiMaterial && geometry3.groups.length === 0) return null; const materials = isMultiMaterial ? mesh.material : [mesh.material]; const groups = isMultiMaterial ? geometry3.groups : [{ materialIndex: 0, start: void 0, count: void 0 }]; for (let i4 = 0, il = groups.length; i4 < il; i4++) { const primitive = { mode, attributes }; this.serializeUserData(geometry3, primitive); if (targets.length > 0) primitive.targets = targets; if (geometry3.index !== null) { let cacheKey = this.getUID(geometry3.index); if (groups[i4].start !== void 0 || groups[i4].count !== void 0) { cacheKey += ":" + groups[i4].start + ":" + groups[i4].count; } if (cache.attributes.has(cacheKey)) { primitive.indices = cache.attributes.get(cacheKey); } else { primitive.indices = this.processAccessor(geometry3.index, geometry3, groups[i4].start, groups[i4].count); cache.attributes.set(cacheKey, primitive.indices); } if (primitive.indices === null) delete primitive.indices; } const material = this.processMaterial(materials[groups[i4].materialIndex]); if (material !== null) primitive.material = material; primitives.push(primitive); } meshDef.primitives = primitives; if (!json.meshes) json.meshes = []; this._invokeAll(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 {Integer} 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 i4 = 0; i4 < tracks.length; ++i4) { const track = tracks[i4]; 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); return null; } 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 i4 = 0; i4 < skeleton.bones.length; ++i4) { joints.push(nodeMap.get(skeleton.bones[i4])); temporaryBoneInverse.copy(skeleton.boneInverses[i4]); temporaryBoneInverse.multiply(object.bindMatrix).toArray(inverseBindMatrices, i4 * 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} node Object3D to processNode * @return {Integer} Index of the node in the nodes list */ processNode(object) { const json = this.json; const options = this.options; const nodeMap = this.nodeMap; if (!json.nodes) json.nodes = []; const nodeDef = {}; if (options.trs) { const rotation3 = object.quaternion.toArray(); const position2 = object.position.toArray(); const scale5 = object.scale.toArray(); if (!equalArray(rotation3, [0, 0, 0, 1])) { nodeDef.rotation = rotation3; } if (!equalArray(position2, [0, 0, 0])) { nodeDef.translation = position2; } if (!equalArray(scale5, [1, 1, 1])) { nodeDef.scale = scale5; } } 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 = this.processMesh(object); if (meshIndex !== null) nodeDef.mesh = meshIndex; } else if (object.isCamera) { nodeDef.camera = this.processCamera(object); } if (object.isSkinnedMesh) this.skins.push(object); if (object.children.length > 0) { const children = []; for (let i4 = 0, l2 = object.children.length; i4 < l2; i4++) { const child = object.children[i4]; if (child.visible || options.onlyVisible === false) { const nodeIndex2 = this.processNode(child); if (nodeIndex2 !== null) children.push(nodeIndex2); } } if (children.length > 0) nodeDef.children = children; } this._invokeAll(function(ext) { ext.writeNode && ext.writeNode(object, nodeDef); }); const nodeIndex = json.nodes.push(nodeDef) - 1; nodeMap.set(object, nodeIndex); return nodeIndex; } /** * Process Scene * @param {Scene} node Scene to process */ processScene(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 i4 = 0, l2 = scene.children.length; i4 < l2; i4++) { const child = scene.children[i4]; if (child.visible || options.onlyVisible === false) { const nodeIndex = this.processNode(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} objects List of objects to process */ processObjects(objects) { const scene = new Scene(); scene.name = "AuxScene"; for (let i4 = 0; i4 < objects.length; i4++) { scene.children.push(objects[i4]); } this.processScene(scene); } /** * @param {THREE.Object3D|Array} input */ processInput(input) { const options = this.options; input = input instanceof Array ? input : [input]; this._invokeAll(function(ext) { ext.beforeParse && ext.beforeParse(input); }); const objectsWithoutScene = []; for (let i4 = 0; i4 < input.length; i4++) { if (input[i4] instanceof Scene) { this.processScene(input[i4]); } else { objectsWithoutScene.push(input[i4]); } } if (objectsWithoutScene.length > 0) this.processObjects(objectsWithoutScene); for (let i4 = 0; i4 < this.skins.length; ++i4) { this.processSkin(this.skins[i4]); } for (let i4 = 0; i4 < options.animations.length; ++i4) { this.processAnimation(options.animations[i4], input[0]); } this._invokeAll(function(ext) { ext.afterParse && ext.afterParse(input); }); } _invokeAll(func) { for (let i4 = 0, il = this.plugins.length; i4 < il; i4++) { func(this.plugins[i4]); } } }; 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 = (light.penumbra - 1) * light.angle * -1; 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"; } writeMaterial(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"; } writeMaterial(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: writer.processTexture(material.clearcoatMap), texCoord: material.clearcoatMap.channel }; writer.applyTextureTransform(clearcoatMapDef, material.clearcoatMap); extensionDef.clearcoatTexture = clearcoatMapDef; } extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness; if (material.clearcoatRoughnessMap) { const clearcoatRoughnessMapDef = { index: writer.processTexture(material.clearcoatRoughnessMap), texCoord: material.clearcoatRoughnessMap.channel }; writer.applyTextureTransform(clearcoatRoughnessMapDef, material.clearcoatRoughnessMap); extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef; } if (material.clearcoatNormalMap) { const clearcoatNormalMapDef = { index: writer.processTexture(material.clearcoatNormalMap), texCoord: material.clearcoatNormalMap.channel }; writer.applyTextureTransform(clearcoatNormalMapDef, material.clearcoatNormalMap); extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef; } 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"; } writeMaterial(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: writer.processTexture(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: writer.processTexture(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"; } writeMaterial(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: writer.processTexture(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"; } writeMaterial(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: writer.processTexture(material.thicknessMap), texCoord: material.thicknessMap.channel }; writer.applyTextureTransform(thicknessMapDef, material.thicknessMap); extensionDef.thicknessTexture = thicknessMapDef; } 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"; } writeMaterial(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"; } writeMaterial(material, materialDef) { if (!material.isMeshPhysicalMaterial || material.specularIntensity === 1 && material.specularColor.equals(DEFAULT_SPECULAR_COLOR) && !material.specularIntensityMap && !material.specularColorTexture) return; const writer = this.writer; const extensionsUsed = writer.extensionsUsed; const extensionDef = {}; if (material.specularIntensityMap) { const specularIntensityMapDef = { index: writer.processTexture(material.specularIntensityMap), texCoord: material.specularIntensityMap.channel }; writer.applyTextureTransform(specularIntensityMapDef, material.specularIntensityMap); extensionDef.specularTexture = specularIntensityMapDef; } if (material.specularColorMap) { const specularColorMapDef = { index: writer.processTexture(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"; } writeMaterial(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: writer.processTexture(material.sheenRoughnessMap), texCoord: material.sheenRoughnessMap.channel }; writer.applyTextureTransform(sheenRoughnessMapDef, material.sheenRoughnessMap); extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef; } if (material.sheenColorMap) { const sheenColorMapDef = { index: writer.processTexture(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"; } writeMaterial(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: writer.processTexture(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"; } writeMaterial(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; } }; // node_modules/three-stdlib/node_modules/fflate/esm/browser.js var ch2 = {}; var wk = (function(c2, id, msg, transfer, cb2) { var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([c2], { type: "text/javascript" })))); w.onerror = function(e2) { return cb2(e2.error, null); }; w.onmessage = function(e2) { return cb2(null, e2.data); }; w.postMessage(msg, transfer); return w; }); var u8 = Uint8Array; var u16 = Uint16Array; var u32 = Uint32Array; 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 b5 = new u16(31); for (var i4 = 0; i4 < 31; ++i4) { b5[i4] = start += 1 << eb[i4 - 1]; } var r2 = new u32(b5[30]); for (var i4 = 1; i4 < 30; ++i4) { for (var j = b5[i4]; j < b5[i4 + 1]; ++j) { r2[j] = j - b5[i4] << 5 | i4; } } return [b5, r2]; }; var _a2 = freb(fleb, 2); var fl = _a2[0]; var revfl = _a2[1]; fl[28] = 258, revfl[258] = 28; var _b2 = freb(fdeb, 0); var fd = _b2[0]; var revfd = _b2[1]; var rev = new u16(32768); for (i4 = 0; i4 < 32768; ++i4) { x = (i4 & 43690) >>> 1 | (i4 & 21845) << 1; x = (x & 52428) >>> 2 | (x & 13107) << 2; x = (x & 61680) >>> 4 | (x & 3855) << 4; rev[i4] = ((x & 65280) >>> 8 | (x & 255) << 8) >>> 1; } var x; var i4; var hMap = (function(cd, mb, r2) { var s2 = cd.length; var i4 = 0; var l2 = new u16(mb); for (; i4 < s2; ++i4) ++l2[cd[i4] - 1]; var le = new u16(mb); for (i4 = 0; i4 < mb; ++i4) { le[i4] = le[i4 - 1] + l2[i4 - 1] << 1; } var co; if (r2) { co = new u16(1 << mb); var rvb = 15 - mb; for (i4 = 0; i4 < s2; ++i4) { if (cd[i4]) { var sv = i4 << 4 | cd[i4]; var r_1 = mb - cd[i4]; var v5 = le[cd[i4] - 1]++ << r_1; for (var m = v5 | (1 << r_1) - 1; v5 <= m; ++v5) { co[rev[v5] >>> rvb] = sv; } } } } else { co = new u16(s2); for (i4 = 0; i4 < s2; ++i4) { if (cd[i4]) { co[i4] = rev[le[cd[i4] - 1]++] >>> 15 - cd[i4]; } } } return co; }); var flt = new u8(288); for (i4 = 0; i4 < 144; ++i4) flt[i4] = 8; var i4; for (i4 = 144; i4 < 256; ++i4) flt[i4] = 9; var i4; for (i4 = 256; i4 < 280; ++i4) flt[i4] = 7; var i4; for (i4 = 280; i4 < 288; ++i4) flt[i4] = 8; var i4; var fdt = new u8(32); for (i4 = 0; i4 < 32; ++i4) fdt[i4] = 5; var i4; 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(a6) { var m = a6[0]; for (var i4 = 1; i4 < a6.length; ++i4) { if (a6[i4] > m) m = a6[i4]; } return m; }; var bits = function(d2, p2, m) { var o2 = p2 / 8 | 0; return (d2[o2] | d2[o2 + 1] << 8) >> (p2 & 7) & m; }; var bits16 = function(d2, p2) { var o2 = p2 / 8 | 0; return (d2[o2] | d2[o2 + 1] << 8 | d2[o2 + 2] << 16) >> (p2 & 7); }; var shft = function(p2) { return (p2 / 8 | 0) + (p2 & 7 && 1); }; var slc = function(v5, s2, e2) { if (s2 == null || s2 < 0) s2 = 0; if (e2 == null || e2 > v5.length) e2 = v5.length; var n2 = new (v5 instanceof u16 ? u16 : v5 instanceof u32 ? u32 : u8)(e2 - s2); n2.set(v5.subarray(s2, e2)); return n2; }; var inflt = function(dat, buf, st) { var sl = dat.length; if (!sl || st && !st.l && sl < 5) return buf || new u8(0); var noBuf = !buf || st; var noSt = !st || st.i; if (!st) st = {}; if (!buf) 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) { st.f = final = bits(dat, pos, 1); var type = bits(dat, pos + 1, 3); pos += 3; if (!type) { var s2 = shft(pos) + 4, l2 = dat[s2 - 4] | dat[s2 - 3] << 8, t3 = s2 + l2; if (t3 > sl) { if (noSt) throw "unexpected EOF"; break; } if (noBuf) cbuf(bt + l2); buf.set(dat.subarray(s2, t3), bt); st.b = bt += l2, st.p = pos = t3 * 8; 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 i4 = 0; i4 < hcLen; ++i4) { clt[clim[i4]] = bits(dat, pos + i4 * 3, 7); } pos += hcLen * 3; var clb = max(clt), clbmsk = (1 << clb) - 1; var clm = hMap(clt, clb, 1); for (var i4 = 0; i4 < tl; ) { var r2 = clm[bits(dat, pos, clbmsk)]; pos += r2 & 15; var s2 = r2 >>> 4; if (s2 < 16) { ldt[i4++] = s2; } else { var c2 = 0, n2 = 0; if (s2 == 16) n2 = 3 + bits(dat, pos, 3), pos += 2, c2 = ldt[i4 - 1]; else if (s2 == 17) n2 = 3 + bits(dat, pos, 7), pos += 3; else if (s2 == 18) n2 = 11 + bits(dat, pos, 127), pos += 7; while (n2--) ldt[i4++] = 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 throw "invalid block type"; if (pos > tbts) { if (noSt) throw "unexpected EOF"; break; } } if (noBuf) 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) throw "unexpected EOF"; break; } if (!c2) throw "invalid length/literal"; if (sym < 256) buf[bt++] = sym; else if (sym == 256) { lpos = pos, lm = null; break; } else { var add3 = sym - 254; if (sym > 264) { var i4 = sym - 257, b5 = fleb[i4]; add3 = bits(dat, pos, (1 << b5) - 1) + fl[i4]; pos += b5; } var d2 = dm[bits16(dat, pos) & dms], dsym = d2 >>> 4; if (!d2) throw "invalid distance"; pos += d2 & 15; var dt = fd[dsym]; if (dsym > 3) { var b5 = fdeb[dsym]; dt += bits16(dat, pos) & (1 << b5) - 1, pos += b5; } if (pos > tbts) { if (noSt) throw "unexpected EOF"; break; } if (noBuf) cbuf(bt + 131072); var end = bt + add3; for (; bt < end; bt += 4) { buf[bt] = buf[bt - dt]; buf[bt + 1] = buf[bt + 1 - dt]; buf[bt + 2] = buf[bt + 2 - dt]; buf[bt + 3] = buf[bt + 3 - dt]; } bt = end; } } st.l = lm, st.p = lpos, st.b = bt; if (lm) final = 1, st.m = lbt, st.d = dm, st.n = dbt; } while (!final); return bt == buf.length ? buf : slc(buf, 0, bt); }; var wbits = function(d2, p2, v5) { v5 <<= p2 & 7; var o2 = p2 / 8 | 0; d2[o2] |= v5; d2[o2 + 1] |= v5 >>> 8; }; var wbits16 = function(d2, p2, v5) { v5 <<= p2 & 7; var o2 = p2 / 8 | 0; d2[o2] |= v5; d2[o2 + 1] |= v5 >>> 8; d2[o2 + 2] |= v5 >>> 16; }; var hTree = function(d2, mb) { var t3 = []; for (var i4 = 0; i4 < d2.length; ++i4) { if (d2[i4]) t3.push({ s: i4, f: d2[i4] }); } var s2 = t3.length; var t22 = t3.slice(); if (!s2) return [et, 0]; if (s2 == 1) { var v5 = new u8(t3[0].s + 1); v5[t3[0].s] = 1; return [v5, 1]; } t3.sort(function(a6, b5) { return a6.f - b5.f; }); t3.push({ s: -1, f: 25001 }); var l2 = t3[0], r2 = t3[1], i0 = 0, i1 = 1, i22 = 2; t3[0] = { s: -1, f: l2.f + r2.f, l: l2, r: r2 }; while (i1 != s2 - 1) { l2 = t3[t3[i0].f < t3[i22].f ? i0++ : i22++]; r2 = t3[i0 != i1 && t3[i0].f < t3[i22].f ? i0++ : i22++]; t3[i1++] = { s: -1, f: l2.f + r2.f, l: l2, r: r2 }; } var maxSym = t22[0].s; for (var i4 = 1; i4 < s2; ++i4) { if (t22[i4].s > maxSym) maxSym = t22[i4].s; } var tr = new u16(maxSym + 1); var mbt = ln(t3[i1 - 1], tr, 0); if (mbt > mb) { var i4 = 0, dt = 0; var lft = mbt - mb, cst = 1 << lft; t22.sort(function(a6, b5) { return tr[b5.s] - tr[a6.s] || a6.f - b5.f; }); for (; i4 < s2; ++i4) { var i2_1 = t22[i4].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[i4].s; if (tr[i2_2] < mb) dt -= 1 << mb - tr[i2_2]++ - 1; else ++i4; } for (; i4 >= 0 && dt; --i4) { var i2_3 = t22[i4].s; if (tr[i2_3] == mb) { --tr[i2_3]; ++dt; } } mbt = mb; } return [new u8(tr), mbt]; }; var ln = function(n2, l2, d2) { return n2.s == -1 ? Math.max(ln(n2.l, l2, d2 + 1), ln(n2.r, l2, d2 + 1)) : l2[n2.s] = d2; }; var lc = function(c2) { var s2 = c2.length; while (s2 && !c2[--s2]) ; var cl = new u16(++s2); var cli = 0, cln = c2[0], cls = 1; var w = function(v5) { cl[cli++] = v5; }; for (var i4 = 1; i4 <= s2; ++i4) { if (c2[i4] == cln && i4 != s2) ++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[i4]; } } return [cl.subarray(0, cli), s2]; }; var clen = function(cf, cl) { var l2 = 0; for (var i4 = 0; i4 < cl.length; ++i4) l2 += cf[i4] * cl[i4]; return l2; }; var wfblk = function(out7, pos, dat) { var s2 = dat.length; var o2 = shft(pos + 2); out7[o2] = s2 & 255; out7[o2 + 1] = s2 >>> 8; out7[o2 + 2] = out7[o2] ^ 255; out7[o2 + 3] = out7[o2 + 1] ^ 255; for (var i4 = 0; i4 < s2; ++i4) out7[o2 + i4 + 4] = dat[i4]; return (o2 + 4 + s2) * 8; }; var wblk = function(dat, out7, final, syms, lf, df, eb, li, bs, bl, p2) { wbits(out7, p2++, final); ++lf[256]; var _a3 = hTree(lf, 15), dlt = _a3[0], mlb = _a3[1]; var _b3 = hTree(df, 15), ddt = _b3[0], mdb = _b3[1]; var _c = lc(dlt), lclt = _c[0], nlc = _c[1]; var _d = lc(ddt), lcdt = _d[0], ndc = _d[1]; var lcfreq = new u16(19); for (var i4 = 0; i4 < lclt.length; ++i4) lcfreq[lclt[i4] & 31]++; for (var i4 = 0; i4 < lcdt.length; ++i4) lcfreq[lcdt[i4] & 31]++; var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1]; 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 (flen <= ftlen && flen <= dtlen) return wfblk(out7, p2, dat.subarray(bs, bs + bl)); var lm, ll, dm, dl; wbits(out7, p2, 1 + (dtlen < ftlen)), p2 += 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(out7, p2, nlc - 257); wbits(out7, p2 + 5, ndc - 1); wbits(out7, p2 + 10, nlcc - 4); p2 += 14; for (var i4 = 0; i4 < nlcc; ++i4) wbits(out7, p2 + 3 * i4, lct[clim[i4]]); p2 += 3 * nlcc; var lcts = [lclt, lcdt]; for (var it = 0; it < 2; ++it) { var clct = lcts[it]; for (var i4 = 0; i4 < clct.length; ++i4) { var len = clct[i4] & 31; wbits(out7, p2, llm[len]), p2 += lct[len]; if (len > 15) wbits(out7, p2, clct[i4] >>> 5 & 127), p2 += clct[i4] >>> 12; } } } else { lm = flm, ll = flt, dm = fdm, dl = fdt; } for (var i4 = 0; i4 < li; ++i4) { if (syms[i4] > 255) { var len = syms[i4] >>> 18 & 31; wbits16(out7, p2, lm[len + 257]), p2 += ll[len + 257]; if (len > 7) wbits(out7, p2, syms[i4] >>> 23 & 31), p2 += fleb[len]; var dst = syms[i4] & 31; wbits16(out7, p2, dm[dst]), p2 += dl[dst]; if (dst > 3) wbits16(out7, p2, syms[i4] >>> 5 & 8191), p2 += fdeb[dst]; } else { wbits16(out7, p2, lm[syms[i4]]), p2 += ll[syms[i4]]; } } wbits16(out7, p2, lm[256]); return p2 + ll[256]; }; var deo = new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); var et = new u8(0); var dflt = function(dat, lvl, plvl, pre, post, lst) { var s2 = dat.length; var o2 = new u8(pre + s2 + 5 * (1 + Math.ceil(s2 / 7e3)) + post); var w = o2.subarray(pre, o2.length - post); var pos = 0; if (!lvl || s2 < 8) { for (var i4 = 0; i4 <= s2; i4 += 65535) { var e2 = i4 + 65535; if (e2 < s2) { pos = wfblk(w, pos, dat.subarray(i4, e2)); } else { w[i4] = lst; pos = wfblk(w, pos, dat.subarray(i4, s2)); } } } else { var opt = deo[lvl - 1]; var n2 = opt >>> 13, c2 = opt & 8191; var msk_1 = (1 << plvl) - 1; var prev = new u16(32768), head = new u16(msk_1 + 1); var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; var hsh = function(i5) { return (dat[i5] ^ dat[i5 + 1] << bs1_1 ^ dat[i5 + 2] << bs2_1) & msk_1; }; var syms = new u32(25e3); var lf = new u16(288), df = new u16(32); var lc_1 = 0, eb = 0, i4 = 0, li = 0, wi = 0, bs = 0; for (; i4 < s2; ++i4) { var hv = hsh(i4); var imod = i4 & 32767, pimod = head[hv]; prev[imod] = pimod; head[hv] = imod; if (wi <= i4) { var rem = s2 - i4; if ((lc_1 > 7e3 || li > 24576) && rem > 423) { pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i4 - bs, pos); li = lc_1 = eb = 0, bs = i4; for (var j = 0; j < 286; ++j) lf[j] = 0; for (var j = 0; j < 30; ++j) df[j] = 0; } var l2 = 2, d2 = 0, ch_1 = c2, dif = imod - pimod & 32767; if (rem > 2 && hv == hsh(i4 - dif)) { var maxn = Math.min(n2, rem) - 1; var maxd = Math.min(32767, i4); var ml = Math.min(258, rem); while (dif <= maxd && --ch_1 && imod != pimod) { if (dat[i4 + l2] == dat[i4 + l2 - dif]) { var nl = 0; for (; nl < ml && dat[i4 + nl] == dat[i4 + nl - dif]; ++nl) ; if (nl > l2) { l2 = nl, d2 = dif; if (nl > maxn) break; var mmd = Math.min(dif, nl - 2); var md = 0; for (var j = 0; j < mmd; ++j) { var ti = i4 - dif + j + 32768 & 32767; var pti = prev[ti]; var cd = ti - pti + 32768 & 32767; if (cd > md) md = cd, pimod = ti; } } } imod = pimod, pimod = prev[imod]; dif += imod - pimod + 32768 & 32767; } } if (d2) { syms[li++] = 268435456 | revfl[l2] << 18 | revfd[d2]; var lin = revfl[l2] & 31, din = revfd[d2] & 31; eb += fleb[lin] + fdeb[din]; ++lf[257 + lin]; ++df[din]; wi = i4 + l2; ++lc_1; } else { syms[li++] = dat[i4]; ++lf[dat[i4]]; } } } pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i4 - bs, pos); if (!lst && pos & 7) pos = wfblk(w, pos + 1, et); } return slc(o2, 0, pre + shft(pos) + post); }; var crct = (function() { var t3 = new Int32Array(256); for (var i4 = 0; i4 < 256; ++i4) { var c2 = i4, k = 9; while (--k) c2 = (c2 & 1 && -306674912) ^ c2 >>> 1; t3[i4] = c2; } return t3; })(); var crc = function() { var c2 = -1; return { p: function(d2) { var cr = c2; for (var i4 = 0; i4 < d2.length; ++i4) cr = crct[cr & 255 ^ d2[i4]] ^ cr >>> 8; c2 = cr; }, d: function() { return ~c2; } }; }; var adler = function() { var a6 = 1, b5 = 0; return { p: function(d2) { var n2 = a6, m = b5; var l2 = d2.length; for (var i4 = 0; i4 != l2; ) { var e2 = Math.min(i4 + 2655, l2); for (; i4 < e2; ++i4) m += n2 += d2[i4]; n2 = (n2 & 65535) + 15 * (n2 >> 16), m = (m & 65535) + 15 * (m >> 16); } a6 = n2, b5 = m; }, d: function() { a6 %= 65521, b5 %= 65521; return (a6 & 255) << 24 | a6 >>> 8 << 16 | (b5 & 255) << 8 | b5 >>> 8; } }; }; var dopt = function(dat, opt, pre, post, st) { return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 12 + opt.mem, pre, post, !st); }; var mrg = function(a6, b5) { var o2 = {}; for (var k in a6) o2[k] = a6[k]; for (var k in b5) o2[k] = b5[k]; return o2; }; var wcln = function(fn, fnStr, td2) { var dt = fn(); var st = fn.toString(); var ks = st.slice(st.indexOf("[") + 1, st.lastIndexOf("]")).replace(/ /g, "").split(","); for (var i4 = 0; i4 < dt.length; ++i4) { var v5 = dt[i4], k = ks[i4]; if (typeof v5 == "function") { fnStr += ";" + k + "="; var st_1 = v5.toString(); if (v5.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 v5.prototype) fnStr += ";" + k + ".prototype." + t3 + "=" + v5.prototype[t3].toString(); } } else fnStr += st_1; } else td2[k] = v5; } return [fnStr, td2]; }; var ch = []; var cbfs = function(v5) { var tl = []; for (var k in v5) { if (v5[k] instanceof u8 || v5[k] instanceof u16 || v5[k] instanceof u32) tl.push((v5[k] = new v5[k].constructor(v5[k])).buffer); } return tl; }; var wrkr = function(fns, init3, id, cb2) { var _a3; if (!ch[id]) { var fnStr = "", td_1 = {}, m = fns.length - 1; for (var i4 = 0; i4 < m; ++i4) _a3 = wcln(fns[i4], fnStr, td_1), fnStr = _a3[0], td_1 = _a3[1]; ch[id] = wcln(fns[m], fnStr, td_1); } var td2 = mrg({}, ch[id][1]); return wk(ch[id][0] + ";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=" + init3.toString() + "}", id, td2, cbfs(td2), cb2); }; var bInflt = function() { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, hMap, max, bits, bits16, shft, slc, inflt, inflateSync, pbf, gu8]; }; var bDflt = function() { return [u8, u16, u32, 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 [zlv]; }; var pbf = function(msg) { return postMessage(msg, [msg.buffer]); }; var gu8 = function(o2) { return o2 && o2.size && new u8(o2.size); }; var astrm = function(strm) { strm.ondata = function(dat, final) { return postMessage([dat, final], [dat.buffer]); }; return function(ev) { return strm.push(ev.data[0], ev.data[1]); }; }; var astrmify = function(fns, strm, opts, init3, id) { var t3; var w = wrkr(fns, init3, id, function(err, dat) { if (err) w.terminate(), strm.ondata.call(strm, err); else { if (dat[1]) w.terminate(); strm.ondata.call(strm, err, dat[0], dat[1]); } }); w.postMessage(opts); strm.push = function(d2, f2) { if (t3) throw "stream finished"; if (!strm.ondata) throw "no stream handler"; w.postMessage([d2, t3 = f2], [d2.buffer]); }; strm.terminate = function() { w.terminate(); }; }; var b22 = function(d2, b5) { return d2[b5] | d2[b5 + 1] << 8; }; var b42 = function(d2, b5) { return (d2[b5] | d2[b5 + 1] << 8 | d2[b5 + 2] << 16 | d2[b5 + 3] << 24) >>> 0; }; var b8 = function(d2, b5) { return b42(d2, b5) + b42(d2, b5 + 4) * 4294967296; }; var wbytes = function(d2, b5, v5) { for (; v5; ++b5) d2[b5] = v5, v5 >>>= 8; }; var gzh = function(c2, o2) { var fn = o2.filename; c2[0] = 31, c2[1] = 139, c2[2] = 8, c2[8] = o2.level < 2 ? 4 : o2.level == 9 ? 2 : 0, c2[9] = 3; if (o2.mtime != 0) wbytes(c2, 4, Math.floor(new Date(o2.mtime || Date.now()) / 1e3)); if (fn) { c2[3] = 8; for (var i4 = 0; i4 <= fn.length; ++i4) c2[i4 + 10] = fn.charCodeAt(i4); } }; var gzs = function(d2) { if (d2[0] != 31 || d2[1] != 139 || d2[2] != 8) throw "invalid gzip data"; var flg = d2[3]; var st = 10; if (flg & 4) st += d2[10] | (d2[11] << 8) + 2; for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d2[st++]) ; return st + (flg & 2); }; var gzl = function(d2) { var l2 = d2.length; return (d2[l2 - 4] | d2[l2 - 3] << 8 | d2[l2 - 2] << 16 | d2[l2 - 1] << 24) >>> 0; }; var gzhl = function(o2) { return 10 + (o2.filename && o2.filename.length + 1 || 0); }; var zlh = function(c2, o2) { var lv = o2.level, fl2 = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; c2[0] = 120, c2[1] = fl2 << 6 | (fl2 ? 32 - 2 * fl2 : 1); }; var zlv = function(d2) { if ((d2[0] & 15) != 8 || d2[0] >>> 4 > 7 || (d2[0] << 8 | d2[1]) % 31) throw "invalid zlib data"; if (d2[1] & 32) throw "invalid zlib data: preset dictionaries not supported"; }; function AsyncCmpStrm(opts, cb2) { if (!cb2 && typeof opts == "function") cb2 = opts, opts = {}; this.ondata = cb2; return opts; } var Deflate = (function() { function Deflate2(opts, cb2) { if (!cb2 && typeof opts == "function") cb2 = opts, opts = {}; this.ondata = cb2; this.o = opts || {}; } Deflate2.prototype.p = function(c2, f2) { this.ondata(dopt(c2, this.o, 0, 0, !f2), f2); }; Deflate2.prototype.push = function(chunk, final) { if (this.d) throw "stream finished"; if (!this.ondata) throw "no stream handler"; this.d = final; this.p(chunk, final || false); }; return Deflate2; })(); var AsyncDeflate = /* @__PURE__ */ (function() { function AsyncDeflate2(opts, cb2) { astrmify([ bDflt, function() { return [astrm, Deflate]; } ], this, AsyncCmpStrm.call(this, opts, cb2), function(ev) { var strm = new Deflate(ev.data); onmessage = astrm(strm); }, 6); } return AsyncDeflate2; })(); function deflateSync(data, opts) { return dopt(data, opts || {}, 0, 0); } var Inflate = (function() { function Inflate2(cb2) { this.s = {}; this.p = new u8(0); this.ondata = cb2; } Inflate2.prototype.e = function(c2) { if (this.d) throw "stream finished"; if (!this.ondata) throw "no stream handler"; var l2 = this.p.length; var n2 = new u8(l2 + c2.length); n2.set(this.p), n2.set(c2, l2), this.p = n2; }; Inflate2.prototype.c = function(final) { this.d = this.s.i = final || false; var bts = this.s.b; var dt = inflt(this.p, this.o, this.s); 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(cb2) { this.ondata = cb2; astrmify([ bInflt, function() { return [astrm, Inflate]; } ], this, 0, function() { var strm = new Inflate(); onmessage = astrm(strm); }, 7); } return AsyncInflate2; })(); function inflateSync(data, out7) { return inflt(data, out7); } var Gzip = (function() { function Gzip2(opts, cb2) { this.c = crc(); this.l = 0; this.v = 1; Deflate.call(this, opts, cb2); } Gzip2.prototype.push = function(chunk, final) { Deflate.prototype.push.call(this, chunk, final); }; Gzip2.prototype.p = function(c2, f2) { this.c.p(c2); this.l += c2.length; var raw = dopt(c2, this.o, this.v && gzhl(this.o), f2 && 8, !f2); if (this.v) gzh(raw, this.o), this.v = 0; if (f2) wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); this.ondata(raw, f2); }; return Gzip2; })(); var Gunzip = (function() { function Gunzip2(cb2) { this.v = 1; Inflate.call(this, cb2); } Gunzip2.prototype.push = function(chunk, final) { Inflate.prototype.e.call(this, chunk); if (this.v) { var s2 = this.p.length > 3 ? gzs(this.p) : 4; if (s2 >= this.p.length && !final) return; this.p = this.p.subarray(s2), this.v = 0; } if (final) { if (this.p.length < 8) throw "invalid gzip stream"; this.p = this.p.subarray(0, -8); } Inflate.prototype.c.call(this, final); }; return Gunzip2; })(); var AsyncGunzip = /* @__PURE__ */ (function() { function AsyncGunzip2(cb2) { this.ondata = cb2; astrmify([ bInflt, guze, function() { return [astrm, Inflate, Gunzip]; } ], this, 0, function() { var strm = new Gunzip(); onmessage = astrm(strm); }, 9); } return AsyncGunzip2; })(); var Zlib = (function() { function Zlib2(opts, cb2) { this.c = adler(); this.v = 1; Deflate.call(this, opts, cb2); } Zlib2.prototype.push = function(chunk, final) { Deflate.prototype.push.call(this, chunk, final); }; Zlib2.prototype.p = function(c2, f2) { this.c.p(c2); var raw = dopt(c2, this.o, this.v && 2, f2 && 4, !f2); if (this.v) zlh(raw, this.o), this.v = 0; if (f2) wbytes(raw, raw.length - 4, this.c.d()); this.ondata(raw, f2); }; return Zlib2; })(); var Unzlib = (function() { function Unzlib2(cb2) { this.v = 1; Inflate.call(this, cb2); } Unzlib2.prototype.push = function(chunk, final) { Inflate.prototype.e.call(this, chunk); if (this.v) { if (this.p.length < 2 && !final) return; this.p = this.p.subarray(2), this.v = 0; } if (final) { if (this.p.length < 4) throw "invalid zlib stream"; this.p = this.p.subarray(0, -4); } Inflate.prototype.c.call(this, final); }; return Unzlib2; })(); var AsyncUnzlib = /* @__PURE__ */ (function() { function AsyncUnzlib2(cb2) { this.ondata = cb2; astrmify([ bInflt, zule, function() { return [astrm, Inflate, Unzlib]; } ], this, 0, function() { var strm = new Unzlib(); onmessage = astrm(strm); }, 11); } return AsyncUnzlib2; })(); function unzlibSync(data, out7) { return inflt((zlv(data), data.subarray(2, -4)), out7); } var Decompress = (function() { function Decompress2(cb2) { this.G = Gunzip; this.I = Inflate; this.Z = Unzlib; this.ondata = cb2; } Decompress2.prototype.push = function(chunk, final) { if (!this.ondata) throw "no stream handler"; 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) { var _this_1 = this; var cb2 = function() { _this_1.ondata.apply(_this_1, arguments); }; this.s = this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8 ? new this.G(cb2) : (this.p[0] & 15) != 8 || this.p[0] >> 4 > 7 || (this.p[0] << 8 | this.p[1]) % 31 ? new this.I(cb2) : new this.Z(cb2); this.s.push(this.p, final); this.p = null; } } else this.s.push(chunk, final); }; return Decompress2; })(); var AsyncDecompress = (function() { function AsyncDecompress2(cb2) { this.G = AsyncGunzip; this.I = AsyncInflate; this.Z = AsyncUnzlib; this.ondata = cb2; } AsyncDecompress2.prototype.push = function(chunk, final) { Decompress.prototype.push.call(this, chunk, final); }; return AsyncDecompress2; })(); 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 (e2) { } var dutf8 = function(d2) { for (var r2 = "", i4 = 0; ; ) { var c2 = d2[i4++]; var eb = (c2 > 127) + (c2 > 223) + (c2 > 239); if (i4 + eb > d2.length) return [r2, slc(d2, i4 - 1)]; if (!eb) r2 += String.fromCharCode(c2); else if (eb == 3) { c2 = ((c2 & 15) << 18 | (d2[i4++] & 63) << 12 | (d2[i4++] & 63) << 6 | d2[i4++] & 63) - 65536, r2 += String.fromCharCode(55296 | c2 >> 10, 56320 | c2 & 1023); } else if (eb & 1) r2 += String.fromCharCode((c2 & 31) << 6 | d2[i4++] & 63); else r2 += String.fromCharCode((c2 & 15) << 12 | (d2[i4++] & 63) << 6 | d2[i4++] & 63); } }; var DecodeUTF8 = (function() { function DecodeUTF82(cb2) { this.ondata = cb2; if (tds) this.t = new TextDecoder(); else this.p = et; } DecodeUTF82.prototype.push = function(chunk, final) { if (!this.ondata) throw "no callback"; final = !!final; if (this.t) { this.ondata(this.t.decode(chunk, { stream: true }), final); if (final) { if (this.t.decode().length) throw "invalid utf-8 data"; this.t = null; } return; } if (!this.p) throw "stream finished"; var dat = new u8(this.p.length + chunk.length); dat.set(this.p); dat.set(chunk, this.p.length); var _a3 = dutf8(dat), ch3 = _a3[0], np = _a3[1]; if (final) { if (np.length) throw "invalid utf-8 data"; this.p = null; } else this.p = np; this.ondata(ch3, final); }; return DecodeUTF82; })(); var EncodeUTF8 = (function() { function EncodeUTF82(cb2) { this.ondata = cb2; } EncodeUTF82.prototype.push = function(chunk, final) { if (!this.ondata) throw "no callback"; if (this.d) throw "stream finished"; 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 i4 = 0; i4 < str.length; ++i4) ar_1[i4] = str.charCodeAt(i4); 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(v5) { ar[ai++] = v5; }; for (var i4 = 0; i4 < l2; ++i4) { if (ai + 5 > ar.length) { var n2 = new u8(ai + 8 + (l2 - i4 << 1)); n2.set(ar); ar = n2; } var c2 = str.charCodeAt(i4); 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(++i4) & 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 r2 = ""; for (var i4 = 0; i4 < dat.length; i4 += 16384) r2 += String.fromCharCode.apply(null, dat.subarray(i4, i4 + 16384)); return r2; } else if (td) return td.decode(dat); else { var _a3 = dutf8(dat), out7 = _a3[0], ext = _a3[1]; if (ext.length) throw "invalid utf-8 data"; return out7; } } var dbf = function(l2) { return l2 == 1 ? 3 : l2 < 6 ? 2 : l2 == 9 ? 1 : 0; }; var z64e = function(d2, b5) { for (; b22(d2, b5) != 1; b5 += 4 + b22(d2, b5 + 2)) ; return [b8(d2, b5 + 12), b8(d2, b5 + 4), b8(d2, b5 + 20)]; }; var exfl = function(ex) { var le = 0; if (ex) { for (var k in ex) { var l2 = ex[k].length; if (l2 > 65535) throw "extra field too long"; le += l2 + 4; } } return le; }; var wzh = function(d2, b5, f2, fn, u, c2, ce, co) { var fl2 = fn.length, ex = f2.extra, col3 = co && co.length; var exl = exfl(ex); wbytes(d2, b5, ce != null ? 33639248 : 67324752), b5 += 4; if (ce != null) d2[b5++] = 20, d2[b5++] = f2.os; d2[b5] = 20, b5 += 2; d2[b5++] = f2.flag << 1 | (c2 == null && 8), d2[b5++] = u && 8; d2[b5++] = f2.compression & 255, d2[b5++] = f2.compression >> 8; var dt = new Date(f2.mtime == null ? Date.now() : f2.mtime), y = dt.getFullYear() - 1980; if (y < 0 || y > 119) throw "date not in range 1980-2099"; wbytes(d2, b5, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >>> 1), b5 += 4; if (c2 != null) { wbytes(d2, b5, f2.crc); wbytes(d2, b5 + 4, c2); wbytes(d2, b5 + 8, f2.size); } wbytes(d2, b5 + 12, fl2); wbytes(d2, b5 + 14, exl), b5 += 16; if (ce != null) { wbytes(d2, b5, col3); wbytes(d2, b5 + 6, f2.attrs); wbytes(d2, b5 + 10, ce), b5 += 14; } d2.set(fn, b5); b5 += fl2; if (exl) { for (var k in ex) { var exf = ex[k], l2 = exf.length; wbytes(d2, b5, +k); wbytes(d2, b5 + 2, l2); d2.set(exf, b5 + 4), b5 += 4 + l2; } } if (col3) d2.set(co, b5), b5 += col3; return b5; }; var wzf = function(o2, b5, c2, d2, e2) { wbytes(o2, b5, 101010256); wbytes(o2, b5 + 8, c2); wbytes(o2, b5 + 10, c2); wbytes(o2, b5 + 12, d2); wbytes(o2, b5 + 16, e2); }; 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) throw "no callback - add to ZIP archive before pushing"; 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_1 = this; if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new Deflate(opts, function(dat, final) { _this_1.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 (e2) { this.ondata(e2, 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_1 = this; if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new AsyncDeflate(opts, function(err, dat, final) { _this_1.ondata(err, 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(cb2) { this.ondata = cb2; this.u = []; this.d = 1; } Zip2.prototype.add = function(file) { var _this_1 = this; if (this.d & 2) throw "stream finished"; var f2 = strToU8(file.filename), fl2 = f2.length; var com = file.comment, o2 = com && strToU8(com); var u = fl2 != file.filename.length || o2 && com.length != o2.length; var hl = fl2 + exfl(file.extra) + 30; if (fl2 > 65535) throw "filename too long"; var header = new u8(hl); wzh(header, 0, file, f2, u); var chks = [header]; var pAll = function() { for (var _i = 0, chks_1 = chks; _i < chks_1.length; _i++) { var chk = chks_1[_i]; _this_1.ondata(null, chk, false); } chks = []; }; var tr = this.d; this.d = 0; var ind = this.u.length; var uf = mrg(file, { f: f2, u, o: o2, t: function() { if (file.terminate) file.terminate(); }, r: function() { pAll(); if (tr) { var nxt = _this_1.u[ind + 1]; if (nxt) nxt.r(); else _this_1.d = 1; } tr = 1; } }); var cl = 0; file.ondata = function(err, dat, final) { if (err) { _this_1.ondata(err, dat, final); _this_1.terminate(); } else { cl += dat.length; chks.push(dat); if (final) { var dd = new u8(16); wbytes(dd, 0, 134695760); wbytes(dd, 4, file.crc); wbytes(dd, 8, cl); wbytes(dd, 12, file.size); chks.push(dd); uf.c = cl, uf.b = hl + cl + 16, uf.crc = file.crc, uf.size = file.size; if (tr) uf.r(); tr = 1; } else if (tr) pAll(); } }; this.u.push(uf); }; Zip2.prototype.end = function() { var _this_1 = this; if (this.d & 2) { if (this.d & 1) throw "stream finishing"; throw "stream finished"; } if (this.d) this.e(); else this.u.push({ r: function() { if (!(_this_1.d & 1)) return; _this_1.u.splice(-1, 1); _this_1.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 f2 = _a3[_i]; tl += 46 + f2.f.length + exfl(f2.extra) + (f2.o ? f2.o.length : 0); } var out7 = new u8(tl + 22); for (var _b3 = 0, _c = this.u; _b3 < _c.length; _b3++) { var f2 = _c[_b3]; wzh(out7, bt, f2, f2.f, f2.u, f2.c, l2, f2.o); bt += 46 + f2.f.length + exfl(f2.extra) + (f2.o ? f2.o.length : 0), l2 += f2.b; } wzf(out7, bt, this.u.length, tl, l2); this.ondata(null, out7, true); this.d = 2; }; Zip2.prototype.terminate = function() { for (var _i = 0, _a3 = this.u; _i < _a3.length; _i++) { var f2 = _a3[_i]; f2.t(); } this.d = 2; }; return Zip2; })(); var UnzipPassThrough = (function() { function UnzipPassThrough2() { } UnzipPassThrough2.prototype.push = function(data, final) { this.ondata(null, data, final); }; UnzipPassThrough2.compression = 0; return UnzipPassThrough2; })(); var UnzipInflate = (function() { function UnzipInflate2() { var _this_1 = this; this.i = new Inflate(function(dat, final) { _this_1.ondata(null, dat, final); }); } UnzipInflate2.prototype.push = function(data, final) { try { this.i.push(data, final); } catch (e2) { this.ondata(e2, data, final); } }; UnzipInflate2.compression = 8; return UnzipInflate2; })(); var AsyncUnzipInflate = (function() { function AsyncUnzipInflate2(_, sz) { var _this_1 = this; if (sz < 32e4) { this.i = new Inflate(function(dat, final) { _this_1.ondata(null, dat, final); }); } else { this.i = new AsyncInflate(function(err, dat, final) { _this_1.ondata(err, dat, final); }); this.terminate = this.i.terminate; } } AsyncUnzipInflate2.prototype.push = function(data, final) { if (this.i.terminate) data = slc(data, 0); this.i.push(data, final); }; AsyncUnzipInflate2.compression = 8; return AsyncUnzipInflate2; })(); var Unzip = (function() { function Unzip2(cb2) { this.onfile = cb2; this.k = []; this.o = { 0: UnzipPassThrough }; this.p = et; } Unzip2.prototype.push = function(chunk, final) { var _this_1 = this; if (!this.onfile) throw "no callback"; if (!this.p) throw "stream finished"; 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 f2 = 0, i4 = 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, add3 = oc && this.d; var _loop_2 = function() { var _a3; var sig = b42(buf, i4); if (sig == 67324752) { f2 = 1, is = i4; this_1.d = null; this_1.c = 0; var bf = b22(buf, i4 + 6), cmp_1 = b22(buf, i4 + 8), u = bf & 2048, dd = bf & 8, fnl = b22(buf, i4 + 26), es = b22(buf, i4 + 28); if (l2 > i4 + 30 + fnl + es) { var chks_2 = []; this_1.k.unshift(chks_2); f2 = 2; var sc_1 = b42(buf, i4 + 18), su_1 = b42(buf, i4 + 22); var fn_1 = strFromU8(buf.subarray(i4 + 30, i4 += 30 + fnl), !u); if (sc_1 == 4294967295) { _a3 = dd ? [-2] : z64e(buf, i4), sc_1 = _a3[0], su_1 = _a3[1]; } else if (dd) sc_1 = -1; i4 += es; this_1.c = sc_1; var d_1; var file_1 = { name: fn_1, compression: cmp_1, start: function() { if (!file_1.ondata) throw "no callback"; if (!sc_1) file_1.ondata(null, et, true); else { var ctr = _this_1.o[cmp_1]; if (!ctr) throw "unknown compression type " + cmp_1; d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); d_1.ondata = function(err, dat3, final2) { file_1.ondata(err, dat3, final2); }; for (var _i = 0, chks_3 = chks_2; _i < chks_3.length; _i++) { var dat2 = chks_3[_i]; d_1.push(dat2, false); } if (_this_1.k[0] == chks_2 && _this_1.c) _this_1.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 = i4 += 12 + (oc == -2 && 8), f2 = 3, this_1.c = 0; return "break"; } else if (sig == 33639248) { is = i4 -= 4, f2 = 3, this_1.c = 0; return "break"; } } }; var this_1 = this; for (; i4 < l2 - 4; ++i4) { var state_1 = _loop_2(); if (state_1 === "break") break; } this.p = et; if (oc < 0) { var dat = f2 ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b42(buf, is - 16) == 134695760 && 4)) : buf.subarray(0, i4); if (add3) add3.push(dat, !!f2); else this.k[+(f2 == 2)].push(dat); } if (f2 & 2) return this.push(buf.subarray(i4), final); this.p = buf.subarray(i4); } if (final) { if (this.c) throw "invalid zip file"; this.p = null; } }; Unzip2.prototype.register = function(decoder) { this.o[decoder.compression] = decoder; }; return Unzip2; })(); // node_modules/three-stdlib/exporters/DRACOExporter.js var __defProp3 = Object.defineProperty; var __defNormalProp3 = (obj, key, value) => key in obj ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField3 = (obj, key, value) => { __defNormalProp3(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var DRACOExporter = (() => { const _DRACOExporter = class { parse(object, options = { decodeSpeed: 5, encodeSpeed: 5, encoderMethod: _DRACOExporter.MESH_EDGEBREAKER_ENCODING, quantization: [16, 8, 8, 8, 8], exportUvs: true, exportNormals: true, exportColor: false }) { if (object instanceof BufferGeometry && object.isBufferGeometry) { throw new Error("DRACOExporter: The first parameter of parse() is now an instance of Mesh or Points."); } if (DracoEncoderModule === void 0) { throw new Error("THREE.DRACOExporter: required the draco_encoder to work."); } const geometry3 = object.geometry; const dracoEncoder = DracoEncoderModule(); const encoder = new dracoEncoder.Encoder(); let builder; let dracoObject; if (!geometry3.isBufferGeometry) { throw new Error( "THREE.DRACOExporter.parse(geometry, options): geometry is not a THREE.BufferGeometry instance." ); } if (object instanceof Mesh && object.isMesh) { builder = new dracoEncoder.MeshBuilder(); dracoObject = new dracoEncoder.Mesh(); const vertices = geometry3.getAttribute("position"); builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array ); const faces = geometry3.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 i4 = 0; i4 < faces2.length; i4++) { faces2[i4] = i4; } builder.AddFacesToMesh(dracoObject, vertices.count, faces2); } if (options.exportNormals) { const normals = geometry3.getAttribute("normal"); if (normals !== void 0) { builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array ); } } if (options.exportUvs) { const uvs = geometry3.getAttribute("uv"); if (uvs !== void 0) { builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array); } } if (options.exportColor) { const colors2 = geometry3.getAttribute("color"); if (colors2 !== void 0) { builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.COLOR, colors2.count, colors2.itemSize, colors2.array ); } } } else if (object instanceof Points && object.isPoints) { builder = new dracoEncoder.PointCloudBuilder(); dracoObject = new dracoEncoder.PointCloud(); const vertices = geometry3.getAttribute("position"); builder.AddFloatAttribute(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); if (options.exportColor) { const colors2 = geometry3.getAttribute("color"); if (colors2 !== void 0) { builder.AddFloatAttribute(dracoObject, dracoEncoder.COLOR, colors2.count, colors2.itemSize, colors2.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 i4 = 0; i4 < 5; i4++) { if (options.quantization[i4] !== void 0) { encoder.SetAttributeQuantization(i4, options.quantization[i4]); } } } let length3; if (object instanceof Mesh && object.isMesh) { length3 = encoder.EncodeMeshToDracoBuffer(dracoObject, encodedData); } else { length3 = encoder.EncodePointCloudToDracoBuffer(dracoObject, true, encodedData); } dracoEncoder.destroy(dracoObject); if (length3 === 0) { throw new Error("THREE.DRACOExporter: Draco encoding failed."); } const outputData = new Int8Array(new ArrayBuffer(length3)); for (let i4 = 0; i4 < length3; i4++) { outputData[i4] = encodedData.GetValue(i4); } dracoEncoder.destroy(encodedData); dracoEncoder.destroy(encoder); dracoEncoder.destroy(builder); return outputData; } }; let DRACOExporter2 = _DRACOExporter; __publicField3(DRACOExporter2, "MESH_EDGEBREAKER_ENCODING", 1); __publicField3(DRACOExporter2, "MESH_SEQUENTIAL_ENCODING", 0); __publicField3(DRACOExporter2, "POINT_CLOUD", 0); __publicField3(DRACOExporter2, "TRIANGULAR_MESH", 1); __publicField3(DRACOExporter2, "INVALID", -1); __publicField3(DRACOExporter2, "POSITION", 0); __publicField3(DRACOExporter2, "NORMAL", 1); __publicField3(DRACOExporter2, "COLOR", 2); __publicField3(DRACOExporter2, "TEX_COORD", 3); __publicField3(DRACOExporter2, "GENERIC", 4); return DRACOExporter2; })(); // node_modules/three-stdlib/animation/CCDIKSolver.js var _q = 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 _vector2 = new Vector3(); var _matrix3 = new Matrix4(); // node_modules/three-stdlib/animation/MMDPhysics.js var _position3 = new Vector3(); var _quaternion2 = new Quaternion(); var _scale2 = new Vector3(); var _matrixWorldInv = new Matrix4(); // node_modules/three-stdlib/animation/MMDAnimationHelper.js var _q3 = new Quaternion(); // node_modules/three-stdlib/objects/BatchedMesh.js var ID_ATTR_NAME = "_batch_id_"; var _identityMatrix = new Matrix4(); var _zeroScaleMatrix = (() => new Matrix4().set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1))(); var batchingParsVertex = ( /* glsl */ ` #ifdef BATCHING attribute float ${ID_ATTR_NAME}; uniform highp sampler2D batchingTexture; mat4 getBatchingMatrix( const in float i ) { int size = textureSize( batchingTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } #endif ` ); var batchingbaseVertex = ( /* glsl */ ` #ifdef BATCHING mat4 batchingMatrix = getBatchingMatrix( ${ID_ATTR_NAME} ); #endif ` ); // node_modules/three-stdlib/objects/Reflector.js var __defProp4 = Object.defineProperty; var __defNormalProp4 = (obj, key, value) => key in obj ? __defProp4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField4 = (obj, key, value) => { __defNormalProp4(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Reflector = (() => { const _Reflector = class extends Mesh { constructor(geometry3, options = {}) { super(geometry3); this.isReflector = true; this.type = "Reflector"; 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 normal2 = 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 target2 = new Vector3(); const q = new Vector4(); const textureMatrix = new Matrix4(); const virtualCamera = this.camera; const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType }); const material = new ShaderMaterial({ 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(renderer, scene, camera) { reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); rotationMatrix2.extractRotation(scope.matrixWorld); normal2.set(0, 0, 1); normal2.applyMatrix4(rotationMatrix2); view.subVectors(reflectorWorldPosition, cameraWorldPosition); if (view.dot(normal2) > 0) return; view.reflect(normal2).negate(); view.add(reflectorWorldPosition); rotationMatrix2.extractRotation(camera.matrixWorld); lookAtPosition.set(0, 0, -1); lookAtPosition.applyMatrix4(rotationMatrix2); lookAtPosition.add(cameraWorldPosition); target2.subVectors(reflectorWorldPosition, lookAtPosition); target2.reflect(normal2).negate(); target2.add(reflectorWorldPosition); virtualCamera.position.copy(view); virtualCamera.up.set(0, 1, 0); virtualCamera.up.applyMatrix4(rotationMatrix2); virtualCamera.up.reflect(normal2); virtualCamera.lookAt(target2); 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(normal2, reflectorWorldPosition); reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse); clipPlane.set( reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant ); const projectionMatrix = virtualCamera.projectionMatrix; q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; q.z = -1; q.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; clipPlane.multiplyScalar(2 / clipPlane.dot(q)); 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 = renderer.getRenderTarget(); const currentXrEnabled = renderer.xr.enabled; const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; const currentToneMapping = renderer.toneMapping; let isSRGB = false; if ("outputColorSpace" in renderer) isSRGB = renderer.outputColorSpace === "srgb"; else isSRGB = renderer.outputEncoding === 3001; renderer.xr.enabled = false; renderer.shadowMap.autoUpdate = false; if ("outputColorSpace" in renderer) renderer.outputColorSpace = "srgb-linear"; else renderer.outputEncoding = 3e3; renderer.toneMapping = NoToneMapping; renderer.setRenderTarget(renderTarget); renderer.state.buffers.depth.setMask(true); if (renderer.autoClear === false) renderer.clear(); renderer.render(scene, virtualCamera); renderer.xr.enabled = currentXrEnabled; renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; renderer.toneMapping = currentToneMapping; if ("outputColorSpace" in renderer) renderer.outputColorSpace = isSRGB ? "srgb" : "srgb-linear"; else renderer.outputEncoding = isSRGB ? 3001 : 3e3; renderer.setRenderTarget(currentRenderTarget); const viewport = camera.viewport; if (viewport !== void 0) { renderer.state.viewport(viewport); } scope.visible = true; }; this.getRenderTarget = function() { return renderTarget; }; this.dispose = function() { renderTarget.dispose(); scope.material.dispose(); }; } }; let Reflector2 = _Reflector; __publicField4(Reflector2, "ReflectorShader", { uniforms: { color: { value: null }, tDiffuse: { value: null }, textureMatrix: { value: null } }, vertexShader: ( /* glsl */ ` uniform mat4 textureMatrix; varying vec4 vUv; #include #include void main() { vUv = textureMatrix * vec4( position, 1.0 ); gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); #include }` ), fragmentShader: ( /* glsl */ ` uniform vec3 color; uniform sampler2D tDiffuse; varying vec4 vUv; #include 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 vec4 base = texture2DProj( tDiffuse, vUv ); gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); #include #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }` ) }); return Reflector2; })(); // node_modules/three-stdlib/objects/Refractor.js var __defProp5 = Object.defineProperty; var __defNormalProp5 = (obj, key, value) => key in obj ? __defProp5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField5 = (obj, key, value) => { __defNormalProp5(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Refractor = (() => { const _Refractor = class extends Mesh { constructor(geometry3, options = {}) { super(geometry3); 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({ 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 normal2 = new Vector3(); return function visible2(camera) { refractorWorldPosition.setFromMatrixPosition(scope.matrixWorld); cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); view.subVectors(refractorWorldPosition, cameraWorldPosition); rotationMatrix2.extractRotation(scope.matrixWorld); normal2.set(0, 0, 1); normal2.applyMatrix4(rotationMatrix2); return view.dot(normal2) < 0; }; })(); const updateRefractorPlane = (function() { const normal2 = new Vector3(); const position2 = new Vector3(); const quaternion = new Quaternion(); const scale5 = new Vector3(); return function updateRefractorPlane2() { scope.matrixWorld.decompose(position2, quaternion, scale5); normal2.set(0, 0, 1).applyQuaternion(quaternion).normalize(); normal2.negate(); refractorPlane.setFromNormalAndCoplanarPoint(normal2, position2); }; })(); const updateVirtualCamera = (function() { const clipPlane = new Plane(); const clipVector = new Vector4(); const q = 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; q.x = (Math.sign(clipVector.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; q.y = (Math.sign(clipVector.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; q.z = -1; q.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; clipVector.multiplyScalar(2 / clipVector.dot(q)); 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(renderer, scene, camera) { scope.visible = false; const currentRenderTarget = renderer.getRenderTarget(); const currentXrEnabled = renderer.xr.enabled; const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; const currentToneMapping = renderer.toneMapping; let isSRGB = false; if ("outputColorSpace" in renderer) isSRGB = renderer.outputColorSpace === "srgb"; else isSRGB = renderer.outputEncoding === 3001; renderer.xr.enabled = false; renderer.shadowMap.autoUpdate = false; if ("outputColorSpace" in renderer) renderer.outputColorSpace = "srgb-linear"; else renderer.outputEncoding = 3e3; renderer.toneMapping = NoToneMapping; renderer.setRenderTarget(renderTarget); if (renderer.autoClear === false) renderer.clear(); renderer.render(scene, virtualCamera); renderer.xr.enabled = currentXrEnabled; renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; renderer.toneMapping = currentToneMapping; renderer.setRenderTarget(currentRenderTarget); if ("outputColorSpace" in renderer) renderer.outputColorSpace = isSRGB ? "srgb" : "srgb-linear"; else renderer.outputEncoding = isSRGB ? 3001 : 3e3; const viewport = camera.viewport; if (viewport !== void 0) { renderer.state.viewport(viewport); } scope.visible = true; } this.onBeforeRender = function(renderer, scene, camera) { if (camera.userData.refractor === true) return; if (!visible(camera) === true) return; updateRefractorPlane(); updateTextureMatrix(camera); updateVirtualCamera(camera); render(renderer, scene, camera); }; this.getRenderTarget = function() { return renderTarget; }; this.dispose = function() { renderTarget.dispose(); scope.material.dispose(); }; } }; let Refractor2 = _Refractor; __publicField5(Refractor2, "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 #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }` ) }); return Refractor2; })(); // node_modules/three-stdlib/objects/ShadowMesh.js var _shadowMatrix = new Matrix4(); // node_modules/three-stdlib/objects/Lensflare.js var Lensflare = (() => { class Lensflare2 extends Mesh { constructor() { super(Lensflare2.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 Texture({ width: 16, height: 16 }); tempMap.isFramebufferTexture = true; tempMap.magFilter = NearestFilter; tempMap.minFilter = NearestFilter; tempMap.generateMipmaps = false; tempMap.needsUpdate = true; const occlusionMap = new Texture({ width: 16, height: 16 }); occlusionMap.isFramebufferTexture = true; occlusionMap.magFilter = NearestFilter; occlusionMap.minFilter = NearestFilter; occlusionMap.generateMipmaps = false; occlusionMap.needsUpdate = true; const geometry3 = Lensflare2.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(geometry3, material1a); const elements = []; const shader = LensflareElement.Shader; const material2 = new RawShaderMaterial({ 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(geometry3, material2); this.addElement = function(element) { elements.push(element); }; const scale5 = new Vector2(); const screenPositionPixels = new Vector2(); const validArea = new Box2(); const viewport = new Vector4(); this.onBeforeRender = function(renderer, scene, camera) { renderer.getCurrentViewport(viewport); const invAspect = viewport.w / viewport.z; const halfViewportWidth = viewport.z / 2; const halfViewportHeight = viewport.w / 2; let size2 = 16 / viewport.w; scale5.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)) { renderer.copyFramebufferToTexture(screenPositionPixels, tempMap); let uniforms = material1a.uniforms; uniforms["scale"].value = scale5; uniforms["screenPosition"].value = positionScreen; renderer.renderBufferDirect(camera, null, geometry3, material1a, mesh1, null); renderer.copyFramebufferToTexture(screenPositionPixels, occlusionMap); uniforms = material1b.uniforms; uniforms["scale"].value = scale5; uniforms["screenPosition"].value = positionScreen; renderer.renderBufferDirect(camera, null, geometry3, material1b, mesh1, null); const vecX = -positionScreen.x * 2; const vecY = -positionScreen.y * 2; for (let i4 = 0, l2 = elements.length; i4 < l2; i4++) { const element = elements[i4]; 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; renderer.renderBufferDirect(camera, null, geometry3, material2, mesh2, null); } } }; this.dispose = function() { material1a.dispose(); material1b.dispose(); material2.dispose(); tempMap.dispose(); occlusionMap.dispose(); for (let i4 = 0, l2 = elements.length; i4 < l2; i4++) { elements[i4].texture.dispose(); } }; } } const _geometry = new BufferGeometry(); const interleavedBuffer = new InterleavedBuffer( new Float32Array([-1, -1, 0, 0, 0, 1, -1, 0, 1, 0, 1, 1, 0, 1, 1, -1, 1, 0, 0, 1]), 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)); Lensflare2.Geometry = _geometry; return Lensflare2; })(); var LensflareElement = (() => { class LensflareElement2 { constructor(texture, size2 = 1, distance3 = 0, color = new Color(16777215)) { this.texture = texture; this.size = size2; this.distance = distance3; this.color = color; } } LensflareElement2.Shader = { 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; } ` ) }; return LensflareElement2; })(); // node_modules/three-stdlib/objects/MarchingCubes.js var MarchingCubes = class extends Mesh { constructor(resolution, material, enableUvs = false, enableColors = false, maxPolyCount = 1e4) { const geometry3 = new BufferGeometry(); super(geometry3, 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); geometry3.setAttribute("position", positionAttribute); this.normalArray = new Float32Array(maxVertexCount * 3); const normalAttribute = new BufferAttribute(this.normalArray, 3); normalAttribute.setUsage(DynamicDrawUsage); geometry3.setAttribute("normal", normalAttribute); if (this.enableUvs) { this.uvArray = new Float32Array(maxVertexCount * 2); const uvAttribute = new BufferAttribute(this.uvArray, 2); uvAttribute.setUsage(DynamicDrawUsage); geometry3.setAttribute("uv", uvAttribute); } if (this.enableColors) { this.colorArray = new Float32Array(maxVertexCount * 3); const colorAttribute = new BufferAttribute(this.colorArray, 3); colorAttribute.setUsage(DynamicDrawUsage); geometry3.setAttribute("color", colorAttribute); } geometry3.boundingSphere = new Sphere(new Vector3(), 1); }; function lerp3(a6, b5, t3) { return a6 + (b5 - a6) * t3; } function VIntX(q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2) { const mu = (isol - valp1) / (valp2 - valp1), nc = scope.normal_cache; vlist[offset + 0] = x + mu * scope.delta; vlist[offset + 1] = y; vlist[offset + 2] = z; nlist[offset + 0] = lerp3(nc[q + 0], nc[q + 3], mu); nlist[offset + 1] = lerp3(nc[q + 1], nc[q + 4], mu); nlist[offset + 2] = lerp3(nc[q + 2], nc[q + 5], mu); clist[offset + 0] = lerp3(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); clist[offset + 1] = lerp3(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); clist[offset + 2] = lerp3(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu); } function VIntY(q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2) { const mu = (isol - valp1) / (valp2 - valp1), nc = scope.normal_cache; vlist[offset + 0] = x; vlist[offset + 1] = y + mu * scope.delta; vlist[offset + 2] = z; const q22 = q + scope.yd * 3; nlist[offset + 0] = lerp3(nc[q + 0], nc[q22 + 0], mu); nlist[offset + 1] = lerp3(nc[q + 1], nc[q22 + 1], mu); nlist[offset + 2] = lerp3(nc[q + 2], nc[q22 + 2], mu); clist[offset + 0] = lerp3(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); clist[offset + 1] = lerp3(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); clist[offset + 2] = lerp3(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu); } function VIntZ(q, offset, isol, x, y, z, valp1, valp2, c_offset1, c_offset2) { const mu = (isol - valp1) / (valp2 - valp1), nc = scope.normal_cache; vlist[offset + 0] = x; vlist[offset + 1] = y; vlist[offset + 2] = z + mu * scope.delta; const q22 = q + scope.zd * 3; nlist[offset + 0] = lerp3(nc[q + 0], nc[q22 + 0], mu); nlist[offset + 1] = lerp3(nc[q + 1], nc[q22 + 1], mu); nlist[offset + 2] = lerp3(nc[q + 2], nc[q22 + 2], mu); clist[offset + 0] = lerp3(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); clist[offset + 1] = lerp3(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); clist[offset + 2] = lerp3(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu); } function compNorm(q) { const q3 = q * 3; if (scope.normal_cache[q3] === 0) { scope.normal_cache[q3 + 0] = scope.field[q - 1] - scope.field[q + 1]; scope.normal_cache[q3 + 1] = scope.field[q - scope.yd] - scope.field[q + scope.yd]; scope.normal_cache[q3 + 2] = scope.field[q - scope.zd] - scope.field[q + scope.zd]; } } function polygonize(fx, fy, fz, q, isol) { const q12 = q + 1, qy = q + scope.yd, qz = q + scope.zd, q1y = q12 + scope.yd, q1z = q12 + scope.zd, qyz = q + scope.yd + scope.zd, q1yz = q12 + scope.yd + scope.zd; let cubeindex = 0; const field0 = scope.field[q], field1 = scope.field[q12], 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 d2 = scope.delta, fx2 = fx + d2, fy2 = fy + d2, fz2 = fz + d2; if (bits2 & 1) { compNorm(q); compNorm(q12); VIntX(q * 3, 0, isol, fx, fy, fz, field0, field1, q, q12); } if (bits2 & 2) { compNorm(q12); compNorm(q1y); VIntY(q12 * 3, 3, isol, fx2, fy, fz, field1, field3, q12, q1y); } if (bits2 & 4) { compNorm(qy); compNorm(q1y); VIntX(qy * 3, 6, isol, fx, fy2, fz, field2, field3, qy, q1y); } if (bits2 & 8) { compNorm(q); compNorm(qy); VIntY(q * 3, 9, isol, fx, fy, fz, field0, field2, q, 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(q); compNorm(qz); VIntZ(q * 3, 24, isol, fx, fy, fz, field0, field4, q, qz); } if (bits2 & 512) { compNorm(q12); compNorm(q1z); VIntZ(q12 * 3, 27, isol, fx2, fy, fz, field1, field5, q12, 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, i4 = 0; while (triTable[cubeindex + i4] != -1) { o1 = cubeindex + i4; o2 = o1 + 1; o3 = o1 + 2; posnormtriv(vlist, nlist, clist, 3 * triTable[o1], 3 * triTable[o2], 3 * triTable[o3]); i4 += 3; numtris++; } return numtris; } function posnormtriv(pos, norm, colors2, 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 d2 = scope.count * 2; scope.uvArray[d2 + 0] = pos[o1 + 0]; scope.uvArray[d2 + 1] = pos[o1 + 2]; scope.uvArray[d2 + 2] = pos[o2 + 0]; scope.uvArray[d2 + 3] = pos[o2 + 2]; scope.uvArray[d2 + 4] = pos[o3 + 0]; scope.uvArray[d2 + 5] = pos[o3 + 2]; } if (scope.enableColors) { scope.colorArray[c2 + 0] = colors2[o1 + 0]; scope.colorArray[c2 + 1] = colors2[o1 + 1]; scope.colorArray[c2 + 2] = colors2[o1 + 2]; scope.colorArray[c2 + 3] = colors2[o2 + 0]; scope.colorArray[c2 + 4] = colors2[o2 + 1]; scope.colorArray[c2 + 5] = colors2[o2 + 2]; scope.colorArray[c2 + 6] = colors2[o3 + 0]; scope.colorArray[c2 + 7] = colors2[o3 + 1]; scope.colorArray[c2 + 8] = colors2[o3 + 2]; } scope.count += 3; } this.addBall = function(ballx, bally, ballz, strength, subtract, colors2) { const sign = Math.sign(strength); strength = Math.abs(strength); const userDefineColor = !(colors2 === void 0 || colors2 === null); let ballColor = new Color(ballx, bally, ballz); if (userDefineColor) { try { ballColor = colors2 instanceof Color ? colors2 : Array.isArray(colors2) ? new Color( Math.min(Math.abs(colors2[0]), 1), Math.min(Math.abs(colors2[1]), 1), Math.min(Math.abs(colors2[2]), 1) ) : new Color(colors2); } catch (err) { 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 x, y, z, y_offset, z_offset, fx, fy, fz, fz2, fy2, val; 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 (x = min_x; x < max_x; x++) { fx = x / this.size - ballx; val = strength / (1e-6 + fx * fx + fy2 + fz2) - subtract; if (val > 0) { this.field[y_offset + x] += val * sign; const ratio = Math.sqrt((x - xs) * (x - 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 + x) * 3 + 0] += ballColor.r * contrib; this.palette[(y_offset + x) * 3 + 1] += ballColor.g * contrib; this.palette[(y_offset + x) * 3 + 2] += ballColor.b * contrib; } } } } }; this.addPlaneX = function(strength, subtract) { const size2 = this.size, yd = this.yd, zd = this.zd, field = this.field; let x, y, z, xx, val, xdiv, cxy, dist = size2 * Math.sqrt(strength / subtract); if (dist > size2) dist = size2; for (x = 0; x < dist; x++) { xdiv = x / size2; xx = xdiv * xdiv; val = strength / (1e-4 + xx) - subtract; if (val > 0) { for (y = 0; y < size2; y++) { cxy = x + y * yd; for (z = 0; z < size2; z++) { field[zd * z + cxy] += val; } } } } }; this.addPlaneY = function(strength, subtract) { const size2 = this.size, yd = this.yd, zd = this.zd, field = this.field; let x, y, z, yy, val, 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; val = strength / (1e-4 + yy) - subtract; if (val > 0) { cy = y * yd; for (x = 0; x < size2; x++) { cxy = cy + x; for (z = 0; z < size2; z++) field[zd * z + cxy] += val; } } } }; this.addPlaneZ = function(strength, subtract) { const size2 = this.size, yd = this.yd, zd = this.zd, field = this.field; let x, y, z, zz, val, 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; val = strength / (1e-4 + zz) - subtract; if (val > 0) { cz = zd * z; for (y = 0; y < size2; y++) { cyz = cz + y * yd; for (x = 0; x < size2; x++) field[cyz + x] += val; } } } }; this.setCell = function(x, y, z, value) { const index2 = this.size2 * z + this.size * y + x; this.field[index2] = value; }; this.getCell = function(x, y, z) { const index2 = this.size2 * z + this.size * y + x; 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 x = 0; x < size2; x++) { for (let y = 0; y < size2; y++) { for (let z = 0; z < size2; z++) { const index2 = size22 * z + size2 * y + x; let val = fieldCopy[index2]; let count = 1; for (let x2 = -1; x2 <= 1; x2 += 2) { const x3 = x2 + x; 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 val2 = fieldCopy[index22]; count++; val += intensity * (val2 - val) / count; } } } field[index2] = val; } } } }; this.reset = function() { for (let i4 = 0; i4 < this.size3; i4++) { this.normal_cache[i4 * 3] = 0; this.field[i4] = 0; this.palette[i4 * 3] = this.palette[i4 * 3 + 1] = this.palette[i4 * 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 x = 1; x < smin2; x++) { const fx = (x - this.halfsize) / this.halfsize; const q = y_offset + x; polygonize(fx, fy, fz, q, this.isolation); } } } this.geometry.setDrawRange(0, this.count); geometry3.getAttribute("position").needsUpdate = true; geometry3.getAttribute("normal").needsUpdate = true; if (this.enableUvs) geometry3.getAttribute("uv").needsUpdate = true; if (this.enableColors) geometry3.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-stdlib/math/SimplexNoise.js var __defProp6 = Object.defineProperty; var __defNormalProp6 = (obj, key, value) => key in obj ? __defProp6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField6 = (obj, key, value) => { __defNormalProp6(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var SimplexNoise = class { /** * You can pass in a random number generator object if you like. * It is assumed to have a random() method. */ constructor(r2 = Math) { __publicField6(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] ]); __publicField6(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] ]); __publicField6(this, "p", []); __publicField6(this, "perm", []); __publicField6(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] ]); __publicField6(this, "dot", (g, x, y) => { return g[0] * x + g[1] * y; }); __publicField6(this, "dot3", (g, x, y, z) => { return g[0] * x + g[1] * y + g[2] * z; }); __publicField6(this, "dot4", (g, x, y, z, w) => { return g[0] * x + g[1] * y + g[2] * z + g[3] * w; }); __publicField6(this, "noise", (xin, yin) => { let n0; let n1; let n2; const F22 = 0.5 * (Math.sqrt(3) - 1); const s2 = (xin + yin) * F22; const i4 = Math.floor(xin + s2); const j = Math.floor(yin + s2); const G22 = (3 - Math.sqrt(3)) / 6; const t3 = (i4 + j) * G22; const X0 = i4 - t3; const Y0 = j - t3; const x0 = xin - X0; const y0 = yin - Y0; let i1 = 0; let j1 = 1; if (x0 > y0) { i1 = 1; j1 = 0; } const x1 = x0 - i1 + G22; const y1 = y0 - j1 + G22; const x2 = x0 - 1 + 2 * G22; const y2 = y0 - 1 + 2 * G22; const ii = i4 & 255; const jj = j & 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); }); __publicField6(this, "noise3d", (xin, yin, zin) => { let n0; let n1; let n2; let n3; const F32 = 1 / 3; const s2 = (xin + yin + zin) * F32; const i4 = Math.floor(xin + s2); const j = Math.floor(yin + s2); const k = Math.floor(zin + s2); const G32 = 1 / 6; const t3 = (i4 + j + k) * G32; const X0 = i4 - t3; const Y0 = j - t3; const Z0 = k - t3; const x0 = xin - X0; const y0 = yin - Y0; const z0 = zin - Z0; let i1; let j1; let k1; let i22; let j2; let k2; if (x0 >= y0) { if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i22 = 1; j2 = 1; k2 = 0; } else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i22 = 1; j2 = 0; k2 = 1; } else { i1 = 0; j1 = 0; k1 = 1; i22 = 1; j2 = 0; k2 = 1; } } else { if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i22 = 0; j2 = 1; k2 = 1; } else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i22 = 0; j2 = 1; k2 = 1; } else { i1 = 0; j1 = 1; k1 = 0; i22 = 1; j2 = 1; k2 = 0; } } const x1 = x0 - i1 + G32; const y1 = y0 - j1 + G32; const z1 = z0 - k1 + G32; const x2 = x0 - i22 + 2 * G32; const y2 = y0 - j2 + 2 * G32; const z2 = z0 - k2 + 2 * G32; const x3 = x0 - 1 + 3 * G32; const y3 = y0 - 1 + 3 * G32; const z3 = z0 - 1 + 3 * G32; const ii = i4 & 255; const jj = j & 255; const kk = k & 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 + i22 + this.perm[jj + j2 + this.perm[kk + k2]]] % 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); }); __publicField6(this, "noise4d", (x, y, z, w) => { const grad4 = this.grad4; const simplex = this.simplex; const perm2 = 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 s2 = (x + y + z + w) * F4; const i4 = Math.floor(x + s2); const j = Math.floor(y + s2); const k = Math.floor(z + s2); const l2 = Math.floor(w + s2); const t3 = (i4 + j + k + l2) * G4; const X0 = i4 - t3; const Y0 = j - t3; const Z0 = k - t3; const W0 = l2 - t3; const x0 = x - 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 c32 = y0 > z0 ? 8 : 0; const c42 = x0 > w0 ? 4 : 0; const c5 = y0 > w0 ? 2 : 0; const c6 = z0 > w0 ? 1 : 0; const c7 = c1 + c2 + c32 + c42 + c5 + c6; let i1; let j1; let k1; let l1; let i22; let j2; let k2; let l22; let i32; let j3; let k3; let l3; i1 = simplex[c7][0] >= 3 ? 1 : 0; j1 = simplex[c7][1] >= 3 ? 1 : 0; k1 = simplex[c7][2] >= 3 ? 1 : 0; l1 = simplex[c7][3] >= 3 ? 1 : 0; i22 = simplex[c7][0] >= 2 ? 1 : 0; j2 = simplex[c7][1] >= 2 ? 1 : 0; k2 = simplex[c7][2] >= 2 ? 1 : 0; l22 = simplex[c7][3] >= 2 ? 1 : 0; i32 = simplex[c7][0] >= 1 ? 1 : 0; j3 = simplex[c7][1] >= 1 ? 1 : 0; k3 = simplex[c7][2] >= 1 ? 1 : 0; 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 x2 = x0 - i22 + 2 * G4; const y2 = y0 - j2 + 2 * G4; const z2 = z0 - k2 + 2 * G4; const w2 = w0 - l22 + 2 * G4; const x3 = x0 - i32 + 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 = i4 & 255; const jj = j & 255; const kk = k & 255; const ll = l2 & 255; const gi0 = perm2[ii + perm2[jj + perm2[kk + perm2[ll]]]] % 32; const gi1 = perm2[ii + i1 + perm2[jj + j1 + perm2[kk + k1 + perm2[ll + l1]]]] % 32; const gi2 = perm2[ii + i22 + perm2[jj + j2 + perm2[kk + k2 + perm2[ll + l22]]]] % 32; const gi3 = perm2[ii + i32 + perm2[jj + j3 + perm2[kk + k3 + perm2[ll + l3]]]] % 32; const gi4 = perm2[ii + 1 + perm2[jj + 1 + perm2[kk + 1 + perm2[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 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; if (t22 < 0) { n2 = 0; } else { t22 *= t22; n2 = t22 * t22 * this.dot4(grad4[gi2], x2, 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); }); for (let i4 = 0; i4 < 256; i4++) { this.p[i4] = Math.floor(r2.random() * 256); } for (let i4 = 0; i4 < 512; i4++) { this.perm[i4] = this.p[i4 & 255]; } } }; // node_modules/three-stdlib/geometries/LightningStrike.js var __defProp7 = Object.defineProperty; var __defNormalProp7 = (obj, key, value) => key in obj ? __defProp7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField7 = (obj, key, value) => { __defNormalProp7(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var LightningStrike = (() => { const _LightningStrike = class extends BufferGeometry { constructor(rayParameters = {}) { super(); this.isLightningStrike = true; this.type = "LightningStrike"; this.init(_LightningStrike.copyParameters(rayParameters, rayParameters)); this.createMesh(); } static createRandomGenerator() { const numSeeds = 2053; const seeds = []; for (let i4 = 0; i4 < numSeeds; i4++) { seeds.push(Math.random()); } const generator = { currentSeed: 0, random: function() { const value = seeds[generator.currentSeed]; generator.currentSeed = (generator.currentSeed + 1) % numSeeds; return value; }, getSeed: function() { return generator.currentSeed / numSeeds; }, setSeed: function(seed3) { generator.currentSeed = Math.floor(seed3 * numSeeds) % numSeeds; } }; return generator; } static copyParameters(dest = {}, source = {}) { const vecCopy = function(v5) { if (source === dest) { return v5; } else { return v5.clone(); } }; dest.sourceOffset = source.sourceOffset !== void 0 ? vecCopy(source.sourceOffset) : new Vector3(0, 100, 0), dest.destOffset = source.destOffset !== void 0 ? vecCopy(source.destOffset) : new Vector3(0, 0, 0), dest.timeScale = source.timeScale !== void 0 ? source.timeScale : 1, dest.roughness = source.roughness !== void 0 ? source.roughness : 0.9, dest.straightness = source.straightness !== void 0 ? source.straightness : 0.7, dest.up0 = source.up0 !== void 0 ? vecCopy(source.up0) : new Vector3(0, 0, 1); dest.up1 = source.up1 !== void 0 ? vecCopy(source.up1) : new Vector3(0, 0, 1), dest.radius0 = source.radius0 !== void 0 ? source.radius0 : 1, dest.radius1 = source.radius1 !== void 0 ? source.radius1 : 1, dest.radius0Factor = source.radius0Factor !== void 0 ? source.radius0Factor : 0.5, dest.radius1Factor = source.radius1Factor !== void 0 ? source.radius1Factor : 0.2, dest.minRadius = source.minRadius !== void 0 ? source.minRadius : 0.2, // These parameters should not be changed after lightning creation. They can be changed but the ray will change its form abruptly: dest.isEternal = source.isEternal !== void 0 ? source.isEternal : source.birthTime === void 0 || source.deathTime === void 0, dest.birthTime = source.birthTime, dest.deathTime = source.deathTime, dest.propagationTimeFactor = source.propagationTimeFactor !== void 0 ? source.propagationTimeFactor : 0.1, dest.vanishingTimeFactor = source.vanishingTimeFactor !== void 0 ? source.vanishingTimeFactor : 0.9, dest.subrayPeriod = source.subrayPeriod !== void 0 ? source.subrayPeriod : 4, dest.subrayDutyCycle = source.subrayDutyCycle !== void 0 ? source.subrayDutyCycle : 0.6; dest.maxIterations = source.maxIterations !== void 0 ? source.maxIterations : 9; dest.isStatic = source.isStatic !== void 0 ? source.isStatic : false; dest.ramification = source.ramification !== void 0 ? source.ramification : 5; dest.maxSubrayRecursion = source.maxSubrayRecursion !== void 0 ? source.maxSubrayRecursion : 3; dest.recursionProbability = source.recursionProbability !== void 0 ? source.recursionProbability : 0.6; dest.generateUVs = source.generateUVs !== void 0 ? source.generateUVs : false; dest.randomGenerator = source.randomGenerator, dest.noiseSeed = source.noiseSeed, dest.onDecideSubrayCreation = source.onDecideSubrayCreation, dest.onSubrayCreation = source.onSubrayCreation; return dest; } update(time) { if (this.isStatic) return; if (this.rayParameters.isEternal || this.rayParameters.birthTime <= time && time <= this.rayParameters.deathTime) { this.updateMesh(time); if (time < this.subrays[0].endPropagationTime) { this.state = _LightningStrike.RAY_PROPAGATING; } else if (time > this.subrays[0].beginVanishingTime) { this.state = _LightningStrike.RAY_VANISHING; } else { this.state = _LightningStrike.RAY_STEADY; } this.visible = true; } else { this.visible = false; if (time < this.rayParameters.birthTime) { this.state = _LightningStrike.RAY_UNBORN; } else { this.state = _LightningStrike.RAY_EXTINGUISHED; } } } init(rayParameters) { this.rayParameters = rayParameters; this.maxIterations = rayParameters.maxIterations !== void 0 ? Math.floor(rayParameters.maxIterations) : 9; rayParameters.maxIterations = this.maxIterations; this.isStatic = rayParameters.isStatic !== void 0 ? rayParameters.isStatic : false; rayParameters.isStatic = this.isStatic; this.ramification = rayParameters.ramification !== void 0 ? Math.floor(rayParameters.ramification) : 5; rayParameters.ramification = this.ramification; this.maxSubrayRecursion = rayParameters.maxSubrayRecursion !== void 0 ? Math.floor(rayParameters.maxSubrayRecursion) : 3; rayParameters.maxSubrayRecursion = this.maxSubrayRecursion; this.recursionProbability = rayParameters.recursionProbability !== void 0 ? rayParameters.recursionProbability : 0.6; rayParameters.recursionProbability = this.recursionProbability; this.generateUVs = rayParameters.generateUVs !== void 0 ? rayParameters.generateUVs : false; rayParameters.generateUVs = this.generateUVs; if (rayParameters.randomGenerator !== void 0) { this.randomGenerator = rayParameters.randomGenerator; this.seedGenerator = rayParameters.randomGenerator; if (rayParameters.noiseSeed !== void 0) { this.seedGenerator.setSeed(rayParameters.noiseSeed); } } else { this.randomGenerator = _LightningStrike.createRandomGenerator(); this.seedGenerator = Math; } if (rayParameters.onDecideSubrayCreation !== void 0) { this.onDecideSubrayCreation = rayParameters.onDecideSubrayCreation; } else { this.createDefaultSubrayCreationCallbacks(); if (rayParameters.onSubrayCreation !== void 0) { this.onSubrayCreation = rayParameters.onSubrayCreation; } } this.state = _LightningStrike.RAY_INITIALIZED; this.maxSubrays = Math.ceil(1 + Math.pow(this.ramification, Math.max(0, this.maxSubrayRecursion - 1))); rayParameters.maxSubrays = this.maxSubrays; this.maxRaySegments = 2 * (1 << this.maxIterations); this.subrays = []; for (let i4 = 0; i4 < this.maxSubrays; i4++) { this.subrays.push(this.createSubray()); } this.raySegments = []; for (let i4 = 0; i4 < this.maxRaySegments; i4++) { this.raySegments.push(this.createSegment()); } this.time = 0; this.timeFraction = 0; this.currentSegmentCallback = null; this.currentCreateTriangleVertices = this.generateUVs ? this.createTriangleVerticesWithUVs : this.createTriangleVerticesWithoutUVs; this.numSubrays = 0; this.currentSubray = null; this.currentSegmentIndex = 0; this.isInitialSegment = false; this.subrayProbability = 0; this.currentVertex = 0; this.currentIndex = 0; this.currentCoordinate = 0; this.currentUVCoordinate = 0; this.vertices = null; this.uvs = null; this.indices = null; this.positionAttribute = null; this.uvsAttribute = null; this.simplexX = new SimplexNoise(this.seedGenerator); this.simplexY = new SimplexNoise(this.seedGenerator); this.simplexZ = new SimplexNoise(this.seedGenerator); this.forwards = new Vector3(); this.forwardsFill = new Vector3(); this.side = new Vector3(); this.down = new Vector3(); this.middlePos = new Vector3(); this.middleLinPos = new Vector3(); this.newPos = new Vector3(); this.vPos = new Vector3(); this.cross1 = new Vector3(); } createMesh() { const maxDrawableSegmentsPerSubRay = 1 << this.maxIterations; const maxVerts = 3 * (maxDrawableSegmentsPerSubRay + 1) * this.maxSubrays; const maxIndices = 18 * maxDrawableSegmentsPerSubRay * this.maxSubrays; this.vertices = new Float32Array(maxVerts * 3); this.indices = new Uint32Array(maxIndices); if (this.generateUVs) { this.uvs = new Float32Array(maxVerts * 2); } this.fillMesh(0); this.setIndex(new Uint32BufferAttribute(this.indices, 1)); this.positionAttribute = new Float32BufferAttribute(this.vertices, 3); this.setAttribute("position", this.positionAttribute); if (this.generateUVs) { this.uvsAttribute = new Float32BufferAttribute(new Float32Array(this.uvs), 2); this.setAttribute("uv", this.uvsAttribute); } if (!this.isStatic) { this.index.usage = DynamicDrawUsage; this.positionAttribute.usage = DynamicDrawUsage; if (this.generateUVs) { this.uvsAttribute.usage = DynamicDrawUsage; } } this.vertices = this.positionAttribute.array; this.indices = this.index.array; if (this.generateUVs) { this.uvs = this.uvsAttribute.array; } } updateMesh(time) { this.fillMesh(time); this.drawRange.count = this.currentIndex; this.index.needsUpdate = true; this.positionAttribute.needsUpdate = true; if (this.generateUVs) { this.uvsAttribute.needsUpdate = true; } } fillMesh(time) { const scope = this; this.currentVertex = 0; this.currentIndex = 0; this.currentCoordinate = 0; this.currentUVCoordinate = 0; this.fractalRay(time, function fillVertices(segment) { const subray = scope.currentSubray; if (time < subray.birthTime) { return; } else if (this.rayParameters.isEternal && scope.currentSubray.recursion == 0) { scope.createPrism(segment); scope.onDecideSubrayCreation(segment, scope); } else if (time < subray.endPropagationTime) { if (scope.timeFraction >= segment.fraction0 * subray.propagationTimeFactor) { scope.createPrism(segment); scope.onDecideSubrayCreation(segment, scope); } } else if (time < subray.beginVanishingTime) { scope.createPrism(segment); scope.onDecideSubrayCreation(segment, scope); } else { if (scope.timeFraction <= subray.vanishingTimeFactor + segment.fraction1 * (1 - subray.vanishingTimeFactor)) { scope.createPrism(segment); } scope.onDecideSubrayCreation(segment, scope); } }); } addNewSubray() { return this.subrays[this.numSubrays++]; } initSubray(subray, rayParameters) { subray.pos0.copy(rayParameters.sourceOffset); subray.pos1.copy(rayParameters.destOffset); subray.up0.copy(rayParameters.up0); subray.up1.copy(rayParameters.up1); subray.radius0 = rayParameters.radius0; subray.radius1 = rayParameters.radius1; subray.birthTime = rayParameters.birthTime; subray.deathTime = rayParameters.deathTime; subray.timeScale = rayParameters.timeScale; subray.roughness = rayParameters.roughness; subray.straightness = rayParameters.straightness; subray.propagationTimeFactor = rayParameters.propagationTimeFactor; subray.vanishingTimeFactor = rayParameters.vanishingTimeFactor; subray.maxIterations = this.maxIterations; subray.seed = rayParameters.noiseSeed !== void 0 ? rayParameters.noiseSeed : 0; subray.recursion = 0; } fractalRay(time, segmentCallback) { this.time = time; this.currentSegmentCallback = segmentCallback; this.numSubrays = 0; this.initSubray(this.addNewSubray(), this.rayParameters); for (let subrayIndex = 0; subrayIndex < this.numSubrays; subrayIndex++) { const subray = this.subrays[subrayIndex]; this.currentSubray = subray; this.randomGenerator.setSeed(subray.seed); subray.endPropagationTime = MathUtils.lerp(subray.birthTime, subray.deathTime, subray.propagationTimeFactor); subray.beginVanishingTime = MathUtils.lerp(subray.deathTime, subray.birthTime, 1 - subray.vanishingTimeFactor); const random1 = this.randomGenerator.random; subray.linPos0.set(random1(), random1(), random1()).multiplyScalar(1e3); subray.linPos1.set(random1(), random1(), random1()).multiplyScalar(1e3); this.timeFraction = (time - subray.birthTime) / (subray.deathTime - subray.birthTime); this.currentSegmentIndex = 0; this.isInitialSegment = true; const segment = this.getNewSegment(); segment.iteration = 0; segment.pos0.copy(subray.pos0); segment.pos1.copy(subray.pos1); segment.linPos0.copy(subray.linPos0); segment.linPos1.copy(subray.linPos1); segment.up0.copy(subray.up0); segment.up1.copy(subray.up1); segment.radius0 = subray.radius0; segment.radius1 = subray.radius1; segment.fraction0 = 0; segment.fraction1 = 1; segment.positionVariationFactor = 1 - subray.straightness; this.subrayProbability = this.ramification * Math.pow(this.recursionProbability, subray.recursion) / (1 << subray.maxIterations); this.fractalRayRecursive(segment); } this.currentSegmentCallback = null; this.currentSubray = null; } fractalRayRecursive(segment) { if (segment.iteration >= this.currentSubray.maxIterations) { this.currentSegmentCallback(segment); return; } this.forwards.subVectors(segment.pos1, segment.pos0); let lForwards = this.forwards.length(); if (lForwards < 1e-6) { this.forwards.set(0, 0, 0.01); lForwards = this.forwards.length(); } const middleRadius = (segment.radius0 + segment.radius1) * 0.5; const middleFraction = (segment.fraction0 + segment.fraction1) * 0.5; const timeDimension = this.time * this.currentSubray.timeScale * Math.pow(2, segment.iteration); this.middlePos.lerpVectors(segment.pos0, segment.pos1, 0.5); this.middleLinPos.lerpVectors(segment.linPos0, segment.linPos1, 0.5); const p2 = this.middleLinPos; this.newPos.set( this.simplexX.noise4d(p2.x, p2.y, p2.z, timeDimension), this.simplexY.noise4d(p2.x, p2.y, p2.z, timeDimension), this.simplexZ.noise4d(p2.x, p2.y, p2.z, timeDimension) ); this.newPos.multiplyScalar(segment.positionVariationFactor * lForwards); this.newPos.add(this.middlePos); const newSegment1 = this.getNewSegment(); newSegment1.pos0.copy(segment.pos0); newSegment1.pos1.copy(this.newPos); newSegment1.linPos0.copy(segment.linPos0); newSegment1.linPos1.copy(this.middleLinPos); newSegment1.up0.copy(segment.up0); newSegment1.up1.copy(segment.up1); newSegment1.radius0 = segment.radius0; newSegment1.radius1 = middleRadius; newSegment1.fraction0 = segment.fraction0; newSegment1.fraction1 = middleFraction; newSegment1.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; newSegment1.iteration = segment.iteration + 1; const newSegment2 = this.getNewSegment(); newSegment2.pos0.copy(this.newPos); newSegment2.pos1.copy(segment.pos1); newSegment2.linPos0.copy(this.middleLinPos); newSegment2.linPos1.copy(segment.linPos1); this.cross1.crossVectors(segment.up0, this.forwards.normalize()); newSegment2.up0.crossVectors(this.forwards, this.cross1).normalize(); newSegment2.up1.copy(segment.up1); newSegment2.radius0 = middleRadius; newSegment2.radius1 = segment.radius1; newSegment2.fraction0 = middleFraction; newSegment2.fraction1 = segment.fraction1; newSegment2.positionVariationFactor = segment.positionVariationFactor * this.currentSubray.roughness; newSegment2.iteration = segment.iteration + 1; this.fractalRayRecursive(newSegment1); this.fractalRayRecursive(newSegment2); } createPrism(segment) { this.forwardsFill.subVectors(segment.pos1, segment.pos0).normalize(); if (this.isInitialSegment) { this.currentCreateTriangleVertices(segment.pos0, segment.up0, this.forwardsFill, segment.radius0, 0); this.isInitialSegment = false; } this.currentCreateTriangleVertices( segment.pos1, segment.up0, this.forwardsFill, segment.radius1, segment.fraction1 ); this.createPrismFaces(); } createTriangleVerticesWithoutUVs(pos, up, forwards, radius) { this.side.crossVectors(up, forwards).multiplyScalar(radius * _LightningStrike.COS30DEG); this.down.copy(up).multiplyScalar(-radius * _LightningStrike.SIN30DEG); const p2 = this.vPos; const v5 = this.vertices; p2.copy(pos).sub(this.side).add(this.down); v5[this.currentCoordinate++] = p2.x; v5[this.currentCoordinate++] = p2.y; v5[this.currentCoordinate++] = p2.z; p2.copy(pos).add(this.side).add(this.down); v5[this.currentCoordinate++] = p2.x; v5[this.currentCoordinate++] = p2.y; v5[this.currentCoordinate++] = p2.z; p2.copy(up).multiplyScalar(radius).add(pos); v5[this.currentCoordinate++] = p2.x; v5[this.currentCoordinate++] = p2.y; v5[this.currentCoordinate++] = p2.z; this.currentVertex += 3; } createTriangleVerticesWithUVs(pos, up, forwards, radius, u) { this.side.crossVectors(up, forwards).multiplyScalar(radius * _LightningStrike.COS30DEG); this.down.copy(up).multiplyScalar(-radius * _LightningStrike.SIN30DEG); const p2 = this.vPos; const v5 = this.vertices; const uv = this.uvs; p2.copy(pos).sub(this.side).add(this.down); v5[this.currentCoordinate++] = p2.x; v5[this.currentCoordinate++] = p2.y; v5[this.currentCoordinate++] = p2.z; uv[this.currentUVCoordinate++] = u; uv[this.currentUVCoordinate++] = 0; p2.copy(pos).add(this.side).add(this.down); v5[this.currentCoordinate++] = p2.x; v5[this.currentCoordinate++] = p2.y; v5[this.currentCoordinate++] = p2.z; uv[this.currentUVCoordinate++] = u; uv[this.currentUVCoordinate++] = 0.5; p2.copy(up).multiplyScalar(radius).add(pos); v5[this.currentCoordinate++] = p2.x; v5[this.currentCoordinate++] = p2.y; v5[this.currentCoordinate++] = p2.z; uv[this.currentUVCoordinate++] = u; uv[this.currentUVCoordinate++] = 1; this.currentVertex += 3; } createPrismFaces(vertex) { const indices = this.indices; vertex = this.currentVertex - 6; indices[this.currentIndex++] = vertex + 1; indices[this.currentIndex++] = vertex + 2; indices[this.currentIndex++] = vertex + 5; indices[this.currentIndex++] = vertex + 1; indices[this.currentIndex++] = vertex + 5; indices[this.currentIndex++] = vertex + 4; indices[this.currentIndex++] = vertex + 0; indices[this.currentIndex++] = vertex + 1; indices[this.currentIndex++] = vertex + 4; indices[this.currentIndex++] = vertex + 0; indices[this.currentIndex++] = vertex + 4; indices[this.currentIndex++] = vertex + 3; indices[this.currentIndex++] = vertex + 2; indices[this.currentIndex++] = vertex + 0; indices[this.currentIndex++] = vertex + 3; indices[this.currentIndex++] = vertex + 2; indices[this.currentIndex++] = vertex + 3; indices[this.currentIndex++] = vertex + 5; } createDefaultSubrayCreationCallbacks() { const random1 = this.randomGenerator.random; this.onDecideSubrayCreation = function(segment, lightningStrike) { const subray = lightningStrike.currentSubray; const period = lightningStrike.rayParameters.subrayPeriod; const dutyCycle = lightningStrike.rayParameters.subrayDutyCycle; const phase0 = lightningStrike.rayParameters.isEternal && subray.recursion == 0 ? -random1() * period : MathUtils.lerp(subray.birthTime, subray.endPropagationTime, segment.fraction0) - random1() * period; const phase = lightningStrike.time - phase0; const currentCycle = Math.floor(phase / period); const childSubraySeed = random1() * (currentCycle + 1); const isActive = phase % period <= dutyCycle * period; let probability = 0; if (isActive) { probability = lightningStrike.subrayProbability; } if (subray.recursion < lightningStrike.maxSubrayRecursion && lightningStrike.numSubrays < lightningStrike.maxSubrays && random1() < probability) { const childSubray = lightningStrike.addNewSubray(); const parentSeed = lightningStrike.randomGenerator.getSeed(); childSubray.seed = childSubraySeed; lightningStrike.randomGenerator.setSeed(childSubraySeed); childSubray.recursion = subray.recursion + 1; childSubray.maxIterations = Math.max(1, subray.maxIterations - 1); childSubray.linPos0.set(random1(), random1(), random1()).multiplyScalar(1e3); childSubray.linPos1.set(random1(), random1(), random1()).multiplyScalar(1e3); childSubray.up0.copy(subray.up0); childSubray.up1.copy(subray.up1); childSubray.radius0 = segment.radius0 * lightningStrike.rayParameters.radius0Factor; childSubray.radius1 = Math.min( lightningStrike.rayParameters.minRadius, segment.radius1 * lightningStrike.rayParameters.radius1Factor ); childSubray.birthTime = phase0 + currentCycle * period; childSubray.deathTime = childSubray.birthTime + period * dutyCycle; if (!lightningStrike.rayParameters.isEternal && subray.recursion == 0) { childSubray.birthTime = Math.max(childSubray.birthTime, subray.birthTime); childSubray.deathTime = Math.min(childSubray.deathTime, subray.deathTime); } childSubray.timeScale = subray.timeScale * 2; childSubray.roughness = subray.roughness; childSubray.straightness = subray.straightness; childSubray.propagationTimeFactor = subray.propagationTimeFactor; childSubray.vanishingTimeFactor = subray.vanishingTimeFactor; lightningStrike.onSubrayCreation(segment, subray, childSubray, lightningStrike); lightningStrike.randomGenerator.setSeed(parentSeed); } }; const vec1Pos = new Vector3(); const vec2Forward = new Vector3(); const vec3Side = new Vector3(); const vec4Up = new Vector3(); this.onSubrayCreation = function(segment, parentSubray, childSubray, lightningStrike) { lightningStrike.subrayCylinderPosition(segment, parentSubray, childSubray, 0.5, 0.6, 0.2); }; this.subrayConePosition = function(segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor) { childSubray.pos0.copy(segment.pos0); vec1Pos.subVectors(parentSubray.pos1, parentSubray.pos0); vec2Forward.copy(vec1Pos).normalize(); vec1Pos.multiplyScalar(segment.fraction0 + (1 - segment.fraction0) * (random1() * heightFactor)); const length3 = vec1Pos.length(); vec3Side.crossVectors(parentSubray.up0, vec2Forward); const angle = 2 * Math.PI * random1(); vec3Side.multiplyScalar(Math.cos(angle)); vec4Up.copy(parentSubray.up0).multiplyScalar(Math.sin(angle)); childSubray.pos1.copy(vec3Side).add(vec4Up).multiplyScalar(length3 * sideWidthFactor * (minSideWidthFactor + random1() * (1 - minSideWidthFactor))).add(vec1Pos).add(parentSubray.pos0); }; this.subrayCylinderPosition = function(segment, parentSubray, childSubray, heightFactor, sideWidthFactor, minSideWidthFactor) { childSubray.pos0.copy(segment.pos0); vec1Pos.subVectors(parentSubray.pos1, parentSubray.pos0); vec2Forward.copy(vec1Pos).normalize(); vec1Pos.multiplyScalar(segment.fraction0 + (1 - segment.fraction0) * ((2 * random1() - 1) * heightFactor)); const length3 = vec1Pos.length(); vec3Side.crossVectors(parentSubray.up0, vec2Forward); const angle = 2 * Math.PI * random1(); vec3Side.multiplyScalar(Math.cos(angle)); vec4Up.copy(parentSubray.up0).multiplyScalar(Math.sin(angle)); childSubray.pos1.copy(vec3Side).add(vec4Up).multiplyScalar(length3 * sideWidthFactor * (minSideWidthFactor + random1() * (1 - minSideWidthFactor))).add(vec1Pos).add(parentSubray.pos0); }; } createSubray() { return { seed: 0, maxIterations: 0, recursion: 0, pos0: new Vector3(), pos1: new Vector3(), linPos0: new Vector3(), linPos1: new Vector3(), up0: new Vector3(), up1: new Vector3(), radius0: 0, radius1: 0, birthTime: 0, deathTime: 0, timeScale: 0, roughness: 0, straightness: 0, propagationTimeFactor: 0, vanishingTimeFactor: 0, endPropagationTime: 0, beginVanishingTime: 0 }; } createSegment() { return { iteration: 0, pos0: new Vector3(), pos1: new Vector3(), linPos0: new Vector3(), linPos1: new Vector3(), up0: new Vector3(), up1: new Vector3(), radius0: 0, radius1: 0, fraction0: 0, fraction1: 0, positionVariationFactor: 0 }; } getNewSegment() { return this.raySegments[this.currentSegmentIndex++]; } copy(source) { super.copy(source); this.init(_LightningStrike.copyParameters({}, source.rayParameters)); return this; } clone() { return new this.constructor(_LightningStrike.copyParameters({}, this.rayParameters)); } }; let LightningStrike2 = _LightningStrike; __publicField7(LightningStrike2, "RAY_INITIALIZED", 0); __publicField7(LightningStrike2, "RAY_UNBORN", 1); __publicField7(LightningStrike2, "RAY_PROPAGATING", 2); __publicField7(LightningStrike2, "RAY_STEADY", 3); __publicField7(LightningStrike2, "RAY_VANISHING", 4); __publicField7(LightningStrike2, "RAY_EXTINGUISHED", 5); __publicField7(LightningStrike2, "COS30DEG", Math.cos(30 * Math.PI / 180)); __publicField7(LightningStrike2, "SIN30DEG", Math.sin(30 * Math.PI / 180)); return LightningStrike2; })(); // node_modules/three-stdlib/objects/ReflectorForSSRPass.js var __defProp8 = Object.defineProperty; var __defNormalProp8 = (obj, key, value) => key in obj ? __defProp8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField8 = (obj, key, value) => { __defNormalProp8(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var ReflectorForSSRPass = (() => { const _ReflectorForSSRPass = class extends Mesh { constructor(geometry3, options = {}) { super(geometry3); 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(val) { if (scope._distanceAttenuation === val) return; scope._distanceAttenuation = val; scope.material.defines.DISTANCE_ATTENUATION = val; scope.material.needsUpdate = true; } }); scope._fresnel = _ReflectorForSSRPass.ReflectorShader.defines.FRESNEL; Object.defineProperty(scope, "fresnel", { get() { return scope._fresnel; }, set(val) { if (scope._fresnel === val) return; scope._fresnel = val; scope.material.defines.FRESNEL = val; scope.material.needsUpdate = true; } }); const normal2 = 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 target2 = 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({ 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(renderer, 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); normal2.set(0, 0, 1); normal2.applyMatrix4(rotationMatrix2); view.subVectors(reflectorWorldPosition, cameraWorldPosition); if (view.dot(normal2) > 0) return; view.reflect(normal2).negate(); view.add(reflectorWorldPosition); rotationMatrix2.extractRotation(camera.matrixWorld); lookAtPosition.set(0, 0, -1); lookAtPosition.applyMatrix4(rotationMatrix2); lookAtPosition.add(cameraWorldPosition); target2.subVectors(reflectorWorldPosition, lookAtPosition); target2.reflect(normal2).negate(); target2.add(reflectorWorldPosition); virtualCamera.position.copy(view); virtualCamera.up.set(0, 1, 0); virtualCamera.up.applyMatrix4(rotationMatrix2); virtualCamera.up.reflect(normal2); virtualCamera.lookAt(target2); 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 = renderer.getRenderTarget(); const currentXrEnabled = renderer.xr.enabled; const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; const currentClippingPlanes = renderer.clippingPlanes; renderer.xr.enabled = false; renderer.shadowMap.autoUpdate = false; renderer.clippingPlanes = globalPlanes; renderer.setRenderTarget(renderTarget); renderer.state.buffers.depth.setMask(true); if (renderer.autoClear === false) renderer.clear(); renderer.render(scene, virtualCamera); renderer.xr.enabled = currentXrEnabled; renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; renderer.clippingPlanes = currentClippingPlanes; renderer.setRenderTarget(currentRenderTarget); const viewport = camera.viewport; if (viewport !== void 0) { renderer.state.viewport(viewport); } }; this.getRenderTarget = function() { return renderTarget; }; } }; let ReflectorForSSRPass2 = _ReflectorForSSRPass; __publicField8(ReflectorForSSRPass2, "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 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 } ` ) }); return ReflectorForSSRPass2; })(); // node_modules/three-stdlib/objects/Sky.js var __defProp9 = Object.defineProperty; var __defNormalProp9 = (obj, key, value) => key in obj ? __defProp9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField9 = (obj, key, value) => { __defNormalProp9(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Sky = (() => { const 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-calcuation 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 (absorbtion + 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; const vec3 cameraPos = vec3( 0.0, 0.0, 0.0 ); // 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 - cameraPos ); // 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 #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}> } ` ) }; const material = new ShaderMaterial({ name: "SkyShader", fragmentShader: SkyShader.fragmentShader, vertexShader: SkyShader.vertexShader, uniforms: UniformsUtils.clone(SkyShader.uniforms), side: BackSide, depthWrite: false }); class Sky22 extends Mesh { constructor() { super(new BoxGeometry(1, 1, 1), material); } } __publicField9(Sky22, "SkyShader", SkyShader); __publicField9(Sky22, "material", material); return Sky22; })(); // node_modules/three-stdlib/objects/Water2.js var __defProp10 = Object.defineProperty; var __defNormalProp10 = (obj, key, value) => key in obj ? __defProp10(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField10 = (obj, key, value) => { __defNormalProp10(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Water2 = (() => { const _Water2 = class extends Mesh { constructor(geometry3, options = {}) { super(geometry3); 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 || 512; const textureHeight = options.textureHeight || 512; const clipBias = options.clipBias || 0; const flowDirection = options.flowDirection || new Vector2(1, 0); const flowSpeed = options.flowSpeed || 0.03; const reflectivity = options.reflectivity || 0.02; const scale5 = options.scale || 1; const shader = options.shader || _Water2.WaterShader; const encoding = options.encoding !== void 0 ? options.encoding : 3e3; const flowMap = options.flowMap || void 0; const normalMap0 = options.normalMap0; const normalMap1 = options.normalMap1; 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(geometry3, { textureWidth, textureHeight, clipBias, encoding }); const refractor = new Refractor(geometry3, { textureWidth, textureHeight, clipBias, encoding }); reflector.matrixAutoUpdate = false; refractor.matrixAutoUpdate = false; this.material = new ShaderMaterial({ 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 = scale5; 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(renderer, scene, camera) { updateTextureMatrix(camera); updateFlow(); scope.visible = false; reflector.matrixWorld.copy(scope.matrixWorld); refractor.matrixWorld.copy(scope.matrixWorld); reflector.onBeforeRender(renderer, scene, camera); refractor.onBeforeRender(renderer, scene, camera); scope.visible = true; }; } }; let Water22 = _Water2; __publicField10(Water22, "WaterShader", { uniforms: { color: { value: null }, reflectivity: { value: 0 }, tReflectionMap: { value: null }, tRefractionMap: { value: null }, tNormalMap0: { value: null }, tNormalMap1: { value: null }, textureMatrix: { value: null }, config: { value: new Vector4() } }, vertexShader: ( /* glsl */ ` #include #include #include 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 #include }` ), fragmentShader: ( /* glsl */ ` #include #include #include 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 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 #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}> #include }` ) }); return Water22; })(); // node_modules/three-stdlib/objects/GroundProjectedEnv.js var isCubeTexture = (def) => def && def.isCubeTexture; var GroundProjectedEnv = class extends Mesh { constructor(texture, options) { var _a3, _b3; const isCubeMap = isCubeTexture(texture); const w = (_b3 = isCubeMap ? (_a3 = texture.image[0]) == null ? void 0 : _a3.width : texture.image.width) != null ? _b3 : 1024; const cubeSize = w / 4; const _lodMax = Math.floor(Math.log2(cubeSize)); const _cubeSize = Math.pow(2, _lodMax); const width = 3 * Math.max(_cubeSize, 16 * 7); const height = 4 * _cubeSize; const defines = [ isCubeMap ? "#define ENVMAP_TYPE_CUBE" : "", `#define CUBEUV_TEXEL_WIDTH ${1 / width}`, `#define CUBEUV_TEXEL_HEIGHT ${1 / height}`, `#define CUBEUV_MAX_MIP ${_lodMax}.0` ]; const vertexShader3 = ( /* glsl */ ` varying vec3 vWorldPosition; void main() { vec4 worldPosition = ( modelMatrix * vec4( position, 1.0 ) ); vWorldPosition = worldPosition.xyz; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } ` ); const fragmentShader3 = defines.join("\n") + /* glsl */ ` #define ENVMAP_TYPE_CUBE_UV varying vec3 vWorldPosition; uniform float radius; uniform float height; uniform float angle; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube map; #else uniform sampler2D map; #endif // From: https://www.shadertoy.com/view/4tsBD7 float diskIntersectWithBackFaceCulling( vec3 ro, vec3 rd, vec3 c, vec3 n, float r ) { float d = dot ( rd, n ); if( d > 0.0 ) { return 1e6; } vec3 o = ro - c; float t = - dot( n, o ) / d; vec3 q = o + rd * t; return ( dot( q, q ) < r * r ) ? t : 1e6; } // From: https://www.iquilezles.org/www/articles/intersectors/intersectors.htm float sphereIntersect( vec3 ro, vec3 rd, vec3 ce, float ra ) { vec3 oc = ro - ce; float b = dot( oc, rd ); float c = dot( oc, oc ) - ra * ra; float h = b * b - c; if( h < 0.0 ) { return -1.0; } h = sqrt( h ); return - b + h; } vec3 project() { vec3 p = normalize( vWorldPosition ); vec3 camPos = cameraPosition; camPos.y -= height; float intersection = sphereIntersect( camPos, p, vec3( 0.0 ), radius ); if( intersection > 0.0 ) { vec3 h = vec3( 0.0, - height, 0.0 ); float intersection2 = diskIntersectWithBackFaceCulling( camPos, p, h, vec3( 0.0, 1.0, 0.0 ), radius ); p = ( camPos + min( intersection, intersection2 ) * p ) / radius; } else { p = vec3( 0.0, 1.0, 0.0 ); } return p; } #include #include void main() { vec3 projectedWorldPosition = project(); #ifdef ENVMAP_TYPE_CUBE vec3 outcolor = textureCube( map, projectedWorldPosition ).rgb; #else vec3 direction = normalize( projectedWorldPosition ); vec2 uv = equirectUv( direction ); vec3 outcolor = texture2D( map, uv ).rgb; #endif gl_FragColor = vec4( outcolor, 1.0 ); #include #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}> } `; const uniforms = { map: { value: texture }, height: { value: (options == null ? void 0 : options.height) || 15 }, radius: { value: (options == null ? void 0 : options.radius) || 100 } }; const geometry3 = new IcosahedronGeometry(1, 16); const material = new ShaderMaterial({ uniforms, fragmentShader: fragmentShader3, vertexShader: vertexShader3, side: DoubleSide }); super(geometry3, material); } set radius(radius) { this.material.uniforms.radius.value = radius; } get radius() { return this.material.uniforms.radius.value; } set height(height) { this.material.uniforms.height.value = height; } get height() { return this.material.uniforms.height.value; } }; // node_modules/three-stdlib/utils/RoughnessMipmapper.js var _mipmapMaterial = _getMipmapMaterial(); var _mesh = new Mesh(new PlaneGeometry(2, 2), _mipmapMaterial); var _flatCamera = new OrthographicCamera(0, 1, 0, 1, 0, 1); function _getMipmapMaterial() { var shaderMaterial2 = new RawShaderMaterial({ uniforms: { roughnessMap: { value: null }, normalMap: { value: null }, texelSize: { value: new Vector2(1, 1) } }, vertexShader: ( /* glsl */ ` precision mediump float; precision mediump int; attribute vec3 position; attribute vec2 uv; varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4( position, 1.0 ); } ` ), fragmentShader: ( /* glsl */ ` precision mediump float; precision mediump int; varying vec2 vUv; uniform sampler2D roughnessMap; uniform sampler2D normalMap; uniform vec2 texelSize; #define ENVMAP_TYPE_CUBE_UV vec4 envMapTexelToLinear( vec4 a ) { return a; } #include float roughnessToVariance( float roughness ) { float variance = 0.0; if ( roughness >= r1 ) { variance = ( r0 - roughness ) * ( v1 - v0 ) / ( r0 - r1 ) + v0; } else if ( roughness >= r4 ) { variance = ( r1 - roughness ) * ( v4 - v1 ) / ( r1 - r4 ) + v1; } else if ( roughness >= r5 ) { variance = ( r4 - roughness ) * ( v5 - v4 ) / ( r4 - r5 ) + v4; } else { float roughness2 = roughness * roughness; variance = 1.79 * roughness2 * roughness2; } return variance; } float varianceToRoughness( float variance ) { float roughness = 0.0; if ( variance >= v1 ) { roughness = ( v0 - variance ) * ( r1 - r0 ) / ( v0 - v1 ) + r0; } else if ( variance >= v4 ) { roughness = ( v1 - variance ) * ( r4 - r1 ) / ( v1 - v4 ) + r1; } else if ( variance >= v5 ) { roughness = ( v4 - variance ) * ( r5 - r4 ) / ( v4 - v5 ) + r4; } else { roughness = pow( 0.559 * variance, 0.25 ); // 0.559 = 1.0 / 1.79 } return roughness; } void main() { gl_FragColor = texture2D( roughnessMap, vUv, - 1.0 ); if ( texelSize.x == 0.0 ) return; float roughness = gl_FragColor.g; float variance = roughnessToVariance( roughness ); vec3 avgNormal; for ( float x = - 1.0; x < 2.0; x += 2.0 ) { for ( float y = - 1.0; y < 2.0; y += 2.0 ) { vec2 uv = vUv + vec2( x, y ) * 0.25 * texelSize; avgNormal += normalize( texture2D( normalMap, uv, - 1.0 ).xyz - 0.5 ); } } variance += 1.0 - 0.25 * length( avgNormal ); gl_FragColor.g = varianceToRoughness( variance ); } ` ), blending: NoBlending, depthTest: false, depthWrite: false }); shaderMaterial2.type = "RoughnessMipmapper"; return shaderMaterial2; } // node_modules/three-stdlib/utils/SkeletonUtils.js function retarget(target2, source, options = {}) { const pos = new Vector3(), quat = new Quaternion(), scale5 = new Vector3(), bindBoneMatrix = new Matrix4(), relativeMatrix = new Matrix4(), globalMatrix = new Matrix4(); options.preserveMatrix = options.preserveMatrix !== void 0 ? options.preserveMatrix : true; options.preservePosition = options.preservePosition !== void 0 ? options.preservePosition : true; options.preserveHipPosition = options.preserveHipPosition !== void 0 ? options.preserveHipPosition : false; options.useTargetMatrix = options.useTargetMatrix !== void 0 ? options.useTargetMatrix : false; options.hip = options.hip !== void 0 ? options.hip : "hip"; options.names = options.names || {}; const sourceBones = source.isObject3D ? source.skeleton.bones : getBones(source), bones = target2.isObject3D ? target2.skeleton.bones : getBones(target2); let bindBones, bone, name, boneTo, bonesPosition; if (target2.isObject3D) { target2.skeleton.pose(); } else { options.useTargetMatrix = true; options.preserveMatrix = false; } if (options.preservePosition) { bonesPosition = []; for (let i4 = 0; i4 < bones.length; i4++) { bonesPosition.push(bones[i4].position.clone()); } } if (options.preserveMatrix) { target2.updateMatrixWorld(); target2.matrixWorld.identity(); for (let i4 = 0; i4 < target2.children.length; ++i4) { target2.children[i4].updateMatrixWorld(true); } } if (options.offsets) { bindBones = []; for (let i4 = 0; i4 < bones.length; ++i4) { bone = bones[i4]; name = options.names[bone.name] || bone.name; if (options.offsets[name]) { bone.matrix.multiply(options.offsets[name]); bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); bone.updateMatrixWorld(); } bindBones.push(bone.matrixWorld.clone()); } } for (let i4 = 0; i4 < bones.length; ++i4) { bone = bones[i4]; name = options.names[bone.name] || bone.name; boneTo = getBoneByName(name, sourceBones); globalMatrix.copy(bone.matrixWorld); if (boneTo) { boneTo.updateMatrixWorld(); if (options.useTargetMatrix) { relativeMatrix.copy(boneTo.matrixWorld); } else { relativeMatrix.copy(target2.matrixWorld).invert(); relativeMatrix.multiply(boneTo.matrixWorld); } scale5.setFromMatrixScale(relativeMatrix); relativeMatrix.scale(scale5.set(1 / scale5.x, 1 / scale5.y, 1 / scale5.z)); globalMatrix.makeRotationFromQuaternion(quat.setFromRotationMatrix(relativeMatrix)); if (target2.isObject3D) { const boneIndex = bones.indexOf(bone), wBindMatrix = bindBones ? bindBones[boneIndex] : bindBoneMatrix.copy(target2.skeleton.boneInverses[boneIndex]).invert(); globalMatrix.multiply(wBindMatrix); } globalMatrix.copyPosition(relativeMatrix); } if (bone.parent && bone.parent.isBone) { bone.matrix.copy(bone.parent.matrixWorld).invert(); bone.matrix.multiply(globalMatrix); } else { bone.matrix.copy(globalMatrix); } if (options.preserveHipPosition && name === options.hip) { bone.matrix.setPosition(pos.set(0, bone.position.y, 0)); } bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); bone.updateMatrixWorld(); } if (options.preservePosition) { for (let i4 = 0; i4 < bones.length; ++i4) { bone = bones[i4]; name = options.names[bone.name] || bone.name; if (name !== options.hip) { bone.position.copy(bonesPosition[i4]); } } } if (options.preserveMatrix) { target2.updateMatrixWorld(true); } } function retargetClip(target2, source, clip, options = {}) { options.useFirstFramePosition = options.useFirstFramePosition !== void 0 ? options.useFirstFramePosition : false; options.fps = options.fps !== void 0 ? options.fps : 30; options.names = options.names || []; if (!source.isObject3D) { source = getHelperFromSkeleton(source); } const numFrames = Math.round(clip.duration * (options.fps / 1e3) * 1e3), delta = 1 / options.fps, convertedTracks = [], mixer = new AnimationMixer(source), bones = getBones(target2.skeleton), boneDatas = []; let positionOffset, bone, boneTo, boneData, name; mixer.clipAction(clip).play(); mixer.update(0); source.updateMatrixWorld(); for (let i4 = 0; i4 < numFrames; ++i4) { const time = i4 * delta; retarget(target2, source, options); for (let j = 0; j < bones.length; ++j) { name = options.names[bones[j].name] || bones[j].name; boneTo = getBoneByName(name, source.skeleton); if (boneTo) { bone = bones[j]; boneData = boneDatas[j] = boneDatas[j] || { bone }; if (options.hip === name) { if (!boneData.pos) { boneData.pos = { times: new Float32Array(numFrames), values: new Float32Array(numFrames * 3) }; } if (options.useFirstFramePosition) { if (i4 === 0) { positionOffset = bone.position.clone(); } bone.position.sub(positionOffset); } boneData.pos.times[i4] = time; bone.position.toArray(boneData.pos.values, i4 * 3); } if (!boneData.quat) { boneData.quat = { times: new Float32Array(numFrames), values: new Float32Array(numFrames * 4) }; } boneData.quat.times[i4] = time; bone.quaternion.toArray(boneData.quat.values, i4 * 4); } } mixer.update(delta); source.updateMatrixWorld(); } for (let i4 = 0; i4 < boneDatas.length; ++i4) { boneData = boneDatas[i4]; 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(name, skeleton) { for (let i4 = 0, bones = getBones(skeleton); i4 < bones.length; i4++) { if (name === bones[i4].name) return bones[i4]; } } 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(a6, b5, callback) { callback(a6, b5); for (let i4 = 0; i4 < a6.children.length; i4++) { parallelTraverse(a6.children[i4], b5.children[i4], callback); } } var SkeletonUtils = { retarget, retargetClip, clone }; // node_modules/three-stdlib/shaders/UnpackDepthRGBAShader.js var 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 void main() { float depth = 1.0 - unpackRGBAToDepth( texture2D( tDiffuse, vUv ) ); gl_FragColor = vec4( vec3( depth ), opacity ); } ` ) }; // node_modules/three-stdlib/shaders/BokehShader2.js var BokehShader2 = { 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 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 vignete 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; } ` ) }; // node_modules/three-stdlib/math/MeshSurfaceSampler.js var _face = new Triangle(); var _color = new Vector3(); var MeshSurfaceSampler = class { constructor(mesh) { let geometry3 = mesh.geometry; if (geometry3.index) { console.warn("THREE.MeshSurfaceSampler: Converting geometry to non-indexed BufferGeometry."); geometry3 = geometry3.toNonIndexed(); } this.geometry = geometry3; this.randomFunction = Math.random; this.positionAttribute = this.geometry.getAttribute("position"); this.colorAttribute = this.geometry.getAttribute("color"); this.weightAttribute = null; this.distribution = null; } setWeightAttribute(name) { this.weightAttribute = name ? this.geometry.getAttribute(name) : null; return this; } build() { const positionAttribute = this.positionAttribute; const weightAttribute = this.weightAttribute; const faceWeights = new Float32Array(positionAttribute.count / 3); for (let i4 = 0; i4 < positionAttribute.count; i4 += 3) { let faceWeight = 1; if (weightAttribute) { faceWeight = weightAttribute.getX(i4) + weightAttribute.getX(i4 + 1) + weightAttribute.getX(i4 + 2); } _face.a.fromBufferAttribute(positionAttribute, i4); _face.b.fromBufferAttribute(positionAttribute, i4 + 1); _face.c.fromBufferAttribute(positionAttribute, i4 + 2); faceWeight *= _face.getArea(); faceWeights[i4 / 3] = faceWeight; } this.distribution = new Float32Array(positionAttribute.count / 3); let cumulativeTotal = 0; for (let i4 = 0; i4 < faceWeights.length; i4++) { cumulativeTotal += faceWeights[i4]; this.distribution[i4] = cumulativeTotal; } return this; } setRandomGenerator(randomFunction) { this.randomFunction = randomFunction; return this; } sample(targetPosition3, targetNormal, targetColor) { const faceIndex = this.sampleFaceIndex(); return this.sampleFace(faceIndex, targetPosition3, targetNormal, targetColor); } sampleFaceIndex() { const cumulativeTotal = this.distribution[this.distribution.length - 1]; return this.binarySearch(this.randomFunction() * cumulativeTotal); } binarySearch(x) { 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] <= x && dist[mid] > x) { index2 = mid; break; } else if (x < dist[mid]) { end = mid - 1; } else { start = mid + 1; } } return index2; } sampleFace(faceIndex, targetPosition3, targetNormal, targetColor) { let u = this.randomFunction(); let v5 = this.randomFunction(); if (u + v5 > 1) { u = 1 - u; v5 = 1 - v5; } _face.a.fromBufferAttribute(this.positionAttribute, faceIndex * 3); _face.b.fromBufferAttribute(this.positionAttribute, faceIndex * 3 + 1); _face.c.fromBufferAttribute(this.positionAttribute, faceIndex * 3 + 2); targetPosition3.set(0, 0, 0).addScaledVector(_face.a, u).addScaledVector(_face.b, v5).addScaledVector(_face.c, 1 - (u + v5)); if (targetNormal !== void 0) { _face.getNormal(targetNormal); } if (targetColor !== void 0 && this.colorAttribute !== void 0) { _face.a.fromBufferAttribute(this.colorAttribute, faceIndex * 3); _face.b.fromBufferAttribute(this.colorAttribute, faceIndex * 3 + 1); _face.c.fromBufferAttribute(this.colorAttribute, faceIndex * 3 + 2); _color.set(0, 0, 0).addScaledVector(_face.a, u).addScaledVector(_face.b, v5).addScaledVector(_face.c, 1 - (u + v5)); targetColor.r = _color.x; targetColor.g = _color.y; targetColor.b = _color.z; } return this; } }; // node_modules/three-stdlib/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 R = [[], [], []]; var AbsR = [[], [], []]; var t = []; var xAxis = new Vector3(); var yAxis = new Vector3(); var zAxis = new Vector3(); var v12 = new Vector3(); var size = new Vector3(); var closestPoint = new Vector3(); var rotationMatrix = new Matrix3(); var aabb = new Box3(); var matrix3 = new Matrix4(); var inverse = new Matrix4(); var localRay = new Ray(); var OBB = class { constructor(center3 = new Vector3(), halfSize = new Vector3(), rotation3 = new Matrix3()) { this.center = center3; this.halfSize = halfSize; this.rotation = rotation3; } set(center3, halfSize, rotation3) { this.center = center3; this.halfSize = halfSize; this.rotation = rotation3; return this; } copy(obb26) { this.center.copy(obb26.center); this.halfSize.copy(obb26.halfSize); this.rotation.copy(obb26.rotation); return this; } clone() { return new this.constructor().copy(this); } getSize(result) { return result.copy(this.halfSize).multiplyScalar(2); } /** * Reference: Closest Point on OBB to Point in Real-Time Collision Detection * by Christer Ericson (chapter 5.1.4) */ clampPoint(point, result) { const halfSize = this.halfSize; v12.subVectors(point, this.center); this.rotation.extractBasis(xAxis, yAxis, zAxis); result.copy(this.center); const x = MathUtils.clamp(v12.dot(xAxis), -halfSize.x, halfSize.x); result.add(xAxis.multiplyScalar(x)); const y = MathUtils.clamp(v12.dot(yAxis), -halfSize.y, halfSize.y); result.add(yAxis.multiplyScalar(y)); const z = MathUtils.clamp(v12.dot(zAxis), -halfSize.z, halfSize.z); result.add(zAxis.multiplyScalar(z)); return result; } containsPoint(point) { v12.subVectors(point, this.center); this.rotation.extractBasis(xAxis, yAxis, zAxis); return Math.abs(v12.dot(xAxis)) <= this.halfSize.x && Math.abs(v12.dot(yAxis)) <= this.halfSize.y && Math.abs(v12.dot(zAxis)) <= this.halfSize.z; } intersectsBox3(box3) { return this.intersectsOBB(obb.fromBox3(box3)); } intersectsSphere(sphere) { this.clampPoint(sphere.center, closestPoint); return closestPoint.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; } /** * Reference: OBB-OBB Intersection in Real-Time Collision Detection * by Christer Ericson (chapter 4.4.1) * */ intersectsOBB(obb26, epsilon2 = 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 = obb26.center; b.e[0] = obb26.halfSize.x; b.e[1] = obb26.halfSize.y; b.e[2] = obb26.halfSize.z; obb26.rotation.extractBasis(b.u[0], b.u[1], b.u[2]); for (let i4 = 0; i4 < 3; i4++) { for (let j = 0; j < 3; j++) { R[i4][j] = a.u[i4].dot(b.u[j]); } } v12.subVectors(b.c, a.c); t[0] = v12.dot(a.u[0]); t[1] = v12.dot(a.u[1]); t[2] = v12.dot(a.u[2]); for (let i4 = 0; i4 < 3; i4++) { for (let j = 0; j < 3; j++) { AbsR[i4][j] = Math.abs(R[i4][j]) + epsilon2; } } let ra, rb; for (let i4 = 0; i4 < 3; i4++) { ra = a.e[i4]; rb = b.e[0] * AbsR[i4][0] + b.e[1] * AbsR[i4][1] + b.e[2] * AbsR[i4][2]; if (Math.abs(t[i4]) > ra + rb) return false; } for (let i4 = 0; i4 < 3; i4++) { ra = a.e[0] * AbsR[0][i4] + a.e[1] * AbsR[1][i4] + a.e[2] * AbsR[2][i4]; rb = b.e[i4]; if (Math.abs(t[0] * R[0][i4] + t[1] * R[1][i4] + t[2] * R[2][i4]) > ra + rb) return false; } ra = 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(t[2] * R[1][0] - t[1] * R[2][0]) > ra + rb) return false; ra = 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(t[2] * R[1][1] - t[1] * R[2][1]) > ra + rb) return false; ra = 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(t[2] * R[1][2] - t[1] * R[2][2]) > ra + rb) return false; ra = 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(t[0] * R[2][0] - t[2] * R[0][0]) > ra + rb) return false; ra = 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(t[0] * R[2][1] - t[2] * R[0][1]) > ra + rb) return false; ra = 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(t[0] * R[2][2] - t[2] * R[0][2]) > ra + rb) return false; ra = 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(t[1] * R[0][0] - t[0] * R[1][0]) > ra + rb) return false; ra = 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(t[1] * R[0][1] - t[0] * R[1][1]) > ra + rb) return false; ra = 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(t[1] * R[0][2] - t[0] * R[1][2]) > ra + rb) return false; return true; } /** * Reference: Testing Box Against Plane in Real-Time Collision Detection * by Christer Ericson (chapter 5.2.3) */ intersectsPlane(plane) { this.rotation.extractBasis(xAxis, yAxis, zAxis); const r2 = this.halfSize.x * Math.abs(plane.normal.dot(xAxis)) + this.halfSize.y * Math.abs(plane.normal.dot(yAxis)) + this.halfSize.z * Math.abs(plane.normal.dot(zAxis)); const d2 = plane.normal.dot(this.center) - plane.constant; return Math.abs(d2) <= r2; } /** * Performs a ray/OBB intersection test and stores the intersection point * to the given 3D vector. If no intersection is detected, *null* is returned. */ intersectRay(ray4, result) { this.getSize(size); aabb.setFromCenterAndSize(v12.set(0, 0, 0), size); matrix3.setFromMatrix3(this.rotation); matrix3.setPosition(this.center); inverse.copy(matrix3).invert(); localRay.copy(ray4).applyMatrix4(inverse); if (localRay.intersectBox(aabb, result)) { return result.applyMatrix4(matrix3); } else { return null; } } /** * Performs a ray/OBB intersection test. Returns either true or false if * there is a intersection or not. */ intersectsRay(ray4) { return this.intersectRay(ray4, v12) !== null; } fromBox3(box3) { box3.getCenter(this.center); box3.getSize(this.halfSize).multiplyScalar(0.5); this.rotation.identity(); return this; } equals(obb26) { return obb26.center.equals(this.center) && obb26.halfSize.equals(this.halfSize) && obb26.rotation.equals(this.rotation); } applyMatrix4(matrix22) { const e2 = matrix22.elements; let sx = v12.set(e2[0], e2[1], e2[2]).length(); const sy = v12.set(e2[4], e2[5], e2[6]).length(); const sz = v12.set(e2[8], e2[9], e2[10]).length(); const det = matrix22.determinant(); if (det < 0) sx = -sx; rotationMatrix.setFromMatrix4(matrix22); 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; v12.setFromMatrixPosition(matrix22); this.center.add(v12); return this; } }; var obb = new OBB(); // node_modules/three-stdlib/math/Capsule.js var _v13 = new Vector3(); var _v2 = new Vector3(); var _v3 = new Vector3(); var EPS = 1e-10; var Capsule = class _Capsule { constructor(start = new Vector3(0, 0, 0), end = new Vector3(0, 1, 0), radius = 1) { this.start = start; this.end = end; this.radius = radius; } clone() { return new _Capsule(this.start.clone(), this.end.clone(), this.radius); } set(start, end, radius) { this.start.copy(start); this.end.copy(end); this.radius = radius; } copy(capsule) { this.start.copy(capsule.start); this.end.copy(capsule.end); this.radius = capsule.radius; } getCenter(target2) { return target2.copy(this.end).add(this.start).multiplyScalar(0.5); } translate(v5) { this.start.add(v5); this.end.add(v5); } 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); } intersectsBox(box) { return this.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 ) && this.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 ) && this.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 ); } lineLineMinimumPoints(line1, line2) { const r2 = _v13.copy(line1.end).sub(line1.start); const s2 = _v2.copy(line2.end).sub(line2.start); const w = _v3.copy(line2.start).sub(line1.start); const a6 = r2.dot(s2), b5 = r2.dot(r2), c2 = s2.dot(s2), d2 = s2.dot(w), e2 = r2.dot(w); let t1, t22; const divisor = b5 * c2 - a6 * a6; if (Math.abs(divisor) < EPS) { const d1 = -d2 / c2; const d22 = (a6 - d2) / c2; if (Math.abs(d1 - 0.5) < Math.abs(d22 - 0.5)) { t1 = 0; t22 = d1; } else { t1 = 1; t22 = d22; } } else { t1 = (d2 * a6 + e2 * c2) / divisor; t22 = (t1 * a6 - d2) / c2; } t22 = Math.max(0, Math.min(1, t22)); t1 = Math.max(0, Math.min(1, t1)); const point1 = r2.multiplyScalar(t1).add(line1.start); const point2 = s2.multiplyScalar(t22).add(line2.start); return [point1, point2]; } }; // node_modules/three-stdlib/math/ImprovedNoise.js function init() { const _p2 = [ 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 i4 = 0; i4 < 256; i4++) { _p2[256 + i4] = _p2[i4]; } return _p2; } var _p = init(); // node_modules/three-stdlib/math/Octree.js var _v14 = new Vector3(); var _v22 = new Vector3(); var _plane2 = new Plane(); var _line1 = new Line3(); var _line2 = new Line3(); var _sphere = new Sphere(); var _capsule = new Capsule(); // node_modules/three-stdlib/controls/EventDispatcher.js var __defProp11 = Object.defineProperty; var __defNormalProp11 = (obj, key, value) => key in obj ? __defProp11(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField11 = (obj, key, value) => { __defNormalProp11(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var EventDispatcher2 = class { constructor() { __publicField11(this, "_listeners"); } /** * Adds a listener to an event type. * @param type The type of event to listen to. * @param listener The function that gets called when the event is fired. */ addEventListener(type, listener) { if (this._listeners === void 0) this._listeners = {}; const listeners = this._listeners; if (listeners[type] === void 0) { listeners[type] = []; } if (listeners[type].indexOf(listener) === -1) { listeners[type].push(listener); } } /** * Checks if listener is added to an event type. * @param type The type of event to listen to. * @param listener The function that gets called when the event is fired. */ hasEventListener(type, listener) { if (this._listeners === void 0) return false; const listeners = this._listeners; return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1; } /** * Removes a listener from an event type. * @param type The type of the listener that gets removed. * @param listener The listener function that gets removed. */ removeEventListener(type, listener) { if (this._listeners === void 0) return; const listeners = this._listeners; const listenerArray = listeners[type]; if (listenerArray !== void 0) { const index2 = listenerArray.indexOf(listener); if (index2 !== -1) { listenerArray.splice(index2, 1); } } } /** * Fire an event type. * @param event The event that gets fired. */ dispatchEvent(event) { if (this._listeners === void 0) return; const listeners = this._listeners; const listenerArray = listeners[event.type]; if (listenerArray !== void 0) { event.target = this; const array = listenerArray.slice(0); for (let i4 = 0, l2 = array.length; i4 < l2; i4++) { array[i4].call(this, event); } event.target = null; } } }; // node_modules/three-stdlib/controls/FirstPersonControls.js var __defProp12 = Object.defineProperty; var __defNormalProp12 = (obj, key, value) => key in obj ? __defProp12(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField12 = (obj, key, value) => { __defNormalProp12(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var targetPosition = new Vector3(); var FirstPersonControls = class extends EventDispatcher2 { constructor(object, domElement) { super(); __publicField12(this, "object"); __publicField12(this, "domElement"); __publicField12(this, "enabled", true); __publicField12(this, "movementSpeed", 1); __publicField12(this, "lookSpeed", 5e-3); __publicField12(this, "lookVertical", true); __publicField12(this, "autoForward", false); __publicField12(this, "activeLook", true); __publicField12(this, "heightSpeed", false); __publicField12(this, "heightCoef", 1); __publicField12(this, "heightMin", 0); __publicField12(this, "heightMax", 1); __publicField12(this, "constrainVertical", false); __publicField12(this, "verticalMin", 0); __publicField12(this, "verticalMax", Math.PI); __publicField12(this, "mouseDragOn", false); __publicField12(this, "autoSpeedFactor", 0); __publicField12(this, "mouseX", 0); __publicField12(this, "mouseY", 0); __publicField12(this, "moveForward", false); __publicField12(this, "moveBackward", false); __publicField12(this, "moveLeft", false); __publicField12(this, "moveRight", false); __publicField12(this, "moveUp", false); __publicField12(this, "moveDown", false); __publicField12(this, "viewHalfX", 0); __publicField12(this, "viewHalfY", 0); __publicField12(this, "lat", 0); __publicField12(this, "lon", 0); __publicField12(this, "lookDirection", new Vector3()); __publicField12(this, "spherical", new Spherical()); __publicField12(this, "target", new Vector3()); __publicField12(this, "connect", (domElement2) => { domElement2.setAttribute("tabindex", "-1"); domElement2.style.touchAction = "none"; domElement2.addEventListener("contextmenu", this.contextmenu); domElement2.addEventListener("mousemove", this.onMouseMove); domElement2.addEventListener("mousedown", this.onMouseDown); domElement2.addEventListener("mouseup", this.onMouseUp); this.domElement = domElement2; window.addEventListener("keydown", this.onKeyDown); window.addEventListener("keyup", this.onKeyUp); this.handleResize(); }); __publicField12(this, "dispose", () => { var _a3, _b3, _c, _d; (_a3 = this.domElement) == null ? void 0 : _a3.removeEventListener("contextmenu", this.contextmenu); (_b3 = this.domElement) == null ? void 0 : _b3.removeEventListener("mousedown", this.onMouseDown); (_c = this.domElement) == null ? void 0 : _c.removeEventListener("mousemove", this.onMouseMove); (_d = this.domElement) == null ? void 0 : _d.removeEventListener("mouseup", this.onMouseUp); window.removeEventListener("keydown", this.onKeyDown); window.removeEventListener("keyup", this.onKeyUp); }); __publicField12(this, "handleResize", () => { if (this.domElement) { this.viewHalfX = this.domElement.offsetWidth / 2; this.viewHalfY = this.domElement.offsetHeight / 2; } }); __publicField12(this, "onMouseDown", (event) => { var _a3; (_a3 = this.domElement) == null ? void 0 : _a3.focus(); if (this.activeLook) { switch (event.button) { case 0: this.moveForward = true; break; case 2: this.moveBackward = true; break; } } this.mouseDragOn = true; }); __publicField12(this, "onMouseUp", (event) => { if (this.activeLook) { switch (event.button) { case 0: this.moveForward = false; break; case 2: this.moveBackward = false; break; } } this.mouseDragOn = false; }); __publicField12(this, "onMouseMove", (event) => { if (this.domElement) { this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX; this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY; } }); __publicField12(this, "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; } }); __publicField12(this, "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; } }); __publicField12(this, "lookAt", (x, y, z) => { if (x instanceof Vector3) { this.target.copy(x); } else if (y && z) { this.target.set(x, y, z); } this.object.lookAt(this.target); this.setOrientation(); return this; }); __publicField12(this, "update", (delta) => { if (!this.enabled) 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.mouseX * actualLookSpeed; if (this.lookVertical) this.lat -= this.mouseY * 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); }); __publicField12(this, "contextmenu", (event) => event.preventDefault()); __publicField12(this, "setOrientation", () => { this.lookDirection.set(0, 0, -1).applyQuaternion(this.object.quaternion); this.spherical.setFromVector3(this.lookDirection); this.lat = 90 - MathUtils.radToDeg(this.spherical.phi); this.lon = MathUtils.radToDeg(this.spherical.theta); }); this.object = object; this.domElement = domElement; this.setOrientation(); if (domElement) this.connect(domElement); } }; // node_modules/three-stdlib/controls/TransformControls.js var __defProp13 = Object.defineProperty; var __defNormalProp13 = (obj, key, value) => key in obj ? __defProp13(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField13 = (obj, key, value) => { __defNormalProp13(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var TransformControls = class extends Object3D { constructor(camera, domElement) { super(); __publicField13(this, "isTransformControls", true); __publicField13(this, "visible", false); __publicField13(this, "domElement"); __publicField13(this, "raycaster", new Raycaster()); __publicField13(this, "gizmo"); __publicField13(this, "plane"); __publicField13(this, "tempVector", new Vector3()); __publicField13(this, "tempVector2", new Vector3()); __publicField13(this, "tempQuaternion", new Quaternion()); __publicField13(this, "unit", { X: new Vector3(1, 0, 0), Y: new Vector3(0, 1, 0), Z: new Vector3(0, 0, 1) }); __publicField13(this, "pointStart", new Vector3()); __publicField13(this, "pointEnd", new Vector3()); __publicField13(this, "offset", new Vector3()); __publicField13(this, "rotationAxis", new Vector3()); __publicField13(this, "startNorm", new Vector3()); __publicField13(this, "endNorm", new Vector3()); __publicField13(this, "rotationAngle", 0); __publicField13(this, "cameraPosition", new Vector3()); __publicField13(this, "cameraQuaternion", new Quaternion()); __publicField13(this, "cameraScale", new Vector3()); __publicField13(this, "parentPosition", new Vector3()); __publicField13(this, "parentQuaternion", new Quaternion()); __publicField13(this, "parentQuaternionInv", new Quaternion()); __publicField13(this, "parentScale", new Vector3()); __publicField13(this, "worldPositionStart", new Vector3()); __publicField13(this, "worldQuaternionStart", new Quaternion()); __publicField13(this, "worldScaleStart", new Vector3()); __publicField13(this, "worldPosition", new Vector3()); __publicField13(this, "worldQuaternion", new Quaternion()); __publicField13(this, "worldQuaternionInv", new Quaternion()); __publicField13(this, "worldScale", new Vector3()); __publicField13(this, "eye", new Vector3()); __publicField13(this, "positionStart", new Vector3()); __publicField13(this, "quaternionStart", new Quaternion()); __publicField13(this, "scaleStart", new Vector3()); __publicField13(this, "camera"); __publicField13(this, "object"); __publicField13(this, "enabled", true); __publicField13(this, "axis", null); __publicField13(this, "mode", "translate"); __publicField13(this, "translationSnap", null); __publicField13(this, "rotationSnap", null); __publicField13(this, "scaleSnap", null); __publicField13(this, "space", "world"); __publicField13(this, "size", 1); __publicField13(this, "dragging", false); __publicField13(this, "showX", true); __publicField13(this, "showY", true); __publicField13(this, "showZ", true); __publicField13(this, "changeEvent", { type: "change" }); __publicField13(this, "mouseDownEvent", { type: "mouseDown", mode: this.mode }); __publicField13(this, "mouseUpEvent", { type: "mouseUp", mode: this.mode }); __publicField13(this, "objectChangeEvent", { type: "objectChange" }); __publicField13(this, "intersectObjectWithRay", (object, raycaster, includeInvisible) => { const allIntersections = raycaster.intersectObject(object, true); for (let i4 = 0; i4 < allIntersections.length; i4++) { if (allIntersections[i4].object.visible || includeInvisible) { return allIntersections[i4]; } } return false; }); __publicField13(this, "attach", (object) => { this.object = object; this.visible = true; return this; }); __publicField13(this, "detach", () => { this.object = void 0; this.visible = false; this.axis = null; return this; }); __publicField13(this, "reset", () => { if (!this.enabled) return this; if (this.dragging) { if (this.object !== void 0) { this.object.position.copy(this.positionStart); this.object.quaternion.copy(this.quaternionStart); this.object.scale.copy(this.scaleStart); this.dispatchEvent(this.changeEvent); this.dispatchEvent(this.objectChangeEvent); this.pointStart.copy(this.pointEnd); } } return this; }); __publicField13(this, "updateMatrixWorld", () => { if (this.object !== void 0) { this.object.updateMatrixWorld(); if (this.object.parent === null) { console.error("TransformControls: The attached 3D object must be a part of the scene graph."); } else { this.object.parent.matrixWorld.decompose(this.parentPosition, this.parentQuaternion, this.parentScale); } this.object.matrixWorld.decompose(this.worldPosition, this.worldQuaternion, this.worldScale); this.parentQuaternionInv.copy(this.parentQuaternion).invert(); this.worldQuaternionInv.copy(this.worldQuaternion).invert(); } this.camera.updateMatrixWorld(); this.camera.matrixWorld.decompose(this.cameraPosition, this.cameraQuaternion, this.cameraScale); this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(); super.updateMatrixWorld(); }); __publicField13(this, "pointerHover", (pointer) => { if (this.object === void 0 || this.dragging === true) return; this.raycaster.setFromCamera(pointer, this.camera); const intersect = this.intersectObjectWithRay(this.gizmo.picker[this.mode], this.raycaster); if (intersect) { this.axis = intersect.object.name; } else { this.axis = null; } }); __publicField13(this, "pointerDown", (pointer) => { if (this.object === void 0 || this.dragging === true || pointer.button !== 0) return; if (this.axis !== null) { this.raycaster.setFromCamera(pointer, this.camera); const planeIntersect = this.intersectObjectWithRay(this.plane, this.raycaster, true); if (planeIntersect) { let space = this.space; if (this.mode === "scale") { space = "local"; } else if (this.axis === "E" || this.axis === "XYZE" || this.axis === "XYZ") { space = "world"; } if (space === "local" && this.mode === "rotate") { const snap = this.rotationSnap; if (this.axis === "X" && snap) this.object.rotation.x = Math.round(this.object.rotation.x / snap) * snap; if (this.axis === "Y" && snap) this.object.rotation.y = Math.round(this.object.rotation.y / snap) * snap; if (this.axis === "Z" && snap) this.object.rotation.z = Math.round(this.object.rotation.z / snap) * snap; } this.object.updateMatrixWorld(); if (this.object.parent) { 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; this.mouseDownEvent.mode = this.mode; this.dispatchEvent(this.mouseDownEvent); } }); __publicField13(this, "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.button !== -1) return; this.raycaster.setFromCamera(pointer, this.camera); const planeIntersect = this.intersectObjectWithRay(this.plane, this.raycaster, 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(this.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(this.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(this.tempVector.setFromMatrixPosition(object.parent.matrixWorld)); } } } } else if (mode === "scale") { if (axis.search("XYZ") !== -1) { let d2 = this.pointEnd.length() / this.pointStart.length(); if (this.pointEnd.dot(this.pointStart) < 0) d2 *= -1; this.tempVector2.set(d2, d2, d2); } else { this.tempVector.copy(this.pointStart); this.tempVector2.copy(this.pointEnd); this.tempVector.applyQuaternion(this.worldQuaternionInv); this.tempVector2.applyQuaternion(this.worldQuaternionInv); this.tempVector2.divide(this.tempVector); if (axis.search("X") === -1) { this.tempVector2.x = 1; } if (axis.search("Y") === -1) { this.tempVector2.y = 1; } if (axis.search("Z") === -1) { this.tempVector2.z = 1; } } object.scale.copy(this.scaleStart).multiply(this.tempVector2); if (this.scaleSnap && this.object) { if (axis.search("X") !== -1) { this.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(this.tempVector.setFromMatrixPosition(this.camera.matrixWorld)); if (axis === "E") { 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; } else if (axis === "XYZE") { this.rotationAxis.copy(this.offset).cross(this.eye).normalize(); this.rotationAngle = this.offset.dot(this.tempVector.copy(this.rotationAxis).cross(this.eye)) * ROTATION_SPEED; } else if (axis === "X" || axis === "Y" || axis === "Z") { this.rotationAxis.copy(this.unit[axis]); this.tempVector.copy(this.unit[axis]); if (space === "local") { this.tempVector.applyQuaternion(this.worldQuaternion); } this.rotationAngle = this.offset.dot(this.tempVector.cross(this.eye).normalize()) * ROTATION_SPEED; } 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(this.tempQuaternion.setFromAxisAngle(this.rotationAxis, this.rotationAngle)).normalize(); } else { this.rotationAxis.applyQuaternion(this.parentQuaternionInv); object.quaternion.copy(this.tempQuaternion.setFromAxisAngle(this.rotationAxis, this.rotationAngle)); object.quaternion.multiply(this.quaternionStart).normalize(); } } this.dispatchEvent(this.changeEvent); this.dispatchEvent(this.objectChangeEvent); }); __publicField13(this, "pointerUp", (pointer) => { if (pointer.button !== 0) return; if (this.dragging && this.axis !== null) { this.mouseUpEvent.mode = this.mode; this.dispatchEvent(this.mouseUpEvent); } this.dragging = false; this.axis = null; }); __publicField13(this, "getPointer", (event) => { var _a3; if (this.domElement && ((_a3 = this.domElement.ownerDocument) == null ? void 0 : _a3.pointerLockElement)) { return { x: 0, y: 0, button: event.button }; } else { const pointer = event.changedTouches ? event.changedTouches[0] : event; const rect = this.domElement.getBoundingClientRect(); return { x: (pointer.clientX - rect.left) / rect.width * 2 - 1, y: -(pointer.clientY - rect.top) / rect.height * 2 + 1, button: event.button }; } }); __publicField13(this, "onPointerHover", (event) => { if (!this.enabled) return; switch (event.pointerType) { case "mouse": case "pen": this.pointerHover(this.getPointer(event)); break; } }); __publicField13(this, "onPointerDown", (event) => { if (!this.enabled || !this.domElement) return; this.domElement.style.touchAction = "none"; this.domElement.ownerDocument.addEventListener("pointermove", this.onPointerMove); this.pointerHover(this.getPointer(event)); this.pointerDown(this.getPointer(event)); }); __publicField13(this, "onPointerMove", (event) => { if (!this.enabled) return; this.pointerMove(this.getPointer(event)); }); __publicField13(this, "onPointerUp", (event) => { if (!this.enabled || !this.domElement) return; this.domElement.style.touchAction = ""; this.domElement.ownerDocument.removeEventListener("pointermove", this.onPointerMove); this.pointerUp(this.getPointer(event)); }); __publicField13(this, "getMode", () => this.mode); __publicField13(this, "setMode", (mode) => { this.mode = mode; }); __publicField13(this, "setTranslationSnap", (translationSnap) => { this.translationSnap = translationSnap; }); __publicField13(this, "setRotationSnap", (rotationSnap) => { this.rotationSnap = rotationSnap; }); __publicField13(this, "setScaleSnap", (scaleSnap) => { this.scaleSnap = scaleSnap; }); __publicField13(this, "setSize", (size2) => { this.size = size2; }); __publicField13(this, "setSpace", (space) => { this.space = space; }); __publicField13(this, "update", () => { console.warn( "THREE.TransformControls: update function has no more functionality and therefore has been deprecated." ); }); __publicField13(this, "connect", (domElement2) => { if (domElement2 === document) { console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' ); } this.domElement = domElement2; this.domElement.addEventListener("pointerdown", this.onPointerDown); this.domElement.addEventListener("pointermove", this.onPointerHover); this.domElement.ownerDocument.addEventListener("pointerup", this.onPointerUp); }); __publicField13(this, "dispose", () => { var _a3, _b3, _c, _d, _e, _f; (_a3 = this.domElement) == null ? void 0 : _a3.removeEventListener("pointerdown", this.onPointerDown); (_b3 = this.domElement) == null ? void 0 : _b3.removeEventListener("pointermove", this.onPointerHover); (_d = (_c = this.domElement) == null ? void 0 : _c.ownerDocument) == null ? void 0 : _d.removeEventListener("pointermove", this.onPointerMove); (_f = (_e = this.domElement) == null ? void 0 : _e.ownerDocument) == null ? void 0 : _f.removeEventListener("pointerup", this.onPointerUp); this.traverse((child) => { const mesh = child; if (mesh.geometry) { mesh.geometry.dispose(); } if (mesh.material) { mesh.material.dispose(); } }); }); this.domElement = domElement; this.camera = camera; this.gizmo = new TransformControlsGizmo(); this.add(this.gizmo); this.plane = new TransformControlsPlane(); this.add(this.plane); const defineProperty = (propName, defaultValue) => { let propValue = defaultValue; Object.defineProperty(this, propName, { get: function() { return propValue !== void 0 ? propValue : defaultValue; }, set: function(value) { if (propValue !== value) { propValue = value; this.plane[propName] = value; this.gizmo[propName] = value; this.dispatchEvent({ type: propName + "-changed", value }); this.dispatchEvent(this.changeEvent); } } }); this[propName] = defaultValue; this.plane[propName] = defaultValue; this.gizmo[propName] = defaultValue; }; defineProperty("camera", this.camera); defineProperty("object", this.object); defineProperty("enabled", this.enabled); defineProperty("axis", this.axis); defineProperty("mode", this.mode); defineProperty("translationSnap", this.translationSnap); defineProperty("rotationSnap", this.rotationSnap); defineProperty("scaleSnap", this.scaleSnap); defineProperty("space", this.space); defineProperty("size", this.size); defineProperty("dragging", this.dragging); defineProperty("showX", this.showX); defineProperty("showY", this.showY); defineProperty("showZ", this.showZ); defineProperty("worldPosition", this.worldPosition); defineProperty("worldPositionStart", this.worldPositionStart); defineProperty("worldQuaternion", this.worldQuaternion); defineProperty("worldQuaternionStart", this.worldQuaternionStart); defineProperty("cameraPosition", this.cameraPosition); defineProperty("cameraQuaternion", this.cameraQuaternion); defineProperty("pointStart", this.pointStart); defineProperty("pointEnd", this.pointEnd); defineProperty("rotationAxis", this.rotationAxis); defineProperty("rotationAngle", this.rotationAngle); defineProperty("eye", this.eye); if (domElement !== void 0) this.connect(domElement); } }; var TransformControlsGizmo = class extends Object3D { constructor() { super(); __publicField13(this, "isTransformControlsGizmo", true); __publicField13(this, "type", "TransformControlsGizmo"); __publicField13(this, "tempVector", new Vector3(0, 0, 0)); __publicField13(this, "tempEuler", new Euler()); __publicField13(this, "alignVector", new Vector3(0, 1, 0)); __publicField13(this, "zeroVector", new Vector3(0, 0, 0)); __publicField13(this, "lookAtMatrix", new Matrix4()); __publicField13(this, "tempQuaternion", new Quaternion()); __publicField13(this, "tempQuaternion2", new Quaternion()); __publicField13(this, "identityQuaternion", new Quaternion()); __publicField13(this, "unitX", new Vector3(1, 0, 0)); __publicField13(this, "unitY", new Vector3(0, 1, 0)); __publicField13(this, "unitZ", new Vector3(0, 0, 1)); __publicField13(this, "gizmo"); __publicField13(this, "picker"); __publicField13(this, "helper"); __publicField13(this, "rotationAxis", new Vector3()); __publicField13(this, "cameraPosition", new Vector3()); __publicField13(this, "worldPositionStart", new Vector3()); __publicField13(this, "worldQuaternionStart", new Quaternion()); __publicField13(this, "worldPosition", new Vector3()); __publicField13(this, "worldQuaternion", new Quaternion()); __publicField13(this, "eye", new Vector3()); __publicField13(this, "camera", null); __publicField13(this, "enabled", true); __publicField13(this, "axis", null); __publicField13(this, "mode", "translate"); __publicField13(this, "space", "world"); __publicField13(this, "size", 1); __publicField13(this, "dragging", false); __publicField13(this, "showX", true); __publicField13(this, "showY", true); __publicField13(this, "showZ", true); __publicField13(this, "updateMatrixWorld", () => { let space = this.space; if (this.mode === "scale") { space = "local"; } const quaternion = space === "local" ? this.worldQuaternion : this.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 i4 = 0; i4 < handles.length; i4++) { const handle = handles[i4]; 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 / 7); if (handle.tag === "helper") { handle.visible = false; if (handle.name === "AXIS") { handle.position.copy(this.worldPositionStart); handle.visible = !!this.axis; if (this.axis === "X") { this.tempQuaternion.setFromEuler(this.tempEuler.set(0, 0, 0)); handle.quaternion.copy(quaternion).multiply(this.tempQuaternion); if (Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { handle.visible = false; } } if (this.axis === "Y") { this.tempQuaternion.setFromEuler(this.tempEuler.set(0, 0, Math.PI / 2)); handle.quaternion.copy(quaternion).multiply(this.tempQuaternion); if (Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { handle.visible = false; } } if (this.axis === "Z") { this.tempQuaternion.setFromEuler(this.tempEuler.set(0, Math.PI / 2, 0)); handle.quaternion.copy(quaternion).multiply(this.tempQuaternion); if (Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { handle.visible = false; } } if (this.axis === "XYZE") { this.tempQuaternion.setFromEuler(this.tempEuler.set(0, Math.PI / 2, 0)); this.alignVector.copy(this.rotationAxis); handle.quaternion.setFromRotationMatrix( this.lookAtMatrix.lookAt(this.zeroVector, this.alignVector, this.unitY) ); handle.quaternion.multiply(this.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); this.tempVector.set(1e-10, 1e-10, 1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1); this.tempVector.applyQuaternion(this.worldQuaternionStart.clone().invert()); handle.scale.copy(this.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_TRESHOLD = 0.99; const PLANE_HIDE_TRESHOLD = 0.2; const AXIS_FLIP_TRESHOLD = 0; if (handle.name === "X" || handle.name === "XYZX") { if (Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "Y" || handle.name === "XYZY") { if (Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "Z" || handle.name === "XYZZ") { if (Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "XY") { if (Math.abs(this.alignVector.copy(this.unitZ).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "YZ") { if (Math.abs(this.alignVector.copy(this.unitX).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "XZ") { if (Math.abs(this.alignVector.copy(this.unitY).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_TRESHOLD) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name.search("X") !== -1) { if (this.alignVector.copy(this.unitX).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD) { if (handle.tag === "fwd") { handle.visible = false; } else { handle.scale.x *= -1; } } else if (handle.tag === "bwd") { handle.visible = false; } } if (handle.name.search("Y") !== -1) { if (this.alignVector.copy(this.unitY).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD) { if (handle.tag === "fwd") { handle.visible = false; } else { handle.scale.y *= -1; } } else if (handle.tag === "bwd") { handle.visible = false; } } if (handle.name.search("Z") !== -1) { if (this.alignVector.copy(this.unitZ).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD) { if (handle.tag === "fwd") { handle.visible = false; } else { handle.scale.z *= -1; } } else if (handle.tag === "bwd") { handle.visible = false; } } } else if (this.mode === "rotate") { this.tempQuaternion2.copy(quaternion); this.alignVector.copy(this.eye).applyQuaternion(this.tempQuaternion.copy(quaternion).invert()); if (handle.name.search("E") !== -1) { handle.quaternion.setFromRotationMatrix(this.lookAtMatrix.lookAt(this.eye, this.zeroVector, this.unitY)); } if (handle.name === "X") { this.tempQuaternion.setFromAxisAngle(this.unitX, Math.atan2(-this.alignVector.y, this.alignVector.z)); this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2, this.tempQuaternion); handle.quaternion.copy(this.tempQuaternion); } if (handle.name === "Y") { this.tempQuaternion.setFromAxisAngle(this.unitY, Math.atan2(this.alignVector.x, this.alignVector.z)); this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2, this.tempQuaternion); handle.quaternion.copy(this.tempQuaternion); } if (handle.name === "Z") { this.tempQuaternion.setFromAxisAngle(this.unitZ, Math.atan2(this.alignVector.y, this.alignVector.x)); this.tempQuaternion.multiplyQuaternions(this.tempQuaternion2, this.tempQuaternion); handle.quaternion.copy(this.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.tempOpacity = handle.material.tempOpacity || handle.material.opacity; handle.material.tempColor = handle.material.tempColor || handle.material.color.clone(); handle.material.color.copy(handle.material.tempColor); handle.material.opacity = handle.material.tempOpacity; if (!this.enabled) { handle.material.opacity *= 0.5; handle.material.color.lerp(new Color(1, 1, 1), 0.5); } else if (this.axis) { if (handle.name === this.axis) { handle.material.opacity = 1; handle.material.color.lerp(new Color(1, 1, 1), 0.5); } else if (this.axis.split("").some(function(a6) { return handle.name === a6; })) { handle.material.opacity = 1; handle.material.color.lerp(new Color(1, 1, 1), 0.5); } else { handle.material.opacity *= 0.25; handle.material.color.lerp(new Color(1, 1, 1), 0.5); } } } super.updateMatrixWorld(); }); const gizmoMaterial = new MeshBasicMaterial({ depthTest: false, depthWrite: false, transparent: true, side: DoubleSide, fog: false, toneMapped: false }); const gizmoLineMaterial = new LineBasicMaterial({ depthTest: false, depthWrite: false, transparent: true, linewidth: 1, fog: false, toneMapped: false }); const matInvisible = gizmoMaterial.clone(); matInvisible.opacity = 0.15; const matHelper = gizmoMaterial.clone(); matHelper.opacity = 0.33; const matRed = gizmoMaterial.clone(); matRed.color.set(16711680); const matGreen = gizmoMaterial.clone(); matGreen.color.set(65280); const matBlue = gizmoMaterial.clone(); matBlue.color.set(255); const matWhiteTransparent = gizmoMaterial.clone(); matWhiteTransparent.opacity = 0.25; const matYellowTransparent = matWhiteTransparent.clone(); matYellowTransparent.color.set(16776960); const matCyanTransparent = matWhiteTransparent.clone(); matCyanTransparent.color.set(65535); const matMagentaTransparent = matWhiteTransparent.clone(); matMagentaTransparent.color.set(16711935); const matYellow = gizmoMaterial.clone(); matYellow.color.set(16776960); const matLineRed = gizmoLineMaterial.clone(); matLineRed.color.set(16711680); const matLineGreen = gizmoLineMaterial.clone(); matLineGreen.color.set(65280); const matLineBlue = gizmoLineMaterial.clone(); matLineBlue.color.set(255); const matLineCyan = gizmoLineMaterial.clone(); matLineCyan.color.set(65535); const matLineMagenta = gizmoLineMaterial.clone(); matLineMagenta.color.set(16711935); const matLineYellow = gizmoLineMaterial.clone(); matLineYellow.color.set(16776960); const matLineGray = gizmoLineMaterial.clone(); matLineGray.color.set(7895160); const matLineYellowTransparent = matLineYellow.clone(); matLineYellowTransparent.opacity = 0.25; const arrowGeometry = new CylinderGeometry(0, 0.05, 0.2, 12, 1, false); const scaleHandleGeometry = new BoxGeometry(0.125, 0.125, 0.125); const lineGeometry = new BufferGeometry(); lineGeometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 1, 0, 0], 3)); const CircleGeometry = (radius, arc) => { const geometry3 = new BufferGeometry(); const vertices = []; for (let i4 = 0; i4 <= 64 * arc; ++i4) { vertices.push(0, Math.cos(i4 / 32 * Math.PI) * radius, Math.sin(i4 / 32 * Math.PI) * radius); } geometry3.setAttribute("position", new Float32BufferAttribute(vertices, 3)); return geometry3; }; const TranslateHelperGeometry = () => { const geometry3 = new BufferGeometry(); geometry3.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 1, 1, 1], 3)); return geometry3; }; const gizmoTranslate = { X: [ [new Mesh(arrowGeometry, matRed), [1, 0, 0], [0, 0, -Math.PI / 2], null, "fwd"], [new Mesh(arrowGeometry, matRed), [1, 0, 0], [0, 0, Math.PI / 2], null, "bwd"], [new Line(lineGeometry, matLineRed)] ], Y: [ [new Mesh(arrowGeometry, matGreen), [0, 1, 0], null, null, "fwd"], [new Mesh(arrowGeometry, matGreen), [0, 1, 0], [Math.PI, 0, 0], null, "bwd"], [new Line(lineGeometry, matLineGreen), null, [0, 0, Math.PI / 2]] ], Z: [ [new Mesh(arrowGeometry, matBlue), [0, 0, 1], [Math.PI / 2, 0, 0], null, "fwd"], [new Mesh(arrowGeometry, matBlue), [0, 0, 1], [-Math.PI / 2, 0, 0], null, "bwd"], [new Line(lineGeometry, matLineBlue), null, [0, -Math.PI / 2, 0]] ], XYZ: [[new Mesh(new OctahedronGeometry(0.1, 0), matWhiteTransparent.clone()), [0, 0, 0], [0, 0, 0]]], XY: [ [new Mesh(new PlaneGeometry(0.295, 0.295), matYellowTransparent.clone()), [0.15, 0.15, 0]], [new Line(lineGeometry, matLineYellow), [0.18, 0.3, 0], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineYellow), [0.3, 0.18, 0], [0, 0, Math.PI / 2], [0.125, 1, 1]] ], YZ: [ [new Mesh(new PlaneGeometry(0.295, 0.295), matCyanTransparent.clone()), [0, 0.15, 0.15], [0, Math.PI / 2, 0]], [new Line(lineGeometry, matLineCyan), [0, 0.18, 0.3], [0, 0, Math.PI / 2], [0.125, 1, 1]], [new Line(lineGeometry, matLineCyan), [0, 0.3, 0.18], [0, -Math.PI / 2, 0], [0.125, 1, 1]] ], XZ: [ [ new Mesh(new PlaneGeometry(0.295, 0.295), matMagentaTransparent.clone()), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0] ], [new Line(lineGeometry, matLineMagenta), [0.18, 0, 0.3], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineMagenta), [0.3, 0, 0.18], [0, -Math.PI / 2, 0], [0.125, 1, 1]] ] }; const pickerTranslate = { X: [[new Mesh(new CylinderGeometry(0.2, 0, 1, 4, 1, false), matInvisible), [0.6, 0, 0], [0, 0, -Math.PI / 2]]], Y: [[new Mesh(new CylinderGeometry(0.2, 0, 1, 4, 1, false), matInvisible), [0, 0.6, 0]]], Z: [[new Mesh(new CylinderGeometry(0.2, 0, 1, 4, 1, false), matInvisible), [0, 0, 0.6], [Math.PI / 2, 0, 0]]], XYZ: [[new Mesh(new OctahedronGeometry(0.2, 0), matInvisible)]], XY: [[new Mesh(new PlaneGeometry(0.4, 0.4), matInvisible), [0.2, 0.2, 0]]], YZ: [[new Mesh(new PlaneGeometry(0.4, 0.4), matInvisible), [0, 0.2, 0.2], [0, Math.PI / 2, 0]]], XZ: [[new Mesh(new PlaneGeometry(0.4, 0.4), matInvisible), [0.2, 0, 0.2], [-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.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], "helper"]], Y: [[new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], "helper"]], Z: [[new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], "helper"]] }; const gizmoRotate = { X: [ [new Line(CircleGeometry(1, 0.5), matLineRed)], [new Mesh(new OctahedronGeometry(0.04, 0), matRed), [0, 0, 0.99], null, [1, 3, 1]] ], Y: [ [new Line(CircleGeometry(1, 0.5), matLineGreen), null, [0, 0, -Math.PI / 2]], [new Mesh(new OctahedronGeometry(0.04, 0), matGreen), [0, 0, 0.99], null, [3, 1, 1]] ], Z: [ [new Line(CircleGeometry(1, 0.5), matLineBlue), null, [0, Math.PI / 2, 0]], [new Mesh(new OctahedronGeometry(0.04, 0), matBlue), [0.99, 0, 0], null, [1, 3, 1]] ], E: [ [new Line(CircleGeometry(1.25, 1), matLineYellowTransparent), null, [0, Math.PI / 2, 0]], [ new Mesh(new CylinderGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [1.17, 0, 0], [0, 0, -Math.PI / 2], [1, 1, 1e-3] ], [ new Mesh(new CylinderGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [-1.17, 0, 0], [0, 0, Math.PI / 2], [1, 1, 1e-3] ], [ new Mesh(new CylinderGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [0, -1.17, 0], [Math.PI, 0, 0], [1, 1, 1e-3] ], [ new Mesh(new CylinderGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [0, 1.17, 0], [0, 0, 0], [1, 1, 1e-3] ] ], XYZE: [[new Line(CircleGeometry(1, 1), matLineGray), null, [0, Math.PI / 2, 0]]] }; const helperRotate = { AXIS: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], "helper"]] }; const pickerRotate = { X: [[new Mesh(new TorusGeometry(1, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, -Math.PI / 2, -Math.PI / 2]]], Y: [[new Mesh(new TorusGeometry(1, 0.1, 4, 24), matInvisible), [0, 0, 0], [Math.PI / 2, 0, 0]]], Z: [[new Mesh(new TorusGeometry(1, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, 0, -Math.PI / 2]]], E: [[new Mesh(new TorusGeometry(1.25, 0.1, 2, 24), matInvisible)]], XYZE: [[new Mesh(new SphereGeometry(0.7, 10, 8), matInvisible)]] }; const gizmoScale = { X: [ [new Mesh(scaleHandleGeometry, matRed), [0.8, 0, 0], [0, 0, -Math.PI / 2]], [new Line(lineGeometry, matLineRed), null, null, [0.8, 1, 1]] ], Y: [ [new Mesh(scaleHandleGeometry, matGreen), [0, 0.8, 0]], [new Line(lineGeometry, matLineGreen), null, [0, 0, Math.PI / 2], [0.8, 1, 1]] ], Z: [ [new Mesh(scaleHandleGeometry, matBlue), [0, 0, 0.8], [Math.PI / 2, 0, 0]], [new Line(lineGeometry, matLineBlue), null, [0, -Math.PI / 2, 0], [0.8, 1, 1]] ], XY: [ [new Mesh(scaleHandleGeometry, matYellowTransparent), [0.85, 0.85, 0], null, [2, 2, 0.2]], [new Line(lineGeometry, matLineYellow), [0.855, 0.98, 0], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineYellow), [0.98, 0.855, 0], [0, 0, Math.PI / 2], [0.125, 1, 1]] ], YZ: [ [new Mesh(scaleHandleGeometry, matCyanTransparent), [0, 0.85, 0.85], null, [0.2, 2, 2]], [new Line(lineGeometry, matLineCyan), [0, 0.855, 0.98], [0, 0, Math.PI / 2], [0.125, 1, 1]], [new Line(lineGeometry, matLineCyan), [0, 0.98, 0.855], [0, -Math.PI / 2, 0], [0.125, 1, 1]] ], XZ: [ [new Mesh(scaleHandleGeometry, matMagentaTransparent), [0.85, 0, 0.85], null, [2, 0.2, 2]], [new Line(lineGeometry, matLineMagenta), [0.855, 0, 0.98], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineMagenta), [0.98, 0, 0.855], [0, -Math.PI / 2, 0], [0.125, 1, 1]] ], XYZX: [[new Mesh(new BoxGeometry(0.125, 0.125, 0.125), matWhiteTransparent.clone()), [1.1, 0, 0]]], XYZY: [[new Mesh(new BoxGeometry(0.125, 0.125, 0.125), matWhiteTransparent.clone()), [0, 1.1, 0]]], XYZZ: [[new Mesh(new BoxGeometry(0.125, 0.125, 0.125), matWhiteTransparent.clone()), [0, 0, 1.1]]] }; const pickerScale = { X: [[new Mesh(new CylinderGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible), [0.5, 0, 0], [0, 0, -Math.PI / 2]]], Y: [[new Mesh(new CylinderGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible), [0, 0.5, 0]]], Z: [[new Mesh(new CylinderGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible), [0, 0, 0.5], [Math.PI / 2, 0, 0]]], XY: [[new Mesh(scaleHandleGeometry, matInvisible), [0.85, 0.85, 0], null, [3, 3, 0.2]]], YZ: [[new Mesh(scaleHandleGeometry, matInvisible), [0, 0.85, 0.85], null, [0.2, 3, 3]]], XZ: [[new Mesh(scaleHandleGeometry, matInvisible), [0.85, 0, 0.85], null, [3, 0.2, 3]]], XYZX: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.2), matInvisible), [1.1, 0, 0]]], XYZY: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.2), matInvisible), [0, 1.1, 0]]], XYZZ: [[new Mesh(new BoxGeometry(0.2, 0.2, 0.2), matInvisible), [0, 0, 1.1]]] }; const helperScale = { X: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], "helper"]], Y: [[new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], "helper"]], Z: [[new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], "helper"]] }; const setupGizmo = (gizmoMap) => { const gizmo = new Object3D(); for (let name in gizmoMap) { for (let i4 = gizmoMap[name].length; i4--; ) { const object = gizmoMap[name][i4][0].clone(); const position2 = gizmoMap[name][i4][1]; const rotation3 = gizmoMap[name][i4][2]; const scale5 = gizmoMap[name][i4][3]; const tag = gizmoMap[name][i4][4]; object.name = name; object.tag = tag; if (position2) { object.position.set(position2[0], position2[1], position2[2]); } if (rotation3) { object.rotation.set(rotation3[0], rotation3[1], rotation3[2]); } if (scale5) { object.scale.set(scale5[0], scale5[1], scale5[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; } }; 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 }) ); __publicField13(this, "isTransformControlsPlane", true); __publicField13(this, "type", "TransformControlsPlane"); __publicField13(this, "unitX", new Vector3(1, 0, 0)); __publicField13(this, "unitY", new Vector3(0, 1, 0)); __publicField13(this, "unitZ", new Vector3(0, 0, 1)); __publicField13(this, "tempVector", new Vector3()); __publicField13(this, "dirVector", new Vector3()); __publicField13(this, "alignVector", new Vector3()); __publicField13(this, "tempMatrix", new Matrix4()); __publicField13(this, "identityQuaternion", new Quaternion()); __publicField13(this, "cameraQuaternion", new Quaternion()); __publicField13(this, "worldPosition", new Vector3()); __publicField13(this, "worldQuaternion", new Quaternion()); __publicField13(this, "eye", new Vector3()); __publicField13(this, "axis", null); __publicField13(this, "mode", "translate"); __publicField13(this, "space", "world"); __publicField13(this, "updateMatrixWorld", () => { let space = this.space; this.position.copy(this.worldPosition); if (this.mode === "scale") space = "local"; this.unitX.set(1, 0, 0).applyQuaternion(space === "local" ? this.worldQuaternion : this.identityQuaternion); this.unitY.set(0, 1, 0).applyQuaternion(space === "local" ? this.worldQuaternion : this.identityQuaternion); this.unitZ.set(0, 0, 1).applyQuaternion(space === "local" ? this.worldQuaternion : this.identityQuaternion); this.alignVector.copy(this.unitY); switch (this.mode) { case "translate": case "scale": switch (this.axis) { case "X": this.alignVector.copy(this.eye).cross(this.unitX); this.dirVector.copy(this.unitX).cross(this.alignVector); break; case "Y": this.alignVector.copy(this.eye).cross(this.unitY); this.dirVector.copy(this.unitY).cross(this.alignVector); break; case "Z": this.alignVector.copy(this.eye).cross(this.unitZ); this.dirVector.copy(this.unitZ).cross(this.alignVector); break; case "XY": this.dirVector.copy(this.unitZ); break; case "YZ": this.dirVector.copy(this.unitX); break; case "XZ": this.alignVector.copy(this.unitZ); this.dirVector.copy(this.unitY); break; case "XYZ": case "E": this.dirVector.set(0, 0, 0); break; } break; case "rotate": default: this.dirVector.set(0, 0, 0); } if (this.dirVector.length() === 0) { this.quaternion.copy(this.cameraQuaternion); } else { this.tempMatrix.lookAt(this.tempVector.set(0, 0, 0), this.dirVector, this.alignVector); this.quaternion.setFromRotationMatrix(this.tempMatrix); } super.updateMatrixWorld(); }); } }; // node_modules/three-stdlib/controls/PointerLockControls.js var __defProp14 = Object.defineProperty; var __defNormalProp14 = (obj, key, value) => key in obj ? __defProp14(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField14 = (obj, key, value) => { __defNormalProp14(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var _euler = new Euler(0, 0, 0, "YXZ"); var _vector3 = new Vector3(); var _changeEvent = { 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 EventDispatcher2 { constructor(camera, domElement) { super(); __publicField14(this, "camera"); __publicField14(this, "domElement"); __publicField14(this, "isLocked"); __publicField14(this, "minPolarAngle"); __publicField14(this, "maxPolarAngle"); __publicField14(this, "pointerSpeed"); __publicField14(this, "onMouseMove", (event) => { if (!this.domElement || this.isLocked === false) return; _euler.setFromQuaternion(this.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)); this.camera.quaternion.setFromEuler(_euler); this.dispatchEvent(_changeEvent); }); __publicField14(this, "onPointerlockChange", () => { if (!this.domElement) return; if (this.domElement.ownerDocument.pointerLockElement === this.domElement) { this.dispatchEvent(_lockEvent); this.isLocked = true; } else { this.dispatchEvent(_unlockEvent); this.isLocked = false; } }); __publicField14(this, "onPointerlockError", () => { console.error("THREE.PointerLockControls: Unable to use Pointer Lock API"); }); __publicField14(this, "connect", (domElement2) => { this.domElement = domElement2 || this.domElement; if (!this.domElement) return; this.domElement.ownerDocument.addEventListener("mousemove", this.onMouseMove); this.domElement.ownerDocument.addEventListener("pointerlockchange", this.onPointerlockChange); this.domElement.ownerDocument.addEventListener("pointerlockerror", this.onPointerlockError); }); __publicField14(this, "disconnect", () => { if (!this.domElement) return; this.domElement.ownerDocument.removeEventListener("mousemove", this.onMouseMove); this.domElement.ownerDocument.removeEventListener("pointerlockchange", this.onPointerlockChange); this.domElement.ownerDocument.removeEventListener("pointerlockerror", this.onPointerlockError); }); __publicField14(this, "dispose", () => { this.disconnect(); }); __publicField14(this, "getObject", () => { return this.camera; }); __publicField14(this, "direction", new Vector3(0, 0, -1)); __publicField14(this, "getDirection", (v5) => { return v5.copy(this.direction).applyQuaternion(this.camera.quaternion); }); __publicField14(this, "moveForward", (distance3) => { _vector3.setFromMatrixColumn(this.camera.matrix, 0); _vector3.crossVectors(this.camera.up, _vector3); this.camera.position.addScaledVector(_vector3, distance3); }); __publicField14(this, "moveRight", (distance3) => { _vector3.setFromMatrixColumn(this.camera.matrix, 0); this.camera.position.addScaledVector(_vector3, distance3); }); __publicField14(this, "lock", () => { if (this.domElement) this.domElement.requestPointerLock(); }); __publicField14(this, "unlock", () => { if (this.domElement) this.domElement.ownerDocument.exitPointerLock(); }); this.camera = camera; this.domElement = domElement; this.isLocked = false; this.minPolarAngle = 0; this.maxPolarAngle = Math.PI; this.pointerSpeed = 1; if (domElement) this.connect(domElement); } }; // node_modules/three-stdlib/controls/DeviceOrientationControls.js var __defProp15 = Object.defineProperty; var __defNormalProp15 = (obj, key, value) => key in obj ? __defProp15(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField15 = (obj, key, value) => { __defNormalProp15(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var DeviceOrientationControls = class extends EventDispatcher2 { // radians constructor(object) { super(); __publicField15(this, "object"); __publicField15(this, "changeEvent", { type: "change" }); __publicField15(this, "EPS", 1e-6); __publicField15(this, "enabled", true); __publicField15(this, "deviceOrientation", { alpha: 0, beta: 0, gamma: 0 }); __publicField15(this, "screenOrientation", 0); __publicField15(this, "alphaOffset", 0); __publicField15(this, "onDeviceOrientationChangeEvent", (event) => { this.deviceOrientation = event; }); __publicField15(this, "onScreenOrientationChangeEvent", () => { this.screenOrientation = window.orientation || 0; }); __publicField15(this, "zee", new Vector3(0, 0, 1)); __publicField15(this, "euler", new Euler()); __publicField15(this, "q0", new Quaternion()); __publicField15(this, "q1", new Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5))); __publicField15(this, "setObjectQuaternion", (quaternion, alpha, beta, gamma, orient) => { this.euler.set(beta, alpha, -gamma, "YXZ"); quaternion.setFromEuler(this.euler); quaternion.multiply(this.q1); quaternion.multiply(this.q0.setFromAxisAngle(this.zee, -orient)); }); __publicField15(this, "connect", () => { this.onScreenOrientationChangeEvent(); if (window.DeviceOrientationEvent !== void 0 && // @ts-ignore typeof window.DeviceOrientationEvent.requestPermission === "function") { window.DeviceOrientationEvent.requestPermission().then((response) => { if (response == "granted") { window.addEventListener("orientationchange", this.onScreenOrientationChangeEvent); window.addEventListener("deviceorientation", this.onDeviceOrientationChangeEvent); } }).catch((error) => { console.error("THREE.DeviceOrientationControls: Unable to use DeviceOrientation API:", error); }); } else { window.addEventListener("orientationchange", this.onScreenOrientationChangeEvent); window.addEventListener("deviceorientation", this.onDeviceOrientationChangeEvent); } this.enabled = true; }); __publicField15(this, "disconnect", () => { window.removeEventListener("orientationchange", this.onScreenOrientationChangeEvent); window.removeEventListener("deviceorientation", this.onDeviceOrientationChangeEvent); this.enabled = false; }); __publicField15(this, "lastQuaternion", new Quaternion()); __publicField15(this, "update", () => { if (this.enabled === false) return; const device = this.deviceOrientation; if (device) { const alpha = device.alpha ? MathUtils.degToRad(device.alpha) + this.alphaOffset : 0; const beta = device.beta ? MathUtils.degToRad(device.beta) : 0; const gamma = device.gamma ? MathUtils.degToRad(device.gamma) : 0; const orient = this.screenOrientation ? MathUtils.degToRad(this.screenOrientation) : 0; this.setObjectQuaternion(this.object.quaternion, alpha, beta, gamma, orient); if (8 * (1 - this.lastQuaternion.dot(this.object.quaternion)) > this.EPS) { this.lastQuaternion.copy(this.object.quaternion); this.dispatchEvent(this.changeEvent); } } }); __publicField15(this, "dispose", () => this.disconnect()); this.object = object; this.object.rotation.reorder("YXZ"); this.connect(); } }; // node_modules/three-stdlib/controls/TrackballControls.js var __defProp16 = Object.defineProperty; var __defNormalProp16 = (obj, key, value) => key in obj ? __defProp16(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField16 = (obj, key, value) => { __defNormalProp16(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var TrackballControls = class extends EventDispatcher2 { constructor(object, domElement) { super(); __publicField16(this, "enabled", true); __publicField16(this, "screen", { left: 0, top: 0, width: 0, height: 0 }); __publicField16(this, "rotateSpeed", 1); __publicField16(this, "zoomSpeed", 1.2); __publicField16(this, "panSpeed", 0.3); __publicField16(this, "noRotate", false); __publicField16(this, "noZoom", false); __publicField16(this, "noPan", false); __publicField16(this, "staticMoving", false); __publicField16(this, "dynamicDampingFactor", 0.2); __publicField16(this, "minDistance", 0); __publicField16(this, "maxDistance", Infinity); __publicField16(this, "keys", [ "KeyA", "KeyS", "KeyD" /*D*/ ]); __publicField16(this, "mouseButtons", { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }); __publicField16(this, "object"); __publicField16(this, "domElement"); __publicField16(this, "cursorZoom", false); __publicField16(this, "target", new Vector3()); __publicField16(this, "mousePosition", new Vector2()); __publicField16(this, "STATE", { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 }); __publicField16(this, "EPS", 1e-6); __publicField16(this, "lastZoom", 1); __publicField16(this, "lastPosition", new Vector3()); __publicField16(this, "cursorVector", new Vector3()); __publicField16(this, "targetVector", new Vector3()); __publicField16(this, "_state", this.STATE.NONE); __publicField16(this, "_keyState", this.STATE.NONE); __publicField16(this, "_eye", new Vector3()); __publicField16(this, "_movePrev", new Vector2()); __publicField16(this, "_moveCurr", new Vector2()); __publicField16(this, "_lastAxis", new Vector3()); __publicField16(this, "_lastAngle", 0); __publicField16(this, "_zoomStart", new Vector2()); __publicField16(this, "_zoomEnd", new Vector2()); __publicField16(this, "_touchZoomDistanceStart", 0); __publicField16(this, "_touchZoomDistanceEnd", 0); __publicField16(this, "_panStart", new Vector2()); __publicField16(this, "_panEnd", new Vector2()); __publicField16(this, "target0"); __publicField16(this, "position0"); __publicField16(this, "up0"); __publicField16(this, "zoom0"); __publicField16(this, "changeEvent", { type: "change" }); __publicField16(this, "startEvent", { type: "start" }); __publicField16(this, "endEvent", { type: "end" }); __publicField16(this, "onScreenVector", new Vector2()); __publicField16(this, "getMouseOnScreen", (pageX, pageY) => { this.onScreenVector.set( (pageX - this.screen.left) / this.screen.width, (pageY - this.screen.top) / this.screen.height ); return this.onScreenVector; }); __publicField16(this, "onCircleVector", new Vector2()); __publicField16(this, "getMouseOnCircle", (pageX, pageY) => { this.onCircleVector.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 this.onCircleVector; }); __publicField16(this, "axis", new Vector3()); __publicField16(this, "quaternion", new Quaternion()); __publicField16(this, "eyeDirection", new Vector3()); __publicField16(this, "objectUpDirection", new Vector3()); __publicField16(this, "objectSidewaysDirection", new Vector3()); __publicField16(this, "moveDirection", new Vector3()); __publicField16(this, "angle", 0); __publicField16(this, "rotateCamera", () => { this.moveDirection.set(this._moveCurr.x - this._movePrev.x, this._moveCurr.y - this._movePrev.y, 0); this.angle = this.moveDirection.length(); if (this.angle) { this._eye.copy(this.object.position).sub(this.target); this.eyeDirection.copy(this._eye).normalize(); this.objectUpDirection.copy(this.object.up).normalize(); this.objectSidewaysDirection.crossVectors(this.objectUpDirection, this.eyeDirection).normalize(); this.objectUpDirection.setLength(this._moveCurr.y - this._movePrev.y); this.objectSidewaysDirection.setLength(this._moveCurr.x - this._movePrev.x); this.moveDirection.copy(this.objectUpDirection.add(this.objectSidewaysDirection)); this.axis.crossVectors(this.moveDirection, this._eye).normalize(); this.angle *= this.rotateSpeed; this.quaternion.setFromAxisAngle(this.axis, this.angle); this._eye.applyQuaternion(this.quaternion); this.object.up.applyQuaternion(this.quaternion); this._lastAxis.copy(this.axis); this._lastAngle = this.angle; } else if (!this.staticMoving && this._lastAngle) { this._lastAngle *= Math.sqrt(1 - this.dynamicDampingFactor); this._eye.copy(this.object.position).sub(this.target); this.quaternion.setFromAxisAngle(this._lastAxis, this._lastAngle); this._eye.applyQuaternion(this.quaternion); this.object.up.applyQuaternion(this.quaternion); } this._movePrev.copy(this._moveCurr); }); __publicField16(this, "zoomCamera", () => { let factor; if (this._state === this.STATE.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 /= factor; this.object.updateProjectionMatrix(); } else { console.warn("THREE.TrackballControls: Unsupported camera type"); } } else { factor = 1 + (this._zoomEnd.y - this._zoomStart.y) * this.zoomSpeed; if (Math.abs(factor - 1) > this.EPS && factor > 0) { if (this.object.isPerspectiveCamera) { if (factor > 1 && this._eye.length() >= this.maxDistance - this.EPS) { factor = 1; } this._eye.multiplyScalar(factor); } else if (this.object.isOrthographicCamera) { if (factor > 1 && this.object.zoom < this.maxDistance * this.maxDistance) { factor = 1; } this.object.zoom /= factor; } 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; } if (this.cursorZoom) { this.targetVector.copy(this.target).project(this.object); let worldPos2 = this.cursorVector.set(this.mousePosition.x, this.mousePosition.y, this.targetVector.z).unproject(this.object); this.target.lerpVectors(worldPos2, this.target, factor); } if (this.object.isOrthographicCamera) { this.object.updateProjectionMatrix(); } } }); __publicField16(this, "mouseChange", new Vector2()); __publicField16(this, "objectUp", new Vector3()); __publicField16(this, "pan", new Vector3()); __publicField16(this, "panCamera", () => { if (!this.domElement) return; this.mouseChange.copy(this._panEnd).sub(this._panStart); if (this.mouseChange.lengthSq() > this.EPS) { if (this.object.isOrthographicCamera) { const orthoObject = this.object; const scale_x = (orthoObject.right - orthoObject.left) / this.object.zoom; const scale_y = (orthoObject.top - orthoObject.bottom) / this.object.zoom; this.mouseChange.x *= scale_x; this.mouseChange.y *= scale_y; } else { this.mouseChange.multiplyScalar(this._eye.length() * this.panSpeed); } this.pan.copy(this._eye).cross(this.object.up).setLength(this.mouseChange.x); this.pan.add(this.objectUp.copy(this.object.up).setLength(this.mouseChange.y)); this.object.position.add(this.pan); this.target.add(this.pan); if (this.staticMoving) { this._panStart.copy(this._panEnd); } else { this._panStart.add( this.mouseChange.subVectors(this._panEnd, this._panStart).multiplyScalar(this.dynamicDampingFactor) ); } } }); __publicField16(this, "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); } } }); __publicField16(this, "handleResize", () => { if (!this.domElement) return; const box = this.domElement.getBoundingClientRect(); const d2 = this.domElement.ownerDocument.documentElement; this.screen.left = box.left + window.pageXOffset - d2.clientLeft; this.screen.top = box.top + window.pageYOffset - d2.clientTop; this.screen.width = box.width; this.screen.height = box.height; }); __publicField16(this, "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) > this.EPS) { this.dispatchEvent(this.changeEvent); this.lastPosition.copy(this.object.position); } } else if (this.object.isOrthographicCamera) { this.object.lookAt(this.target); if (this.lastPosition.distanceToSquared(this.object.position) > this.EPS || this.lastZoom !== this.object.zoom) { this.dispatchEvent(this.changeEvent); this.lastPosition.copy(this.object.position); this.lastZoom = this.object.zoom; } } else { console.warn("THREE.TrackballControls: Unsupported camera type"); } }); __publicField16(this, "reset", () => { this._state = this.STATE.NONE; this._keyState = this.STATE.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(this.changeEvent); this.lastPosition.copy(this.object.position); this.lastZoom = this.object.zoom; }); __publicField16(this, "keydown", (event) => { if (this.enabled === false) return; window.removeEventListener("keydown", this.keydown); if (this._keyState !== this.STATE.NONE) { return; } else if (event.code === this.keys[this.STATE.ROTATE] && !this.noRotate) { this._keyState = this.STATE.ROTATE; } else if (event.code === this.keys[this.STATE.ZOOM] && !this.noZoom) { this._keyState = this.STATE.ZOOM; } else if (event.code === this.keys[this.STATE.PAN] && !this.noPan) { this._keyState = this.STATE.PAN; } }); __publicField16(this, "onPointerDown", (event) => { if (this.enabled === false) return; switch (event.pointerType) { case "mouse": case "pen": this.onMouseDown(event); break; } }); __publicField16(this, "onPointerMove", (event) => { if (this.enabled === false) return; switch (event.pointerType) { case "mouse": case "pen": this.onMouseMove(event); break; } }); __publicField16(this, "onPointerUp", (event) => { if (this.enabled === false) return; switch (event.pointerType) { case "mouse": case "pen": this.onMouseUp(); break; } }); __publicField16(this, "keyup", () => { if (this.enabled === false) return; this._keyState = this.STATE.NONE; window.addEventListener("keydown", this.keydown); }); __publicField16(this, "onMouseDown", (event) => { if (!this.domElement) return; if (this._state === this.STATE.NONE) { switch (event.button) { case this.mouseButtons.LEFT: this._state = this.STATE.ROTATE; break; case this.mouseButtons.MIDDLE: this._state = this.STATE.ZOOM; break; case this.mouseButtons.RIGHT: this._state = this.STATE.PAN; break; } } const state = this._keyState !== this.STATE.NONE ? this._keyState : this._state; if (state === this.STATE.ROTATE && !this.noRotate) { this._moveCurr.copy(this.getMouseOnCircle(event.pageX, event.pageY)); this._movePrev.copy(this._moveCurr); } else if (state === this.STATE.ZOOM && !this.noZoom) { this._zoomStart.copy(this.getMouseOnScreen(event.pageX, event.pageY)); this._zoomEnd.copy(this._zoomStart); } else if (state === this.STATE.PAN && !this.noPan) { this._panStart.copy(this.getMouseOnScreen(event.pageX, event.pageY)); this._panEnd.copy(this._panStart); } this.domElement.ownerDocument.addEventListener("pointermove", this.onPointerMove); this.domElement.ownerDocument.addEventListener("pointerup", this.onPointerUp); this.dispatchEvent(this.startEvent); }); __publicField16(this, "onMouseMove", (event) => { if (this.enabled === false) return; const state = this._keyState !== this.STATE.NONE ? this._keyState : this._state; if (state === this.STATE.ROTATE && !this.noRotate) { this._movePrev.copy(this._moveCurr); this._moveCurr.copy(this.getMouseOnCircle(event.pageX, event.pageY)); } else if (state === this.STATE.ZOOM && !this.noZoom) { this._zoomEnd.copy(this.getMouseOnScreen(event.pageX, event.pageY)); } else if (state === this.STATE.PAN && !this.noPan) { this._panEnd.copy(this.getMouseOnScreen(event.pageX, event.pageY)); } }); __publicField16(this, "onMouseUp", () => { if (!this.domElement) return; if (this.enabled === false) return; this._state = this.STATE.NONE; this.domElement.ownerDocument.removeEventListener("pointermove", this.onPointerMove); this.domElement.ownerDocument.removeEventListener("pointerup", this.onPointerUp); this.dispatchEvent(this.endEvent); }); __publicField16(this, "mousewheel", (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.mousePosition.x = event.offsetX / this.screen.width * 2 - 1; this.mousePosition.y = -(event.offsetY / this.screen.height) * 2 + 1; this.dispatchEvent(this.startEvent); this.dispatchEvent(this.endEvent); }); __publicField16(this, "touchstart", (event) => { if (this.enabled === false) return; event.preventDefault(); switch (event.touches.length) { case 1: this._state = this.STATE.TOUCH_ROTATE; this._moveCurr.copy(this.getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY)); this._movePrev.copy(this._moveCurr); break; default: this._state = this.STATE.TOUCH_ZOOM_PAN; const dx = event.touches[0].pageX - event.touches[1].pageX; const dy = event.touches[0].pageY - event.touches[1].pageY; this._touchZoomDistanceEnd = this._touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy); const x = (event.touches[0].pageX + event.touches[1].pageX) / 2; const y = (event.touches[0].pageY + event.touches[1].pageY) / 2; this._panStart.copy(this.getMouseOnScreen(x, y)); this._panEnd.copy(this._panStart); break; } this.dispatchEvent(this.startEvent); }); __publicField16(this, "touchmove", (event) => { if (this.enabled === false) return; event.preventDefault(); switch (event.touches.length) { case 1: this._movePrev.copy(this._moveCurr); this._moveCurr.copy(this.getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY)); break; default: const dx = event.touches[0].pageX - event.touches[1].pageX; const dy = event.touches[0].pageY - event.touches[1].pageY; this._touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy); const x = (event.touches[0].pageX + event.touches[1].pageX) / 2; const y = (event.touches[0].pageY + event.touches[1].pageY) / 2; this._panEnd.copy(this.getMouseOnScreen(x, y)); break; } }); __publicField16(this, "touchend", (event) => { if (this.enabled === false) return; switch (event.touches.length) { case 0: this._state = this.STATE.NONE; break; case 1: this._state = this.STATE.TOUCH_ROTATE; this._moveCurr.copy(this.getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY)); this._movePrev.copy(this._moveCurr); break; } this.dispatchEvent(this.endEvent); }); __publicField16(this, "contextmenu", (event) => { if (this.enabled === false) return; event.preventDefault(); }); __publicField16(this, "connect", (domElement2) => { if (domElement2 === document) { console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' ); } this.domElement = domElement2; this.domElement.addEventListener("contextmenu", this.contextmenu); this.domElement.addEventListener("pointerdown", this.onPointerDown); this.domElement.addEventListener("wheel", this.mousewheel); this.domElement.addEventListener("touchstart", this.touchstart); this.domElement.addEventListener("touchend", this.touchend); this.domElement.addEventListener("touchmove", this.touchmove); this.domElement.ownerDocument.addEventListener("pointermove", this.onPointerMove); this.domElement.ownerDocument.addEventListener("pointerup", this.onPointerUp); window.addEventListener("keydown", this.keydown); window.addEventListener("keyup", this.keyup); this.handleResize(); }); __publicField16(this, "dispose", () => { if (!this.domElement) return; this.domElement.removeEventListener("contextmenu", this.contextmenu); this.domElement.removeEventListener("pointerdown", this.onPointerDown); this.domElement.removeEventListener("wheel", this.mousewheel); this.domElement.removeEventListener("touchstart", this.touchstart); this.domElement.removeEventListener("touchend", this.touchend); this.domElement.removeEventListener("touchmove", this.touchmove); this.domElement.ownerDocument.removeEventListener("pointermove", this.onPointerMove); this.domElement.ownerDocument.removeEventListener("pointerup", this.onPointerUp); window.removeEventListener("keydown", this.keydown); window.removeEventListener("keyup", this.keyup); }); this.object = object; this.target0 = this.target.clone(); this.position0 = this.object.position.clone(); this.up0 = this.object.up.clone(); this.zoom0 = this.object.zoom; if (domElement !== void 0) this.connect(domElement); this.update(); } }; // node_modules/three-stdlib/controls/OrbitControls.js var __defProp17 = Object.defineProperty; var __defNormalProp17 = (obj, key, value) => key in obj ? __defProp17(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField17 = (obj, key, value) => { __defNormalProp17(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var _ray = new Ray(); var _plane3 = new Plane(); var TILT_LIMIT = Math.cos(70 * (Math.PI / 180)); var moduloWrapAround = (offset, capacity) => (offset % capacity + capacity) % capacity; var OrbitControls = class extends EventDispatcher2 { constructor(object, domElement) { super(); __publicField17(this, "object"); __publicField17(this, "domElement"); __publicField17(this, "enabled", true); __publicField17(this, "target", new Vector3()); __publicField17(this, "minDistance", 0); __publicField17(this, "maxDistance", Infinity); __publicField17(this, "minZoom", 0); __publicField17(this, "maxZoom", Infinity); __publicField17(this, "minPolarAngle", 0); __publicField17(this, "maxPolarAngle", Math.PI); __publicField17(this, "minAzimuthAngle", -Infinity); __publicField17(this, "maxAzimuthAngle", Infinity); __publicField17(this, "enableDamping", false); __publicField17(this, "dampingFactor", 0.05); __publicField17(this, "enableZoom", true); __publicField17(this, "zoomSpeed", 1); __publicField17(this, "enableRotate", true); __publicField17(this, "rotateSpeed", 1); __publicField17(this, "enablePan", true); __publicField17(this, "panSpeed", 1); __publicField17(this, "screenSpacePanning", true); __publicField17(this, "keyPanSpeed", 7); __publicField17(this, "zoomToCursor", false); __publicField17(this, "autoRotate", false); __publicField17(this, "autoRotateSpeed", 2); __publicField17(this, "reverseOrbit", false); __publicField17(this, "reverseHorizontalOrbit", false); __publicField17(this, "reverseVerticalOrbit", false); __publicField17(this, "keys", { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" }); __publicField17(this, "mouseButtons", { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }); __publicField17(this, "touches", { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }); __publicField17(this, "target0"); __publicField17(this, "position0"); __publicField17(this, "zoom0"); __publicField17(this, "_domElementKeyEvents", null); __publicField17(this, "getPolarAngle"); __publicField17(this, "getAzimuthalAngle"); __publicField17(this, "setPolarAngle"); __publicField17(this, "setAzimuthalAngle"); __publicField17(this, "getDistance"); __publicField17(this, "getZoomScale"); __publicField17(this, "listenToKeyEvents"); __publicField17(this, "stopListenToKeyEvents"); __publicField17(this, "saveState"); __publicField17(this, "reset"); __publicField17(this, "update"); __publicField17(this, "connect"); __publicField17(this, "dispose"); __publicField17(this, "dollyIn"); __publicField17(this, "dollyOut"); __publicField17(this, "getScale"); __publicField17(this, "setScale"); this.object = object; this.domElement = domElement; this.target0 = this.target.clone(); this.position0 = this.object.position.clone(); this.zoom0 = this.object.zoom; this.getPolarAngle = () => spherical2.phi; this.getAzimuthalAngle = () => spherical2.theta; this.setPolarAngle = (value) => { let phi = moduloWrapAround(value, 2 * Math.PI); let currentPhi = spherical2.phi; if (currentPhi < 0) currentPhi += 2 * Math.PI; if (phi < 0) phi += 2 * Math.PI; let phiDist = Math.abs(phi - currentPhi); if (2 * Math.PI - phiDist < phiDist) { if (phi < currentPhi) { phi += 2 * Math.PI; } else { currentPhi += 2 * Math.PI; } } sphericalDelta.phi = phi - currentPhi; scope.update(); }; this.setAzimuthalAngle = (value) => { let theta = moduloWrapAround(value, 2 * Math.PI); let currentTheta = spherical2.theta; if (currentTheta < 0) currentTheta += 2 * Math.PI; if (theta < 0) theta += 2 * Math.PI; let thetaDist = Math.abs(theta - currentTheta); if (2 * Math.PI - thetaDist < thetaDist) { if (theta < currentTheta) { theta += 2 * Math.PI; } else { currentTheta += 2 * Math.PI; } } sphericalDelta.theta = theta - currentTheta; scope.update(); }; this.getDistance = () => scope.object.position.distanceTo(scope.target); this.listenToKeyEvents = (domElement2) => { domElement2.addEventListener("keydown", onKeyDown); this._domElementKeyEvents = domElement2; }; this.stopListenToKeyEvents = () => { this._domElementKeyEvents.removeEventListener("keydown", onKeyDown); this._domElementKeyEvents = null; }; this.saveState = () => { scope.target0.copy(scope.target); scope.position0.copy(scope.object.position); scope.zoom0 = scope.object.zoom; }; this.reset = () => { scope.target.copy(scope.target0); scope.object.position.copy(scope.position0); scope.object.zoom = scope.zoom0; scope.object.updateProjectionMatrix(); scope.dispatchEvent(changeEvent); scope.update(); state = STATE3.NONE; }; this.update = (() => { const offset = new Vector3(); const up = new Vector3(0, 1, 0); const quat = new Quaternion().setFromUnitVectors(object.up, up); const quatInverse = quat.clone().invert(); const lastPosition = new Vector3(); const lastQuaternion = new Quaternion(); const twoPI = 2 * Math.PI; return function update2() { const position2 = scope.object.position; quat.setFromUnitVectors(object.up, up); quatInverse.copy(quat).invert(); offset.copy(position2).sub(scope.target); offset.applyQuaternion(quat); spherical2.setFromVector3(offset); if (scope.autoRotate && state === STATE3.NONE) { rotateLeft(getAutoRotationAngle()); } if (scope.enableDamping) { spherical2.theta += sphericalDelta.theta * scope.dampingFactor; spherical2.phi += sphericalDelta.phi * scope.dampingFactor; } else { spherical2.theta += sphericalDelta.theta; spherical2.phi += sphericalDelta.phi; } let min = scope.minAzimuthAngle; let max2 = scope.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) { spherical2.theta = Math.max(min, Math.min(max2, spherical2.theta)); } else { spherical2.theta = spherical2.theta > (min + max2) / 2 ? Math.max(min, spherical2.theta) : Math.min(max2, spherical2.theta); } } spherical2.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical2.phi)); spherical2.makeSafe(); if (scope.enableDamping === true) { scope.target.addScaledVector(panOffset, scope.dampingFactor); } else { scope.target.add(panOffset); } if (scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera) { spherical2.radius = clampDistance(spherical2.radius); } else { spherical2.radius = clampDistance(spherical2.radius * scale5); } offset.setFromSpherical(spherical2); offset.applyQuaternion(quatInverse); position2.copy(scope.target).add(offset); if (!scope.object.matrixAutoUpdate) scope.object.updateMatrix(); scope.object.lookAt(scope.target); if (scope.enableDamping === true) { sphericalDelta.theta *= 1 - scope.dampingFactor; sphericalDelta.phi *= 1 - scope.dampingFactor; panOffset.multiplyScalar(1 - scope.dampingFactor); } else { sphericalDelta.set(0, 0, 0); panOffset.set(0, 0, 0); } let zoomChanged = false; if (scope.zoomToCursor && performCursorZoom) { let newRadius = null; if (scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) { const prevRadius = offset.length(); newRadius = clampDistance(prevRadius * scale5); const radiusDelta = prevRadius - newRadius; scope.object.position.addScaledVector(dollyDirection, radiusDelta); scope.object.updateMatrixWorld(); } else if (scope.object.isOrthographicCamera) { const mouseBefore = new Vector3(mouse.x, mouse.y, 0); mouseBefore.unproject(scope.object); scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale5)); scope.object.updateProjectionMatrix(); zoomChanged = true; const mouseAfter = new Vector3(mouse.x, mouse.y, 0); mouseAfter.unproject(scope.object); scope.object.position.sub(mouseAfter).add(mouseBefore); scope.object.updateMatrixWorld(); newRadius = offset.length(); } else { console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."); scope.zoomToCursor = false; } if (newRadius !== null) { if (scope.screenSpacePanning) { scope.target.set(0, 0, -1).transformDirection(scope.object.matrix).multiplyScalar(newRadius).add(scope.object.position); } else { _ray.origin.copy(scope.object.position); _ray.direction.set(0, 0, -1).transformDirection(scope.object.matrix); if (Math.abs(scope.object.up.dot(_ray.direction)) < TILT_LIMIT) { object.lookAt(scope.target); } else { _plane3.setFromNormalAndCoplanarPoint(scope.object.up, scope.target); _ray.intersectPlane(_plane3, scope.target); } } } } else if (scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { zoomChanged = scale5 !== 1; if (zoomChanged) { scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale5)); scope.object.updateProjectionMatrix(); } } scale5 = 1; performCursorZoom = false; if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS2 || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS2) { scope.dispatchEvent(changeEvent); lastPosition.copy(scope.object.position); lastQuaternion.copy(scope.object.quaternion); zoomChanged = false; return true; } return false; }; })(); this.connect = (domElement2) => { scope.domElement = domElement2; scope.domElement.style.touchAction = "none"; scope.domElement.addEventListener("contextmenu", onContextMenu); scope.domElement.addEventListener("pointerdown", onPointerDown); scope.domElement.addEventListener("pointercancel", onPointerUp); scope.domElement.addEventListener("wheel", onMouseWheel); }; this.dispose = () => { var _a3, _b3, _c, _d, _e, _f; if (scope.domElement) { scope.domElement.style.touchAction = "auto"; } (_a3 = scope.domElement) == null ? void 0 : _a3.removeEventListener("contextmenu", onContextMenu); (_b3 = scope.domElement) == null ? void 0 : _b3.removeEventListener("pointerdown", onPointerDown); (_c = scope.domElement) == null ? void 0 : _c.removeEventListener("pointercancel", onPointerUp); (_d = scope.domElement) == null ? void 0 : _d.removeEventListener("wheel", onMouseWheel); (_e = scope.domElement) == null ? void 0 : _e.ownerDocument.removeEventListener("pointermove", onPointerMove); (_f = scope.domElement) == null ? void 0 : _f.ownerDocument.removeEventListener("pointerup", onPointerUp); if (scope._domElementKeyEvents !== null) { scope._domElementKeyEvents.removeEventListener("keydown", onKeyDown); } }; const scope = this; const changeEvent = { type: "change" }; const startEvent = { type: "start" }; const endEvent = { type: "end" }; const STATE3 = { NONE: -1, ROTATE: 0, DOLLY: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_PAN: 4, TOUCH_DOLLY_PAN: 5, TOUCH_DOLLY_ROTATE: 6 }; let state = STATE3.NONE; const EPS2 = 1e-6; const spherical2 = new Spherical(); const sphericalDelta = new Spherical(); let scale5 = 1; const panOffset = new Vector3(); const rotateStart = new Vector2(); const rotateEnd = new Vector2(); const rotateDelta = new Vector2(); const panStart = new Vector2(); const panEnd = new Vector2(); const panDelta = new Vector2(); const dollyStart = new Vector2(); const dollyEnd = new Vector2(); const dollyDelta = new Vector2(); const dollyDirection = new Vector3(); const mouse = new Vector2(); let performCursorZoom = false; const pointers = []; const pointerPositions = {}; function getAutoRotationAngle() { return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; } function getZoomScale() { return Math.pow(0.95, scope.zoomSpeed); } function rotateLeft(angle) { if (scope.reverseOrbit || scope.reverseHorizontalOrbit) { sphericalDelta.theta += angle; } else { sphericalDelta.theta -= angle; } } function rotateUp(angle) { if (scope.reverseOrbit || scope.reverseVerticalOrbit) { sphericalDelta.phi += angle; } else { sphericalDelta.phi -= angle; } } const panLeft = (() => { const v5 = new Vector3(); return function panLeft2(distance3, objectMatrix) { v5.setFromMatrixColumn(objectMatrix, 0); v5.multiplyScalar(-distance3); panOffset.add(v5); }; })(); const panUp = (() => { const v5 = new Vector3(); return function panUp2(distance3, objectMatrix) { if (scope.screenSpacePanning === true) { v5.setFromMatrixColumn(objectMatrix, 1); } else { v5.setFromMatrixColumn(objectMatrix, 0); v5.crossVectors(scope.object.up, v5); } v5.multiplyScalar(distance3); panOffset.add(v5); }; })(); const pan = (() => { const offset = new Vector3(); return function pan2(deltaX, deltaY) { const element = scope.domElement; if (element && scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera) { const position2 = scope.object.position; offset.copy(position2).sub(scope.target); let targetDistance = offset.length(); targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180); panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix); panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix); } else if (element && scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { panLeft( deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix ); panUp( deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix ); } else { console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."); scope.enablePan = false; } }; })(); function setScale(newScale) { if (scope.object instanceof PerspectiveCamera && scope.object.isPerspectiveCamera || scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { scale5 = newScale; } else { console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."); scope.enableZoom = false; } } function dollyOut(dollyScale) { setScale(scale5 / dollyScale); } function dollyIn(dollyScale) { setScale(scale5 * dollyScale); } function updateMouseParameters(event) { if (!scope.zoomToCursor || !scope.domElement) { return; } performCursorZoom = true; const rect = scope.domElement.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; const w = rect.width; const h = rect.height; mouse.x = x / w * 2 - 1; mouse.y = -(y / h) * 2 + 1; dollyDirection.set(mouse.x, mouse.y, 1).unproject(scope.object).sub(scope.object.position).normalize(); } function clampDistance(dist) { return Math.max(scope.minDistance, Math.min(scope.maxDistance, dist)); } function handleMouseDownRotate(event) { rotateStart.set(event.clientX, event.clientY); } function handleMouseDownDolly(event) { updateMouseParameters(event); dollyStart.set(event.clientX, event.clientY); } function handleMouseDownPan(event) { panStart.set(event.clientX, event.clientY); } function handleMouseMoveRotate(event) { rotateEnd.set(event.clientX, event.clientY); rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); const element = scope.domElement; if (element) { rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); } rotateStart.copy(rotateEnd); scope.update(); } function handleMouseMoveDolly(event) { dollyEnd.set(event.clientX, event.clientY); dollyDelta.subVectors(dollyEnd, dollyStart); if (dollyDelta.y > 0) { dollyOut(getZoomScale()); } else if (dollyDelta.y < 0) { dollyIn(getZoomScale()); } dollyStart.copy(dollyEnd); scope.update(); } function handleMouseMovePan(event) { panEnd.set(event.clientX, event.clientY); panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); pan(panDelta.x, panDelta.y); panStart.copy(panEnd); scope.update(); } function handleMouseWheel(event) { updateMouseParameters(event); if (event.deltaY < 0) { dollyIn(getZoomScale()); } else if (event.deltaY > 0) { dollyOut(getZoomScale()); } scope.update(); } function handleKeyDown(event) { let needsUpdate = false; switch (event.code) { case scope.keys.UP: pan(0, scope.keyPanSpeed); needsUpdate = true; break; case scope.keys.BOTTOM: pan(0, -scope.keyPanSpeed); needsUpdate = true; break; case scope.keys.LEFT: pan(scope.keyPanSpeed, 0); needsUpdate = true; break; case scope.keys.RIGHT: pan(-scope.keyPanSpeed, 0); needsUpdate = true; break; } if (needsUpdate) { event.preventDefault(); scope.update(); } } function handleTouchStartRotate() { if (pointers.length == 1) { rotateStart.set(pointers[0].pageX, pointers[0].pageY); } else { const x = 0.5 * (pointers[0].pageX + pointers[1].pageX); const y = 0.5 * (pointers[0].pageY + pointers[1].pageY); rotateStart.set(x, y); } } function handleTouchStartPan() { if (pointers.length == 1) { panStart.set(pointers[0].pageX, pointers[0].pageY); } else { const x = 0.5 * (pointers[0].pageX + pointers[1].pageX); const y = 0.5 * (pointers[0].pageY + pointers[1].pageY); panStart.set(x, y); } } function handleTouchStartDolly() { const dx = pointers[0].pageX - pointers[1].pageX; const dy = pointers[0].pageY - pointers[1].pageY; const distance3 = Math.sqrt(dx * dx + dy * dy); dollyStart.set(0, distance3); } function handleTouchStartDollyPan() { if (scope.enableZoom) handleTouchStartDolly(); if (scope.enablePan) handleTouchStartPan(); } function handleTouchStartDollyRotate() { if (scope.enableZoom) handleTouchStartDolly(); if (scope.enableRotate) handleTouchStartRotate(); } function handleTouchMoveRotate(event) { if (pointers.length == 1) { rotateEnd.set(event.pageX, event.pageY); } else { const position2 = getSecondPointerPosition(event); const x = 0.5 * (event.pageX + position2.x); const y = 0.5 * (event.pageY + position2.y); rotateEnd.set(x, y); } rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); const element = scope.domElement; if (element) { rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); } rotateStart.copy(rotateEnd); } function handleTouchMovePan(event) { if (pointers.length == 1) { panEnd.set(event.pageX, event.pageY); } else { const position2 = getSecondPointerPosition(event); const x = 0.5 * (event.pageX + position2.x); const y = 0.5 * (event.pageY + position2.y); panEnd.set(x, y); } panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); pan(panDelta.x, panDelta.y); panStart.copy(panEnd); } function handleTouchMoveDolly(event) { const position2 = getSecondPointerPosition(event); const dx = event.pageX - position2.x; const dy = event.pageY - position2.y; const distance3 = Math.sqrt(dx * dx + dy * dy); dollyEnd.set(0, distance3); dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed)); dollyOut(dollyDelta.y); dollyStart.copy(dollyEnd); } function handleTouchMoveDollyPan(event) { if (scope.enableZoom) handleTouchMoveDolly(event); if (scope.enablePan) handleTouchMovePan(event); } function handleTouchMoveDollyRotate(event) { if (scope.enableZoom) handleTouchMoveDolly(event); if (scope.enableRotate) handleTouchMoveRotate(event); } function onPointerDown(event) { var _a3, _b3; if (scope.enabled === false) return; if (pointers.length === 0) { (_a3 = scope.domElement) == null ? void 0 : _a3.ownerDocument.addEventListener("pointermove", onPointerMove); (_b3 = scope.domElement) == null ? void 0 : _b3.ownerDocument.addEventListener("pointerup", onPointerUp); } addPointer(event); if (event.pointerType === "touch") { onTouchStart(event); } else { onMouseDown(event); } } function onPointerMove(event) { if (scope.enabled === false) return; if (event.pointerType === "touch") { onTouchMove(event); } else { onMouseMove(event); } } function onPointerUp(event) { var _a3, _b3, _c; removePointer(event); if (pointers.length === 0) { (_a3 = scope.domElement) == null ? void 0 : _a3.releasePointerCapture(event.pointerId); (_b3 = scope.domElement) == null ? void 0 : _b3.ownerDocument.removeEventListener("pointermove", onPointerMove); (_c = scope.domElement) == null ? void 0 : _c.ownerDocument.removeEventListener("pointerup", onPointerUp); } scope.dispatchEvent(endEvent); state = STATE3.NONE; } function onMouseDown(event) { let mouseAction; switch (event.button) { case 0: mouseAction = scope.mouseButtons.LEFT; break; case 1: mouseAction = scope.mouseButtons.MIDDLE; break; case 2: mouseAction = scope.mouseButtons.RIGHT; break; default: mouseAction = -1; } switch (mouseAction) { case MOUSE.DOLLY: if (scope.enableZoom === false) return; handleMouseDownDolly(event); state = STATE3.DOLLY; break; case MOUSE.ROTATE: if (event.ctrlKey || event.metaKey || event.shiftKey) { if (scope.enablePan === false) return; handleMouseDownPan(event); state = STATE3.PAN; } else { if (scope.enableRotate === false) return; handleMouseDownRotate(event); state = STATE3.ROTATE; } break; case MOUSE.PAN: if (event.ctrlKey || event.metaKey || event.shiftKey) { if (scope.enableRotate === false) return; handleMouseDownRotate(event); state = STATE3.ROTATE; } else { if (scope.enablePan === false) return; handleMouseDownPan(event); state = STATE3.PAN; } break; default: state = STATE3.NONE; } if (state !== STATE3.NONE) { scope.dispatchEvent(startEvent); } } function onMouseMove(event) { if (scope.enabled === false) return; switch (state) { case STATE3.ROTATE: if (scope.enableRotate === false) return; handleMouseMoveRotate(event); break; case STATE3.DOLLY: if (scope.enableZoom === false) return; handleMouseMoveDolly(event); break; case STATE3.PAN: if (scope.enablePan === false) return; handleMouseMovePan(event); break; } } function onMouseWheel(event) { if (scope.enabled === false || scope.enableZoom === false || state !== STATE3.NONE && state !== STATE3.ROTATE) { return; } event.preventDefault(); scope.dispatchEvent(startEvent); handleMouseWheel(event); scope.dispatchEvent(endEvent); } function onKeyDown(event) { if (scope.enabled === false || scope.enablePan === false) return; handleKeyDown(event); } function onTouchStart(event) { trackPointer(event); switch (pointers.length) { case 1: switch (scope.touches.ONE) { case TOUCH.ROTATE: if (scope.enableRotate === false) return; handleTouchStartRotate(); state = STATE3.TOUCH_ROTATE; break; case TOUCH.PAN: if (scope.enablePan === false) return; handleTouchStartPan(); state = STATE3.TOUCH_PAN; break; default: state = STATE3.NONE; } break; case 2: switch (scope.touches.TWO) { case TOUCH.DOLLY_PAN: if (scope.enableZoom === false && scope.enablePan === false) return; handleTouchStartDollyPan(); state = STATE3.TOUCH_DOLLY_PAN; break; case TOUCH.DOLLY_ROTATE: if (scope.enableZoom === false && scope.enableRotate === false) return; handleTouchStartDollyRotate(); state = STATE3.TOUCH_DOLLY_ROTATE; break; default: state = STATE3.NONE; } break; default: state = STATE3.NONE; } if (state !== STATE3.NONE) { scope.dispatchEvent(startEvent); } } function onTouchMove(event) { trackPointer(event); switch (state) { case STATE3.TOUCH_ROTATE: if (scope.enableRotate === false) return; handleTouchMoveRotate(event); scope.update(); break; case STATE3.TOUCH_PAN: if (scope.enablePan === false) return; handleTouchMovePan(event); scope.update(); break; case STATE3.TOUCH_DOLLY_PAN: if (scope.enableZoom === false && scope.enablePan === false) return; handleTouchMoveDollyPan(event); scope.update(); break; case STATE3.TOUCH_DOLLY_ROTATE: if (scope.enableZoom === false && scope.enableRotate === false) return; handleTouchMoveDollyRotate(event); scope.update(); break; default: state = STATE3.NONE; } } function onContextMenu(event) { if (scope.enabled === false) return; event.preventDefault(); } function addPointer(event) { pointers.push(event); } function removePointer(event) { delete pointerPositions[event.pointerId]; for (let i4 = 0; i4 < pointers.length; i4++) { if (pointers[i4].pointerId == event.pointerId) { pointers.splice(i4, 1); return; } } } function trackPointer(event) { let position2 = pointerPositions[event.pointerId]; if (position2 === void 0) { position2 = new Vector2(); pointerPositions[event.pointerId] = position2; } position2.set(event.pageX, event.pageY); } function getSecondPointerPosition(event) { const pointer = event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0]; return pointerPositions[pointer.pointerId]; } this.dollyIn = (dollyScale = getZoomScale()) => { dollyIn(dollyScale); scope.update(); }; this.dollyOut = (dollyScale = getZoomScale()) => { dollyOut(dollyScale); scope.update(); }; this.getScale = () => { return scale5; }; this.setScale = (newScale) => { setScale(newScale); scope.update(); }; this.getZoomScale = () => { return getZoomScale(); }; if (domElement !== void 0) this.connect(domElement); this.update(); } }; var MapControls = class extends OrbitControls { constructor(object, domElement) { super(object, domElement); this.screenSpacePanning = false; this.mouseButtons.LEFT = MOUSE.PAN; this.mouseButtons.RIGHT = MOUSE.ROTATE; this.touches.ONE = TOUCH.PAN; this.touches.TWO = TOUCH.DOLLY_ROTATE; } }; // node_modules/three-stdlib/controls/ArcballControls.js var __defProp18 = Object.defineProperty; var __defNormalProp18 = (obj, key, value) => key in obj ? __defProp18(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField18 = (obj, key, value) => { __defNormalProp18(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var STATE = { IDLE: /* @__PURE__ */ Symbol(), ROTATE: /* @__PURE__ */ Symbol(), PAN: /* @__PURE__ */ Symbol(), SCALE: /* @__PURE__ */ Symbol(), FOV: /* @__PURE__ */ Symbol(), FOCUS: /* @__PURE__ */ Symbol(), ZROTATE: /* @__PURE__ */ Symbol(), TOUCH_MULTI: /* @__PURE__ */ Symbol(), ANIMATION_FOCUS: /* @__PURE__ */ Symbol(), ANIMATION_ROTATE: /* @__PURE__ */ Symbol() }; var INPUT = { NONE: /* @__PURE__ */ Symbol(), ONE_FINGER: /* @__PURE__ */ Symbol(), ONE_FINGER_SWITCHED: /* @__PURE__ */ Symbol(), TWO_FINGER: /* @__PURE__ */ Symbol(), MULT_FINGER: /* @__PURE__ */ Symbol(), CURSOR: /* @__PURE__ */ Symbol() }; var _center = { x: 0, y: 0 }; var _transformation = { camera: new Matrix4(), gizmos: new Matrix4() }; var _changeEvent2 = { type: "change" }; var _startEvent = { type: "start" }; var _endEvent = { type: "end" }; var ArcballControls = class extends EventDispatcher2 { constructor(camera, domElement = null, scene = null) { super(); __publicField18(this, "camera"); __publicField18(this, "domElement"); __publicField18(this, "scene"); __publicField18(this, "mouseActions"); __publicField18(this, "_mouseOp"); __publicField18(this, "_v2_1"); __publicField18(this, "_v3_1"); __publicField18(this, "_v3_2"); __publicField18(this, "_m4_1"); __publicField18(this, "_m4_2"); __publicField18(this, "_quat"); __publicField18(this, "_translationMatrix"); __publicField18(this, "_rotationMatrix"); __publicField18(this, "_scaleMatrix"); __publicField18(this, "_rotationAxis"); __publicField18(this, "_cameraMatrixState"); __publicField18(this, "_cameraProjectionState"); __publicField18(this, "_fovState"); __publicField18(this, "_upState"); __publicField18(this, "_zoomState"); __publicField18(this, "_nearPos"); __publicField18(this, "_farPos"); __publicField18(this, "_gizmoMatrixState"); __publicField18(this, "_up0"); __publicField18(this, "_zoom0"); __publicField18(this, "_fov0"); __publicField18(this, "_initialNear"); __publicField18(this, "_nearPos0"); __publicField18(this, "_initialFar"); __publicField18(this, "_farPos0"); __publicField18(this, "_cameraMatrixState0"); __publicField18(this, "_gizmoMatrixState0"); __publicField18(this, "_button"); __publicField18(this, "_touchStart"); __publicField18(this, "_touchCurrent"); __publicField18(this, "_input"); __publicField18(this, "_switchSensibility"); __publicField18(this, "_startFingerDistance"); __publicField18(this, "_currentFingerDistance"); __publicField18(this, "_startFingerRotation"); __publicField18(this, "_currentFingerRotation"); __publicField18(this, "_devPxRatio"); __publicField18(this, "_downValid"); __publicField18(this, "_nclicks"); __publicField18(this, "_downEvents"); __publicField18(this, "_clickStart"); __publicField18(this, "_maxDownTime"); __publicField18(this, "_maxInterval"); __publicField18(this, "_posThreshold"); __publicField18(this, "_movementThreshold"); __publicField18(this, "_currentCursorPosition"); __publicField18(this, "_startCursorPosition"); __publicField18(this, "_grid"); __publicField18(this, "_gridPosition"); __publicField18(this, "_gizmos"); __publicField18(this, "_curvePts"); __publicField18(this, "_timeStart"); __publicField18(this, "_animationId"); __publicField18(this, "focusAnimationTime"); __publicField18(this, "_timePrev"); __publicField18(this, "_timeCurrent"); __publicField18(this, "_anglePrev"); __publicField18(this, "_angleCurrent"); __publicField18(this, "_cursorPosPrev"); __publicField18(this, "_cursorPosCurr"); __publicField18(this, "_wPrev"); __publicField18(this, "_wCurr"); __publicField18(this, "adjustNearFar"); __publicField18(this, "scaleFactor"); __publicField18(this, "dampingFactor"); __publicField18(this, "wMax"); __publicField18(this, "enableAnimations"); __publicField18(this, "enableGrid"); __publicField18(this, "cursorZoom"); __publicField18(this, "minFov"); __publicField18(this, "maxFov"); __publicField18(this, "enabled"); __publicField18(this, "enablePan"); __publicField18(this, "enableRotate"); __publicField18(this, "enableZoom"); __publicField18(this, "minDistance"); __publicField18(this, "maxDistance"); __publicField18(this, "minZoom"); __publicField18(this, "maxZoom"); __publicField18(this, "target"); __publicField18(this, "_currentTarget"); __publicField18(this, "_tbRadius"); __publicField18(this, "_state"); __publicField18(this, "onWindowResize", () => { const scale5 = (this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z) / 3; if (this.camera) { const tbRadius = this.calculateTbRadius(this.camera); if (tbRadius !== void 0) { this._tbRadius = tbRadius; } } const newRadius = this._tbRadius / scale5; 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) { const child = this._gizmos.children[gizmo]; child.geometry = curveGeometry; } this.dispatchEvent(_changeEvent2); }); __publicField18(this, "onContextMenu", (event) => { if (!this.enabled) { return; } for (let i4 = 0; i4 < this.mouseActions.length; i4++) { if (this.mouseActions[i4].mouse == 2) { event.preventDefault(); break; } } }); __publicField18(this, "onPointerCancel", () => { this._touchStart.splice(0, this._touchStart.length); this._touchCurrent.splice(0, this._touchCurrent.length); this._input = INPUT.NONE; }); __publicField18(this, "onPointerDown", (event) => { if (event.button == 0 && event.isPrimary) { this._downValid = true; this._downEvents.push(event); } 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(); 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) { window.addEventListener("pointermove", this.onPointerMove); window.addEventListener("pointerup", this.onPointerUp); this._input = INPUT.CURSOR; this._button = event.button; this.onSinglePanStart(event, this._mouseOp); } } }); __publicField18(this, "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(); 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) { 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; } } }); __publicField18(this, "onPointerUp", (event) => { if (event.pointerType == "touch" && this._input != INPUT.CURSOR) { const nTouch = this._touchCurrent.length; for (let i4 = 0; i4 < nTouch; i4++) { if (this._touchCurrent[i4].pointerId == event.pointerId) { this._touchCurrent.splice(i4, 1); this._touchStart.splice(i4, 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(); this.onPinchEnd(); this.onRotateEnd(); 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); } } }); __publicField18(this, "onWheel", (event) => { var _a3, _b3; if (this.enabled && this.enableZoom && this.domElement) { let modifier = null; if (event.ctrlKey || event.metaKey) { modifier = "CTRL"; } else if (event.shiftKey) { modifier = "SHIFT"; } const mouseOp = this.getOpFromAction("WHEEL", modifier); if (mouseOp) { 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.camera instanceof OrthographicCamera) { scalePoint = (_a3 = this.unprojectOnTbPlane(this.camera, event.clientX, event.clientY, this.domElement)) == null ? void 0 : _a3.applyQuaternion(this.camera.quaternion).multiplyScalar(1 / this.camera.zoom).add(this._gizmos.position); } if (this.camera instanceof PerspectiveCamera) { scalePoint = (_b3 = this.unprojectOnTbPlane(this.camera, event.clientX, event.clientY, this.domElement)) == null ? void 0 : _b3.applyQuaternion(this.camera.quaternion).add(this._gizmos.position); } if (scalePoint !== void 0) this.applyTransformMatrix(this.applyScale(size2, scalePoint)); } else { this.applyTransformMatrix(this.applyScale(size2, this._gizmos.position)); } if (this._grid) { this.disposeGrid(); this.drawGrid(); } this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_changeEvent2); this.dispatchEvent(_endEvent); break; case "FOV": if (this.camera instanceof PerspectiveCamera) { 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 x = this._v3_1.distanceTo(this._gizmos.position); let xNew = x / size2; xNew = MathUtils.clamp(xNew, this.minDistance, this.maxDistance); const y = x * Math.tan(MathUtils.DEG2RAD * this.camera.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 = x / newDistance; this.setFov(newFov); this.applyTransformMatrix(this.applyScale(size2, this._gizmos.position, false)); } if (this._grid) { this.disposeGrid(); this.drawGrid(); } this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_changeEvent2); this.dispatchEvent(_endEvent); break; } } } }); __publicField18(this, "onSinglePanStart", (event, operation) => { if (this.enabled && this.domElement) { 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(_changeEvent2); } if (this.camera) { this.updateTbState(STATE.PAN, true); const rayDir = this.unprojectOnTbPlane(this.camera, _center.x, _center.y, this.domElement); if (rayDir !== void 0) { this._startCursorPosition.copy(rayDir); } if (this.enableGrid) { this.drawGrid(); this.dispatchEvent(_changeEvent2); } } break; case "ROTATE": if (!this.enableRotate) return; if (this._animationId != -1) { cancelAnimationFrame(this._animationId); this._animationId = -1; this._timeStart = -1; } if (this.camera) { this.updateTbState(STATE.ROTATE, true); const rayDir = this.unprojectOnTbSurface(this.camera, _center.x, _center.y, this.domElement, this._tbRadius); if (rayDir !== void 0) { this._startCursorPosition.copy(rayDir); } 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(_changeEvent2); break; case "FOV": if (!this.enableZoom) return; if (this.camera instanceof PerspectiveCamera) { if (this._animationId != -1) { cancelAnimationFrame(this._animationId); this._animationId = -1; this._timeStart = -1; this.activateGizmos(false); this.dispatchEvent(_changeEvent2); } 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(_changeEvent2); } 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; } } }); __publicField18(this, "onSinglePanMove", (event, opState) => { if (this.enabled && this.domElement) { const restart = opState != this._state; this.setCenter(event.clientX, event.clientY); switch (opState) { case STATE.PAN: if (this.enablePan && this.camera) { if (restart) { this.dispatchEvent(_endEvent); this.dispatchEvent(_startEvent); this.updateTbState(opState, true); const rayDir = this.unprojectOnTbPlane(this.camera, _center.x, _center.y, this.domElement); if (rayDir !== void 0) { this._startCursorPosition.copy(rayDir); } if (this.enableGrid) { this.drawGrid(); } this.activateGizmos(false); } else { const rayDir = this.unprojectOnTbPlane(this.camera, _center.x, _center.y, this.domElement); if (rayDir !== void 0) { this._currentCursorPosition.copy(rayDir); } this.applyTransformMatrix(this.pan(this._startCursorPosition, this._currentCursorPosition)); } } break; case STATE.ROTATE: if (this.enableRotate && this.camera) { if (restart) { this.dispatchEvent(_endEvent); this.dispatchEvent(_startEvent); this.updateTbState(opState, true); const rayDir = this.unprojectOnTbSurface( this.camera, _center.x, _center.y, this.domElement, this._tbRadius ); if (rayDir !== void 0) { this._startCursorPosition.copy(rayDir); } if (this.enableGrid) { this.disposeGrid(); } this.activateGizmos(true); } else { const rayDir = this.unprojectOnTbSurface( this.camera, _center.x, _center.y, this.domElement, this._tbRadius ); if (rayDir !== void 0) { this._currentCursorPosition.copy(rayDir); } const distance3 = this._startCursorPosition.distanceTo(this._currentCursorPosition); const angle = this._startCursorPosition.angleTo(this._currentCursorPosition); const amount = Math.max(distance3 / this._tbRadius, angle); 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.applyTransformMatrix(this.applyScale(size2, this._gizmos.position)); } } break; case STATE.FOV: if (this.enableZoom && this.camera instanceof PerspectiveCamera) { 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 x = this._v3_1.distanceTo(this._gizmos.position); let xNew = x / size2; xNew = MathUtils.clamp(xNew, this.minDistance, this.maxDistance); const y = x * 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 = x / newDistance; this._v3_2.setFromMatrixPosition(this._gizmoMatrixState); this.setFov(newFov); this.applyTransformMatrix(this.applyScale(size2, this._v3_2, false)); const direction2 = this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(newDistance / x); this._m4_1.makeTranslation(direction2.x, direction2.y, direction2.z); } } break; } this.dispatchEvent(_changeEvent2); } }); __publicField18(this, "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(_changeEvent2); } } else { this.updateTbState(STATE.IDLE, false); this.activateGizmos(false); this.dispatchEvent(_changeEvent2); } } 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(_changeEvent2); } this.dispatchEvent(_endEvent); }); __publicField18(this, "onDoubleTap", (event) => { if (this.enabled && this.enablePan && this.scene && this.camera && this.domElement) { this.dispatchEvent(_startEvent); this.setCenter(event.clientX, event.clientY); const hitP = this.unprojectOnObj(this.getCursorNDC(_center.x, _center.y, this.domElement), this.camera); if (hitP && 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 && !this.enableAnimations) { this.updateTbState(STATE.FOCUS, true); this.focus(hitP, this.scaleFactor); this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_changeEvent2); } } this.dispatchEvent(_endEvent); }); __publicField18(this, "onDoublePanStart", () => { if (this.enabled && this.enablePan && this.camera && this.domElement) { 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 ); const rayDir = this.unprojectOnTbPlane(this.camera, _center.x, _center.y, this.domElement, true); if (rayDir !== void 0) { this._startCursorPosition.copy(rayDir); } this._currentCursorPosition.copy(this._startCursorPosition); this.activateGizmos(false); } }); __publicField18(this, "onDoublePanMove", () => { if (this.enabled && this.enablePan && this.camera && this.domElement) { 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); } const rayDir = this.unprojectOnTbPlane(this.camera, _center.x, _center.y, this.domElement, true); if (rayDir !== void 0) this._currentCursorPosition.copy(rayDir); this.applyTransformMatrix(this.pan(this._startCursorPosition, this._currentCursorPosition, true)); this.dispatchEvent(_changeEvent2); } }); __publicField18(this, "onDoublePanEnd", () => { this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_endEvent); }); __publicField18(this, "onRotateStart", () => { var _a3; 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; (_a3 = this.camera) == null ? void 0 : _a3.getWorldDirection(this._rotationAxis); if (!this.enablePan && !this.enableZoom) { this.activateGizmos(true); } } }); __publicField18(this, "onRotateMove", () => { var _a3; if (this.enabled && this.enableRotate && this.camera && this.domElement) { 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 if (this.camera) { this._v3_2.setFromMatrixPosition(this._gizmoMatrixState); rotationPoint = (_a3 = this.unprojectOnTbPlane(this.camera, _center.x, _center.y, this.domElement)) == null ? void 0 : _a3.applyQuaternion(this.camera.quaternion).multiplyScalar(1 / this.camera.zoom).add(this._v3_2); } const amount = MathUtils.DEG2RAD * (this._startFingerRotation - this._currentFingerRotation); if (rotationPoint !== void 0) { this.applyTransformMatrix(this.zRotate(rotationPoint, amount)); } this.dispatchEvent(_changeEvent2); } }); __publicField18(this, "onRotateEnd", () => { this.updateTbState(STATE.IDLE, false); this.activateGizmos(false); this.dispatchEvent(_endEvent); }); __publicField18(this, "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); } }); __publicField18(this, "onPinchMove", () => { var _a3, _b3; if (this.enabled && this.enableZoom && this.domElement) { 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.camera instanceof OrthographicCamera) { scalePoint = (_a3 = this.unprojectOnTbPlane(this.camera, _center.x, _center.y, this.domElement)) == null ? void 0 : _a3.applyQuaternion(this.camera.quaternion).multiplyScalar(1 / this.camera.zoom).add(this._gizmos.position); } else if (this.camera instanceof PerspectiveCamera) { scalePoint = (_b3 = this.unprojectOnTbPlane(this.camera, _center.x, _center.y, this.domElement)) == null ? void 0 : _b3.applyQuaternion(this.camera.quaternion).add(this._gizmos.position); } } if (scalePoint !== void 0) { this.applyTransformMatrix(this.applyScale(amount, scalePoint)); } this.dispatchEvent(_changeEvent2); } }); __publicField18(this, "onPinchEnd", () => { this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_endEvent); }); __publicField18(this, "onTriplePanStart", () => { if (this.enabled && this.enableZoom && this.domElement) { this.dispatchEvent(_startEvent); this.updateTbState(STATE.SCALE, true); let clientX = 0; let clientY = 0; const nFingers = this._touchCurrent.length; for (let i4 = 0; i4 < nFingers; i4++) { clientX += this._touchCurrent[i4].clientX; clientY += this._touchCurrent[i4].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); } }); __publicField18(this, "onTriplePanMove", () => { if (this.enabled && this.enableZoom && this.camera && this.domElement) { let clientX = 0; let clientY = 0; const nFingers = this._touchCurrent.length; for (let i4 = 0; i4 < nFingers; i4++) { clientX += this._touchCurrent[i4].clientX; clientY += this._touchCurrent[i4].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 x = this._v3_1.distanceTo(this._gizmos.position); let xNew = x / size2; xNew = MathUtils.clamp(xNew, this.minDistance, this.maxDistance); const y = x * 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 = x / newDistance; this._v3_2.setFromMatrixPosition(this._gizmoMatrixState); this.setFov(newFov); this.applyTransformMatrix(this.applyScale(size2, this._v3_2, false)); const direction2 = this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(newDistance / x); this._m4_1.makeTranslation(direction2.x, direction2.y, direction2.z); this.dispatchEvent(_changeEvent2); } }); __publicField18(this, "onTriplePanEnd", () => { this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_endEvent); }); __publicField18(this, "setCenter", (clientX, clientY) => { _center.x = clientX; _center.y = clientY; }); __publicField18(this, "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"); }); __publicField18(this, "setMouseAction", (operation, mouse, key = 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(key)) { 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, state }; for (let i4 = 0; i4 < this.mouseActions.length; i4++) { if (this.mouseActions[i4].mouse == action.mouse && this.mouseActions[i4].key == action.key) { this.mouseActions.splice(i4, 1, action); return true; } } this.mouseActions.push(action); return true; }); __publicField18(this, "getOpFromAction", (mouse, key) => { let action; for (let i4 = 0; i4 < this.mouseActions.length; i4++) { action = this.mouseActions[i4]; if (action.mouse == mouse && action.key == key) { return action.operation; } } if (key) { for (let i4 = 0; i4 < this.mouseActions.length; i4++) { action = this.mouseActions[i4]; if (action.mouse == mouse && action.key == null) { return action.operation; } } } return null; }); __publicField18(this, "getOpStateFromAction", (mouse, key) => { let action; for (let i4 = 0; i4 < this.mouseActions.length; i4++) { action = this.mouseActions[i4]; if (action.mouse == mouse && action.key == key) { return action.state; } } if (key) { for (let i4 = 0; i4 < this.mouseActions.length; i4++) { action = this.mouseActions[i4]; if (action.mouse == mouse && action.key == null) { return action.state; } } } return null; }); __publicField18(this, "getAngle", (p1, p2) => { return Math.atan2(p2.clientY - p1.clientY, p2.clientX - p1.clientX) * 180 / Math.PI; }); __publicField18(this, "updateTouchEvent", (event) => { for (let i4 = 0; i4 < this._touchCurrent.length; i4++) { if (this._touchCurrent[i4].pointerId == event.pointerId) { this._touchCurrent.splice(i4, 1, event); break; } } }); __publicField18(this, "calculateAngularSpeed", (p0, p1, t0, t1) => { const s2 = p1 - p0; const t3 = (t1 - t0) / 1e3; if (t3 == 0) { return 0; } return s2 / t3; }); __publicField18(this, "calculatePointersDistance", (p0, p1) => { return Math.sqrt(Math.pow(p1.clientX - p0.clientX, 2) + Math.pow(p1.clientY - p0.clientY, 2)); }); __publicField18(this, "calculateRotationAxis", (vec13, vec23) => { this._rotationMatrix.extractRotation(this._cameraMatrixState); this._quat.setFromRotationMatrix(this._rotationMatrix); this._rotationAxis.crossVectors(vec13, vec23).applyQuaternion(this._quat); return this._rotationAxis.normalize().clone(); }); __publicField18(this, "calculateTbRadius", (camera2) => { const factor = 0.67; const distance3 = camera2.position.distanceTo(this._gizmos.position); if (camera2 instanceof PerspectiveCamera) { const halfFovV = MathUtils.DEG2RAD * camera2.fov * 0.5; const halfFovH = Math.atan(camera2.aspect * Math.tan(halfFovV)); return Math.tan(Math.min(halfFovV, halfFovH)) * distance3 * factor; } else if (camera2 instanceof OrthographicCamera) { return Math.min(camera2.top, camera2.right) * factor; } }); __publicField18(this, "focus", (point, size2, amount = 1) => { if (this.camera) { const focusPoint = point.clone(); focusPoint.sub(this._gizmos.position).multiplyScalar(amount); this._translationMatrix.makeTranslation(focusPoint.x, focusPoint.y, focusPoint.z); const gizmoStateTemp = this._gizmoMatrixState.clone(); this._gizmoMatrixState.premultiply(this._translationMatrix); this._gizmoMatrixState.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale); const cameraStateTemp = this._cameraMatrixState.clone(); this._cameraMatrixState.premultiply(this._translationMatrix); this._cameraMatrixState.decompose(this.camera.position, this.camera.quaternion, this.camera.scale); if (this.enableZoom) { this.applyTransformMatrix(this.applyScale(size2, this._gizmos.position)); } this._gizmoMatrixState.copy(gizmoStateTemp); this._cameraMatrixState.copy(cameraStateTemp); } }); __publicField18(this, "drawGrid", () => { if (this.scene) { const color = 8947848; const multiplier = 3; let size2, divisions, maxLength, tick; if (this.camera instanceof OrthographicCamera) { const width = this.camera.right - this.camera.left; const height = this.camera.bottom - this.camera.top; maxLength = Math.max(width, height); tick = maxLength / 20; size2 = maxLength / this.camera.zoom * multiplier; divisions = size2 / tick * this.camera.zoom; } else if (this.camera instanceof PerspectiveCamera) { const distance3 = this.camera.position.distanceTo(this._gizmos.position); const halfFovV = MathUtils.DEG2RAD * this.camera.fov * 0.5; const halfFovH = Math.atan(this.camera.aspect * Math.tan(halfFovV)); maxLength = Math.tan(Math.max(halfFovV, halfFovH)) * distance3 * 2; tick = maxLength / 20; size2 = maxLength * multiplier; divisions = size2 / tick; } if (this._grid == null && this.camera) { 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.camera.quaternion); this._grid.rotateX(Math.PI * 0.5); this.scene.add(this._grid); } } }); __publicField18(this, "connect", (domElement2) => { if (domElement2 === document) { console.error( 'THREE.ArcballControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' ); } this.domElement = domElement2; this.domElement.style.touchAction = "none"; this.domElement.addEventListener("contextmenu", this.onContextMenu); this.domElement.addEventListener("pointerdown", this.onPointerDown); this.domElement.addEventListener("pointercancel", this.onPointerCancel); this.domElement.addEventListener("wheel", this.onWheel); }); __publicField18(this, "dispose", () => { var _a3, _b3, _c, _d, _e; if (this._animationId != -1) { window.cancelAnimationFrame(this._animationId); } (_a3 = this.domElement) == null ? void 0 : _a3.removeEventListener("pointerdown", this.onPointerDown); (_b3 = this.domElement) == null ? void 0 : _b3.removeEventListener("pointercancel", this.onPointerCancel); (_c = this.domElement) == null ? void 0 : _c.removeEventListener("wheel", this.onWheel); (_d = this.domElement) == null ? void 0 : _d.removeEventListener("contextmenu", this.onContextMenu); window.removeEventListener("pointermove", this.onPointerMove); window.removeEventListener("pointerup", this.onPointerUp); window.removeEventListener("resize", this.onWindowResize); (_e = this.scene) == null ? void 0 : _e.remove(this._gizmos); this.disposeGrid(); }); __publicField18(this, "disposeGrid", () => { if (this._grid && this.scene) { this.scene.remove(this._grid); this._grid = null; } }); __publicField18(this, "easeOutCubic", (t3) => { return 1 - Math.pow(1 - t3, 3); }); __publicField18(this, "activateGizmos", (isActive) => { for (const gizmo of this._gizmos.children) { gizmo.material.setValues({ opacity: isActive ? 1 : 0.6 }); } }); __publicField18(this, "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(); }); __publicField18(this, "getCursorPosition", (cursorX, cursorY, canvas) => { this._v2_1.copy(this.getCursorNDC(cursorX, cursorY, canvas)); if (this.camera instanceof OrthographicCamera) { this._v2_1.x *= (this.camera.right - this.camera.left) * 0.5; this._v2_1.y *= (this.camera.top - this.camera.bottom) * 0.5; } return this._v2_1.clone(); }); __publicField18(this, "setCamera", (camera2) => { if (camera2) { camera2.lookAt(this.target); camera2.updateMatrix(); if (camera2 instanceof PerspectiveCamera) { this._fov0 = camera2.fov; this._fovState = camera2.fov; } this._cameraMatrixState0.copy(camera2.matrix); this._cameraMatrixState.copy(this._cameraMatrixState0); this._cameraProjectionState.copy(camera2.projectionMatrix); this._zoom0 = camera2.zoom; this._zoomState = this._zoom0; this._initialNear = camera2.near; this._nearPos0 = camera2.position.distanceTo(this.target) - camera2.near; this._nearPos = this._initialNear; this._initialFar = camera2.far; this._farPos0 = camera2.position.distanceTo(this.target) - camera2.far; this._farPos = this._initialFar; this._up0.copy(camera2.up); this._upState.copy(camera2.up); this.camera = camera2; this.camera.updateProjectionMatrix(); const tbRadius = this.calculateTbRadius(camera2); if (tbRadius !== void 0) { this._tbRadius = tbRadius; } this.makeGizmos(this.target, this._tbRadius); } }); __publicField18(this, "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 rotation3 = Math.PI * 0.5; gizmoX.rotation.x = rotation3; gizmoY.rotation.y = rotation3; this._gizmoMatrixState0.identity().setPosition(tbCenter); this._gizmoMatrixState.copy(this._gizmoMatrixState0); if (this.camera && this.camera.zoom != 1) { const size2 = 1 / this.camera.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.clear(); this._gizmos.add(gizmoX); this._gizmos.add(gizmoY); this._gizmos.add(gizmoZ); }); __publicField18(this, "onFocusAnim", (time, point, cameraMatrix, gizmoMatrix) => { if (this._timeStart == -1) { this._timeStart = time; } if (this._state == STATE.ANIMATION_FOCUS) { const deltaTime = time - 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(_changeEvent2); } 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(_changeEvent2); const self2 = this; this._animationId = window.requestAnimationFrame(function(t3) { self2.onFocusAnim(t3, point, cameraMatrix, gizmoMatrix.clone()); }); } } else { this._animationId = -1; this._timeStart = -1; } }); __publicField18(this, "onRotationAnim", (time, rotationAxis, w0) => { if (this._timeStart == -1) { this._anglePrev = 0; this._angleCurrent = 0; this._timeStart = time; } if (this._state == STATE.ANIMATION_ROTATE) { const deltaTime = (time - 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(_changeEvent2); 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(_changeEvent2); } } else { this._animationId = -1; this._timeStart = -1; if (this._state != STATE.ROTATE) { this.activateGizmos(false); this.dispatchEvent(_changeEvent2); } } }); __publicField18(this, "pan", (p0, p1, adjust = false) => { if (this.camera) { const movement = p0.clone().sub(p1); if (this.camera instanceof OrthographicCamera) { movement.multiplyScalar(1 / this.camera.zoom); } if (this.camera instanceof PerspectiveCamera && adjust) { this._v3_1.setFromMatrixPosition(this._cameraMatrixState0); this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0); const distanceFactor = this._v3_1.distanceTo(this._v3_2) / this.camera.position.distanceTo(this._gizmos.position); movement.multiplyScalar(1 / distanceFactor); } this._v3_1.set(movement.x, movement.y, 0).applyQuaternion(this.camera.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; }); __publicField18(this, "reset", () => { if (this.camera) { this.camera.zoom = this._zoom0; if (this.camera instanceof PerspectiveCamera) { this.camera.fov = this._fov0; } this.camera.near = this._nearPos; this.camera.far = this._farPos; this._cameraMatrixState.copy(this._cameraMatrixState0); this._cameraMatrixState.decompose(this.camera.position, this.camera.quaternion, this.camera.scale); this.camera.up.copy(this._up0); this.camera.updateMatrix(); this.camera.updateProjectionMatrix(); this._gizmoMatrixState.copy(this._gizmoMatrixState0); this._gizmoMatrixState0.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale); this._gizmos.updateMatrix(); const tbRadius = this.calculateTbRadius(this.camera); if (tbRadius !== void 0) { this._tbRadius = tbRadius; } this.makeGizmos(this._gizmos.position, this._tbRadius); this.camera.lookAt(this._gizmos.position); this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_changeEvent2); } }); __publicField18(this, "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; }); __publicField18(this, "copyState", () => { if (this.camera) { const state = JSON.stringify( this.camera instanceof OrthographicCamera ? { arcballState: { cameraFar: this.camera.far, cameraMatrix: this.camera.matrix, cameraNear: this.camera.near, cameraUp: this.camera.up, cameraZoom: this.camera.zoom, gizmoMatrix: this._gizmos.matrix } } : { arcballState: { cameraFar: this.camera.far, cameraFov: this.camera.fov, cameraMatrix: this.camera.matrix, cameraNear: this.camera.near, cameraUp: this.camera.up, cameraZoom: this.camera.zoom, gizmoMatrix: this._gizmos.matrix } } ); navigator.clipboard.writeText(state); } }); __publicField18(this, "pasteState", () => { const self2 = this; navigator.clipboard.readText().then(function resolved(value) { self2.setStateFromJSON(value); }); }); __publicField18(this, "saveState", () => { if (!this.camera) return; this._cameraMatrixState0.copy(this.camera.matrix); this._gizmoMatrixState0.copy(this._gizmos.matrix); this._nearPos = this.camera.near; this._farPos = this.camera.far; this._zoom0 = this.camera.zoom; this._up0.copy(this.camera.up); if (this.camera instanceof PerspectiveCamera) { this._fov0 = this.camera.fov; } }); __publicField18(this, "applyScale", (size2, point, scaleGizmos = true) => { if (!this.camera) return; const scalePoint = point.clone(); let sizeInverse = 1 / size2; if (this.camera instanceof OrthographicCamera) { this.camera.zoom = this._zoomState; this.camera.zoom *= size2; if (this.camera.zoom > this.maxZoom) { this.camera.zoom = this.maxZoom; sizeInverse = this._zoomState / this.maxZoom; } else if (this.camera.zoom < this.minZoom) { this.camera.zoom = this.minZoom; sizeInverse = this._zoomState / this.minZoom; } this.camera.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); scalePoint.sub(this._v3_1); const amount = scalePoint.clone().multiplyScalar(sizeInverse); scalePoint.sub(amount); this._m4_1.makeTranslation(scalePoint.x, scalePoint.y, scalePoint.z); this._m4_2.premultiply(this._m4_1); this.setTransformationMatrices(this._m4_1, this._m4_2); return _transformation; } if (this.camera instanceof PerspectiveCamera) { this._v3_1.setFromMatrixPosition(this._cameraMatrixState); this._v3_2.setFromMatrixPosition(this._gizmoMatrixState); let distance3 = this._v3_1.distanceTo(scalePoint); let amount = distance3 - distance3 * sizeInverse; const newDistance = distance3 - amount; if (newDistance < this.minDistance) { sizeInverse = this.minDistance / distance3; amount = distance3 - distance3 * sizeInverse; } else if (newDistance > this.maxDistance) { sizeInverse = this.maxDistance / distance3; amount = distance3 - distance3 * sizeInverse; } let direction2 = scalePoint.clone().sub(this._v3_1).normalize().multiplyScalar(amount); this._m4_1.makeTranslation(direction2.x, direction2.y, direction2.z); if (scaleGizmos) { const pos = this._v3_2; distance3 = pos.distanceTo(scalePoint); amount = distance3 - distance3 * sizeInverse; direction2 = scalePoint.clone().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(direction2.x, direction2.y, direction2.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; } }); __publicField18(this, "setFov", (value) => { if (this.camera instanceof PerspectiveCamera) { this.camera.fov = MathUtils.clamp(value, this.minFov, this.maxFov); this.camera.updateProjectionMatrix(); } }); __publicField18(this, "setTarget", (x, y, z) => { if (this.camera) { this.target.set(x, y, z); this._gizmos.position.set(x, y, z); const tbRadius = this.calculateTbRadius(this.camera); if (tbRadius !== void 0) { this._tbRadius = tbRadius; } this.makeGizmos(this.target, this._tbRadius); this.camera.lookAt(this.target); } }); __publicField18(this, "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; }); __publicField18(this, "unprojectOnObj", (cursor, camera2) => { if (!this.scene) return null; const raycaster = new Raycaster(); raycaster.near = camera2.near; raycaster.far = camera2.far; raycaster.setFromCamera(cursor, camera2); const intersect = raycaster.intersectObjects(this.scene.children, true); for (let i4 = 0; i4 < intersect.length; i4++) { if (intersect[i4].object.uuid != this._gizmos.uuid && intersect[i4].face) { return intersect[i4].point.clone(); } } return null; }); __publicField18(this, "unprojectOnTbSurface", (camera2, cursorX, cursorY, canvas, tbRadius) => { if (camera2 instanceof 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; } if (camera2 instanceof 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(camera2.projectionMatrixInverse); const rayDir = this._v3_1.clone().normalize(); const cameraGizmoDistance = camera2.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 q = cameraGizmoDistance; let a6 = Math.pow(m, 2) + 1; let b5 = 2 * m * q; let c2 = Math.pow(q, 2) - radius2; let delta = Math.pow(b5, 2) - 4 * a6 * c2; if (delta >= 0) { this._v2_1.setX((-b5 - Math.sqrt(delta)) / (2 * a6)); this._v2_1.setY(m * this._v2_1.x + q); 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; } } a6 = m; b5 = q; c2 = -radius2 * 0.5; delta = Math.pow(b5, 2) - 4 * a6 * c2; this._v2_1.setX((-b5 - Math.sqrt(delta)) / (2 * a6)); this._v2_1.setY(m * this._v2_1.x + q); 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; } }); __publicField18(this, "unprojectOnTbPlane", (camera2, cursorX, cursorY, canvas, initialDistance = false) => { if (camera2 instanceof 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(); } if (camera2 instanceof 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(camera2.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 = camera2.position.distanceTo(this._gizmos.position); } if (l2 == 0) { rayDir.set(0, 0, 0); return rayDir; } const m = h / l2; const q = cameraGizmoDistance; const x = -q / m; const rayLength = Math.sqrt(Math.pow(q, 2) + Math.pow(x, 2)); rayDir.multiplyScalar(rayLength); rayDir.z = 0; return rayDir; } }); __publicField18(this, "updateMatrixState", () => { if (!this.camera) return; this._cameraMatrixState.copy(this.camera.matrix); this._gizmoMatrixState.copy(this._gizmos.matrix); if (this.camera instanceof OrthographicCamera) { this._cameraProjectionState.copy(this.camera.projectionMatrix); this.camera.updateProjectionMatrix(); this._zoomState = this.camera.zoom; } if (this.camera instanceof PerspectiveCamera) { this._fovState = this.camera.fov; } }); __publicField18(this, "updateTbState", (newState, updateMatrices) => { this._state = newState; if (updateMatrices) { this.updateMatrixState(); } }); __publicField18(this, "update", () => { const EPS2 = 1e-6; if (!this.target.equals(this._currentTarget) && this.camera) { this._gizmos.position.set(this.target.x, this.target.y, this.target.z); const tbRadius = this.calculateTbRadius(this.camera); if (tbRadius !== void 0) { this._tbRadius = tbRadius; } this.makeGizmos(this.target, this._tbRadius); this._currentTarget.copy(this.target); } if (!this.camera) return; if (this.camera instanceof OrthographicCamera) { if (this.camera.zoom > this.maxZoom || this.camera.zoom < this.minZoom) { const newZoom = MathUtils.clamp(this.camera.zoom, this.minZoom, this.maxZoom); this.applyTransformMatrix(this.applyScale(newZoom / this.camera.zoom, this._gizmos.position, true)); } } if (this.camera instanceof PerspectiveCamera) { const distance3 = this.camera.position.distanceTo(this._gizmos.position); if (distance3 > this.maxDistance + EPS2 || distance3 < this.minDistance - EPS2) { const newDistance = MathUtils.clamp(distance3, this.minDistance, this.maxDistance); this.applyTransformMatrix(this.applyScale(newDistance / distance3, this._gizmos.position)); this.updateMatrixState(); } if (this.camera.fov < this.minFov || this.camera.fov > this.maxFov) { this.camera.fov = MathUtils.clamp(this.camera.fov, this.minFov, this.maxFov); this.camera.updateProjectionMatrix(); } const oldRadius = this._tbRadius; const tbRadius = this.calculateTbRadius(this.camera); if (tbRadius !== void 0) { this._tbRadius = tbRadius; } if (oldRadius < this._tbRadius - EPS2 || oldRadius > this._tbRadius + EPS2) { const scale5 = (this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z) / 3; const newRadius = this._tbRadius / scale5; 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) { const child = this._gizmos.children[gizmo]; child.geometry = curveGeometry; } } } this.camera.lookAt(this._gizmos.position); }); __publicField18(this, "setStateFromJSON", (json) => { const state = JSON.parse(json); if (state.arcballState && this.camera) { this._cameraMatrixState.fromArray(state.arcballState.cameraMatrix.elements); this._cameraMatrixState.decompose(this.camera.position, this.camera.quaternion, this.camera.scale); this.camera.up.copy(state.arcballState.cameraUp); this.camera.near = state.arcballState.cameraNear; this.camera.far = state.arcballState.cameraFar; this.camera.zoom = state.arcballState.cameraZoom; if (this.camera instanceof PerspectiveCamera) { this.camera.fov = state.arcballState.cameraFov; } this._gizmoMatrixState.fromArray(state.arcballState.gizmoMatrix.elements); this._gizmoMatrixState.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale); this.camera.updateMatrix(); this.camera.updateProjectionMatrix(); this._gizmos.updateMatrix(); const tbRadius = this.calculateTbRadius(this.camera); if (tbRadius !== void 0) { this._tbRadius = tbRadius; } const gizmoTmp = new Matrix4().copy(this._gizmoMatrixState0); this.makeGizmos(this._gizmos.position, this._tbRadius); this._gizmoMatrixState0.copy(gizmoTmp); this.camera.lookAt(this._gizmos.position); this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_changeEvent2); } }); this.camera = null; this.domElement = domElement; this.scene = scene; 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._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._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.enabled = true; this.enablePan = true; this.enableRotate = true; this.enableZoom = true; this.minDistance = 0; this.maxDistance = Infinity; this.minZoom = 0; this.maxZoom = Infinity; this.target = new Vector3(0, 0, 0); this._currentTarget = new Vector3(0, 0, 0); this._tbRadius = 1; this._state = STATE.IDLE; this.setCamera(camera); if (this.scene) { this.scene.add(this._gizmos); } this._devPxRatio = window.devicePixelRatio; this.initializeMouseActions(); if (this.domElement) this.connect(this.domElement); window.addEventListener("resize", this.onWindowResize); } /** * Apply a transformation matrix, to the camera and gizmos * @param {Object} transformation Object containing matrices to apply to camera and gizmos */ applyTransformMatrix(transformation) { if ((transformation == null ? void 0 : transformation.camera) && this.camera) { this._m4_1.copy(this._cameraMatrixState).premultiply(transformation.camera); this._m4_1.decompose(this.camera.position, this.camera.quaternion, this.camera.scale); this.camera.updateMatrix(); if (this._state == STATE.ROTATE || this._state == STATE.ZROTATE || this._state == STATE.ANIMATION_ROTATE) { this.camera.up.copy(this._upState).applyQuaternion(this.camera.quaternion); } } if (transformation == null ? void 0 : transformation.gizmos) { 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.camera) { const tbRadius = this.calculateTbRadius(this.camera); if (tbRadius !== void 0) { this._tbRadius = tbRadius; } if (this.adjustNearFar) { const cameraDistance = this.camera.position.distanceTo(this._gizmos.position); const bb2 = new Box3(); bb2.setFromObject(this._gizmos); const sphere = new Sphere(); bb2.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.camera.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.camera.far = cameraDistance - minFarPos; this.camera.updateProjectionMatrix(); } else { let update2 = false; if (this.camera.near != this._initialNear) { this.camera.near = this._initialNear; update2 = true; } if (this.camera.far != this._initialFar) { this.camera.far = this._initialFar; update2 = true; } if (update2) { this.camera.updateProjectionMatrix(); } } } } /** * Set gizmos visibility * @param {Boolean} value Value of gizmos visibility */ setGizmosVisible(value) { this._gizmos.visible = value; this.dispatchEvent(_changeEvent2); } /** * Set values in transformation object * @param {Matrix4} camera Transformation to be applied to the camera * @param {Matrix4} gizmos Transformation to be applied to gizmos */ setTransformationMatrices(camera = null, gizmos = null) { if (camera) { if (_transformation.camera) { _transformation.camera.copy(camera); } else { _transformation.camera = camera.clone(); } } else { _transformation.camera = null; } if (gizmos) { if (_transformation.gizmos) { _transformation.gizmos.copy(gizmos); } else { _transformation.gizmos = gizmos.clone(); } } else { _transformation.gizmos = null; } } }; // node_modules/three-stdlib/controls/FlyControls.js var __defProp19 = Object.defineProperty; var __defNormalProp19 = (obj, key, value) => key in obj ? __defProp19(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField19 = (obj, key, value) => { __defNormalProp19(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; function contextmenu(event) { event.preventDefault(); } var FlyControls = class extends EventDispatcher2 { constructor(object, domElement) { super(); __publicField19(this, "object"); __publicField19(this, "domElement", null); __publicField19(this, "movementSpeed", 1); __publicField19(this, "rollSpeed", 5e-3); __publicField19(this, "dragToLook", false); __publicField19(this, "autoForward", false); __publicField19(this, "changeEvent", { type: "change" }); __publicField19(this, "EPS", 1e-6); __publicField19(this, "tmpQuaternion", new Quaternion()); __publicField19(this, "mouseStatus", 0); __publicField19(this, "movementSpeedMultiplier", 1); __publicField19(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 }); __publicField19(this, "moveVector", new Vector3(0, 0, 0)); __publicField19(this, "rotationVector", new Vector3(0, 0, 0)); __publicField19(this, "keydown", (event) => { if (event.altKey) { 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(); }); __publicField19(this, "keyup", (event) => { 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(); }); __publicField19(this, "pointerdown", (event) => { if (this.dragToLook) { this.mouseStatus++; } else { switch (event.button) { case 0: this.moveState.forward = 1; break; case 2: this.moveState.back = 1; break; } this.updateMovementVector(); } }); __publicField19(this, "pointermove", (event) => { if (!this.dragToLook || this.mouseStatus > 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(); } }); __publicField19(this, "pointerup", (event) => { if (this.dragToLook) { this.mouseStatus--; 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(); }); __publicField19(this, "lastQuaternion", new Quaternion()); __publicField19(this, "lastPosition", new Vector3()); __publicField19(this, "update", (delta) => { const moveMult = delta * this.movementSpeed; const rotMult = delta * this.rollSpeed; this.object.translateX(this.moveVector.x * moveMult); this.object.translateY(this.moveVector.y * moveMult); this.object.translateZ(this.moveVector.z * moveMult); this.tmpQuaternion.set(this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1).normalize(); this.object.quaternion.multiply(this.tmpQuaternion); if (this.lastPosition.distanceToSquared(this.object.position) > this.EPS || 8 * (1 - this.lastQuaternion.dot(this.object.quaternion)) > this.EPS) { this.dispatchEvent(this.changeEvent); this.lastQuaternion.copy(this.object.quaternion); this.lastPosition.copy(this.object.position); } }); __publicField19(this, "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; }); __publicField19(this, "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; }); __publicField19(this, "getContainerDimensions", () => { if (this.domElement != document && !(this.domElement instanceof 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] }; } }); __publicField19(this, "connect", (domElement2) => { this.domElement = domElement2; if (!(domElement2 instanceof Document)) { domElement2.setAttribute("tabindex", -1); } this.domElement.addEventListener("contextmenu", contextmenu); this.domElement.addEventListener("pointermove", this.pointermove); this.domElement.addEventListener("pointerdown", this.pointerdown); this.domElement.addEventListener("pointerup", this.pointerup); window.addEventListener("keydown", this.keydown); window.addEventListener("keyup", this.keyup); }); __publicField19(this, "dispose", () => { this.domElement.removeEventListener("contextmenu", contextmenu); this.domElement.removeEventListener("pointermove", this.pointermove); this.domElement.removeEventListener("pointerdown", this.pointerdown); this.domElement.removeEventListener("pointerup", this.pointerup); window.removeEventListener("keydown", this.keydown); window.removeEventListener("keyup", this.keyup); }); this.object = object; if (domElement !== void 0) this.connect(domElement); this.updateMovementVector(); this.updateRotationVector(); } }; // node_modules/three-stdlib/postprocessing/Pass.js var __defProp20 = Object.defineProperty; var __defNormalProp20 = (obj, key, value) => key in obj ? __defProp20(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField20 = (obj, key, value) => { __defNormalProp20(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Pass = class { constructor() { __publicField20(this, "enabled", true); __publicField20(this, "needsSwap", true); __publicField20(this, "clear", false); __publicField20(this, "renderToScreen", false); } setSize(width, height) { } render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) { console.error("THREE.Pass: .render() must be implemented in derived pass."); } dispose() { } }; var FullScreenQuad = class { constructor(material) { __publicField20(this, "camera", new OrthographicCamera(-1, 1, 1, -1, 0, 1)); __publicField20(this, "geometry", new PlaneGeometry(2, 2)); __publicField20(this, "mesh"); this.mesh = new Mesh(this.geometry, material); } get material() { return this.mesh.material; } set material(value) { this.mesh.material = value; } dispose() { this.mesh.geometry.dispose(); } render(renderer) { renderer.render(this.mesh, this.camera); } }; // node_modules/three-stdlib/postprocessing/ShaderPass.js var __defProp21 = Object.defineProperty; var __defNormalProp21 = (obj, key, value) => key in obj ? __defProp21(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField21 = (obj, key, value) => { __defNormalProp21(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var ShaderPass = class extends Pass { constructor(shader, textureID = "tDiffuse") { super(); __publicField21(this, "textureID"); __publicField21(this, "uniforms"); __publicField21(this, "material"); __publicField21(this, "fsQuad"); this.textureID = textureID; if (shader instanceof ShaderMaterial) { this.uniforms = shader.uniforms; this.material = shader; } else { this.uniforms = UniformsUtils.clone(shader.uniforms); this.material = new ShaderMaterial({ defines: Object.assign({}, shader.defines), uniforms: this.uniforms, vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }); } this.fsQuad = new FullScreenQuad(this.material); } render(renderer, writeBuffer, readBuffer) { if (this.uniforms[this.textureID]) { this.uniforms[this.textureID].value = readBuffer.texture; } this.fsQuad.material = this.material; if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); this.fsQuad.render(renderer); } } dispose() { this.fsQuad.dispose(); this.material.dispose(); } }; // node_modules/three-stdlib/shaders/HalftoneShader.js var 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-stdlib/shaders/SMAAShader.js var 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 = { 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 = { 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-stdlib/shaders/CopyShader.js var 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-stdlib/shaders/SSAOShader.js var SSAOShader = { defines: { PERSPECTIVE_CAMERA: 1, KERNEL_SIZE: 32 }, uniforms: { tDiffuse: { value: null }, 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 sampler2D tDiffuse; uniform sampler2D tNormal; uniform 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 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 ); 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 = texture2D( tNoise, vUv * noiseScale ).xyz; // 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 = { 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 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 = { 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 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-stdlib/postprocessing/SSAOPass.js var __defProp22 = Object.defineProperty; var __defNormalProp22 = (obj, key, value) => key in obj ? __defProp22(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField22 = (obj, key, value) => { __defNormalProp22(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var SSAOPass = (() => { const _SSAOPass = class extends Pass { constructor(scene, camera, width, height) { super(); this.width = width !== void 0 ? width : 512; this.height = height !== void 0 ? height : 512; this.clear = true; this.camera = camera; this.scene = scene; this.kernelRadius = 8; this.kernelSize = 32; this.kernel = []; this.noiseTexture = null; this.output = 0; this.minDistance = 5e-3; this.maxDistance = 0.1; this._visibilityCache = /* @__PURE__ */ new Map(); this.generateSampleKernel(); this.generateRandomKernelRotations(); const depthTexture = new DepthTexture(); depthTexture.format = DepthStencilFormat; depthTexture.type = UnsignedInt248Type; this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height); this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { minFilter: NearestFilter, magFilter: NearestFilter, depthTexture }); this.ssaoRenderTarget = new WebGLRenderTarget(this.width, this.height); this.blurRenderTarget = this.ssaoRenderTarget.clone(); if (SSAOShader === void 0) { console.error("THREE.SSAOPass: The pass relies on SSAOShader."); } this.ssaoMaterial = new ShaderMaterial({ defines: Object.assign({}, SSAOShader.defines), uniforms: UniformsUtils.clone(SSAOShader.uniforms), vertexShader: SSAOShader.vertexShader, fragmentShader: SSAOShader.fragmentShader, blending: NoBlending }); this.ssaoMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; 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(); } dispose() { this.beautyRenderTarget.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(); } render(renderer, writeBuffer) { renderer.setRenderTarget(this.beautyRenderTarget); renderer.clear(); renderer.render(this.scene, this.camera); this.overrideVisibility(); this.renderOverride(renderer, 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(renderer, this.ssaoMaterial, this.ssaoRenderTarget); this.renderPass(renderer, 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(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); break; case _SSAOPass.OUTPUT.Blur: this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; this.copyMaterial.blending = NoBlending; this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); break; case _SSAOPass.OUTPUT.Beauty: this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; this.copyMaterial.blending = NoBlending; this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); break; case _SSAOPass.OUTPUT.Depth: this.renderPass(renderer, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); break; case _SSAOPass.OUTPUT.Normal: this.copyMaterial.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; this.copyMaterial.blending = NoBlending; this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); break; case _SSAOPass.OUTPUT.Default: this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; this.copyMaterial.blending = NoBlending; this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; this.copyMaterial.blending = CustomBlending; this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); break; default: console.warn("THREE.SSAOPass: Unknown output type."); } } renderPass(renderer, passMaterial, renderTarget, clearColor, clearAlpha) { renderer.getClearColor(this.originalClearColor); const originalClearAlpha = renderer.getClearAlpha(); const originalAutoClear = renderer.autoClear; renderer.setRenderTarget(renderTarget); renderer.autoClear = false; if (clearColor !== void 0 && clearColor !== null) { renderer.setClearColor(clearColor); renderer.setClearAlpha(clearAlpha || 0); renderer.clear(); } this.fsQuad.material = passMaterial; this.fsQuad.render(renderer); renderer.autoClear = originalAutoClear; renderer.setClearColor(this.originalClearColor); renderer.setClearAlpha(originalClearAlpha); } renderOverride(renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { renderer.getClearColor(this.originalClearColor); const originalClearAlpha = renderer.getClearAlpha(); const originalAutoClear = renderer.autoClear; renderer.setRenderTarget(renderTarget); renderer.autoClear = false; clearColor = overrideMaterial.clearColor || clearColor; clearAlpha = overrideMaterial.clearAlpha || clearAlpha; if (clearColor !== void 0 && clearColor !== null) { renderer.setClearColor(clearColor); renderer.setClearAlpha(clearAlpha || 0); renderer.clear(); } this.scene.overrideMaterial = overrideMaterial; renderer.render(this.scene, this.camera); this.scene.overrideMaterial = null; renderer.autoClear = originalAutoClear; renderer.setClearColor(this.originalClearColor); renderer.setClearAlpha(originalClearAlpha); } setSize(width, height) { this.width = width; this.height = height; this.beautyRenderTarget.setSize(width, height); this.ssaoRenderTarget.setSize(width, height); this.normalRenderTarget.setSize(width, height); this.blurRenderTarget.setSize(width, height); this.ssaoMaterial.uniforms["resolution"].value.set(width, height); this.ssaoMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); this.ssaoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); this.blurMaterial.uniforms["resolution"].value.set(width, height); } generateSampleKernel() { const kernelSize = this.kernelSize; const kernel = this.kernel; for (let i4 = 0; i4 < kernelSize; i4++) { const sample = new Vector3(); sample.x = Math.random() * 2 - 1; sample.y = Math.random() * 2 - 1; sample.z = Math.random(); sample.normalize(); let scale5 = i4 / kernelSize; scale5 = MathUtils.lerp(0.1, 1, scale5 * scale5); sample.multiplyScalar(scale5); kernel.push(sample); } } generateRandomKernelRotations() { const width = 4, height = 4; if (SimplexNoise === void 0) { console.error("THREE.SSAOPass: The pass relies on SimplexNoise."); } const simplex = new SimplexNoise(); const size2 = width * height; const data = new Float32Array(size2); for (let i4 = 0; i4 < size2; i4++) { const x = Math.random() * 2 - 1; const y = Math.random() * 2 - 1; const z = 0; data[i4] = simplex.noise3d(x, y, z); } this.noiseTexture = new DataTexture(data, width, height, 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(); } }; let SSAOPass2 = _SSAOPass; __publicField22(SSAOPass2, "OUTPUT", { Default: 0, SSAO: 1, Blur: 2, Beauty: 3, Depth: 4, Normal: 5 }); return SSAOPass2; })(); // node_modules/three-stdlib/shaders/LuminosityHighPassShader.js var LuminosityHighPassShader = { shaderID: "luminosityHighPass", 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 ); vec3 luma = vec3( 0.299, 0.587, 0.114 ); float v = dot( texel.xyz, luma ); vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); gl_FragColor = mix( outputColor, texel, alpha ); } ` ) }; // node_modules/three-stdlib/postprocessing/UnrealBloomPass.js var __defProp23 = Object.defineProperty; var __defNormalProp23 = (obj, key, value) => key in obj ? __defProp23(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField23 = (obj, key, value) => { __defNormalProp23(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var UnrealBloomPass = (() => { const _UnrealBloomPass = class extends Pass { constructor(resolution, strength, radius, threshold) { super(); this.strength = strength !== void 0 ? strength : 1; 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.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 i4 = 0; i4 < this.nMips; i4++) { const renderTargetHorizonal = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); renderTargetHorizonal.texture.name = "UnrealBloomPass.h" + i4; renderTargetHorizonal.texture.generateMipmaps = false; this.renderTargetsHorizontal.push(renderTargetHorizonal); const renderTargetVertical = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); renderTargetVertical.texture.name = "UnrealBloomPass.v" + i4; 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, defines: {} }); 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 i4 = 0; i4 < this.nMips; i4++) { this.separableBlurMaterials.push(this.getSeperableBlurMaterial(kernelSizeArray[i4])); this.separableBlurMaterials[i4].uniforms["texSize"].value = new Vector2(resx, 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; this.compositeMaterial.needsUpdate = true; 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; const copyShader = CopyShader; this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); this.copyUniforms["opacity"].value = 1; this.materialCopy = new ShaderMaterial({ uniforms: this.copyUniforms, vertexShader: copyShader.vertexShader, fragmentShader: copyShader.fragmentShader, blending: AdditiveBlending, depthTest: false, depthWrite: false, transparent: true }); this.enabled = true; this.needsSwap = false; this._oldClearColor = new Color(); this.oldClearAlpha = 1; this.basic = new MeshBasicMaterial(); this.fsQuad = new FullScreenQuad(null); } dispose() { for (let i4 = 0; i4 < this.renderTargetsHorizontal.length; i4++) { this.renderTargetsHorizontal[i4].dispose(); } for (let i4 = 0; i4 < this.renderTargetsVertical.length; i4++) { this.renderTargetsVertical[i4].dispose(); } this.renderTargetBright.dispose(); for (let i4 = 0; i4 < this.separableBlurMaterials.length; i4++) { this.separableBlurMaterials[i4].dispose(); } this.compositeMaterial.dispose(); this.materialCopy.dispose(); this.basic.dispose(); this.fsQuad.dispose(); } setSize(width, height) { let resx = Math.round(width / 2); let resy = Math.round(height / 2); this.renderTargetBright.setSize(resx, resy); for (let i4 = 0; i4 < this.nMips; i4++) { this.renderTargetsHorizontal[i4].setSize(resx, resy); this.renderTargetsVertical[i4].setSize(resx, resy); this.separableBlurMaterials[i4].uniforms["texSize"].value = new Vector2(resx, resy); resx = Math.round(resx / 2); resy = Math.round(resy / 2); } } render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) { renderer.getClearColor(this._oldClearColor); this.oldClearAlpha = renderer.getClearAlpha(); const oldAutoClear = renderer.autoClear; renderer.autoClear = false; renderer.setClearColor(this.clearColor, 0); if (maskActive) renderer.state.buffers.stencil.setTest(false); if (this.renderToScreen) { this.fsQuad.material = this.basic; this.basic.map = readBuffer.texture; renderer.setRenderTarget(null); renderer.clear(); this.fsQuad.render(renderer); } this.highPassUniforms["tDiffuse"].value = readBuffer.texture; this.highPassUniforms["luminosityThreshold"].value = this.threshold; this.fsQuad.material = this.materialHighPassFilter; renderer.setRenderTarget(this.renderTargetBright); renderer.clear(); this.fsQuad.render(renderer); let inputRenderTarget = this.renderTargetBright; for (let i4 = 0; i4 < this.nMips; i4++) { this.fsQuad.material = this.separableBlurMaterials[i4]; this.separableBlurMaterials[i4].uniforms["colorTexture"].value = inputRenderTarget.texture; this.separableBlurMaterials[i4].uniforms["direction"].value = _UnrealBloomPass.BlurDirectionX; renderer.setRenderTarget(this.renderTargetsHorizontal[i4]); renderer.clear(); this.fsQuad.render(renderer); this.separableBlurMaterials[i4].uniforms["colorTexture"].value = this.renderTargetsHorizontal[i4].texture; this.separableBlurMaterials[i4].uniforms["direction"].value = _UnrealBloomPass.BlurDirectionY; renderer.setRenderTarget(this.renderTargetsVertical[i4]); renderer.clear(); this.fsQuad.render(renderer); inputRenderTarget = this.renderTargetsVertical[i4]; } 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; renderer.setRenderTarget(this.renderTargetsHorizontal[0]); renderer.clear(); this.fsQuad.render(renderer); this.fsQuad.material = this.materialCopy; this.copyUniforms["tDiffuse"].value = this.renderTargetsHorizontal[0].texture; if (maskActive) renderer.state.buffers.stencil.setTest(true); if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(readBuffer); this.fsQuad.render(renderer); } renderer.setClearColor(this._oldClearColor, this.oldClearAlpha); renderer.autoClear = oldAutoClear; } getSeperableBlurMaterial(kernelRadius) { return new ShaderMaterial({ defines: { KERNEL_RADIUS: kernelRadius, SIGMA: kernelRadius }, uniforms: { colorTexture: { value: null }, texSize: { value: new Vector2(0.5, 0.5) }, direction: { value: new Vector2(0.5, 0.5) } }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: `#include varying vec2 vUv; uniform sampler2D colorTexture; uniform vec2 texSize; uniform vec2 direction; 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 fSigma = float(SIGMA); float weightSum = gaussianPdf(0.0, fSigma); vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum; for( int i = 1; i < KERNEL_RADIUS; i ++ ) { float x = float(i); float w = gaussianPdf(x, fSigma); 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) ); }` }); } }; let UnrealBloomPass2 = _UnrealBloomPass; __publicField23(UnrealBloomPass2, "BlurDirectionX", new Vector2(1, 0)); __publicField23(UnrealBloomPass2, "BlurDirectionY", new Vector2(0, 1)); return UnrealBloomPass2; })(); // node_modules/three-stdlib/shaders/SAOShader.js var SAOShader = { defines: { NUM_SAMPLES: 7, NUM_RINGS: 4, NORMAL_TEXTURE: 0, DIFFUSE_TEXTURE: 0, DEPTH_PACKING: 1, 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 varying vec2 vUv; #if DIFFUSE_TEXTURE == 1 uniform sampler2D tDiffuse; #endif uniform sampler2D tDepth; #if NORMAL_TEXTURE == 1 uniform sampler2D tNormal; #endif 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 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 ) { #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 } 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 ) { #if NORMAL_TEXTURE == 1 return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); #else return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) ); #endif } 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-stdlib/shaders/DepthLimitedBlurShader.js var 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 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 #include 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: (kernelRadius, stdDev) => { const gaussian = (x, stdDev2) => { return Math.exp(-(x * x) / (2 * (stdDev2 * stdDev2))) / (Math.sqrt(2 * Math.PI) * stdDev2); }; const weights = []; for (let i4 = 0; i4 <= kernelRadius; i4++) { weights.push(gaussian(i4, stdDev)); } return weights; }, createSampleOffsets: (kernelRadius, uvIncrement) => { const offsets = []; for (let i4 = 0; i4 <= kernelRadius; i4++) { offsets.push(uvIncrement.clone().multiplyScalar(i4)); } return offsets; }, configure: (shader, kernelRadius, stdDev, uvIncrement) => { shader.defines["KERNEL_RADIUS"] = kernelRadius; shader.uniforms["sampleUvOffsets"].value = BlurShaderUtils.createSampleOffsets(kernelRadius, uvIncrement); shader.uniforms["sampleWeights"].value = BlurShaderUtils.createSampleWeights(kernelRadius, stdDev); shader.needsUpdate = true; } }; // node_modules/three-stdlib/postprocessing/SAOPass.js var __defProp24 = Object.defineProperty; var __defNormalProp24 = (obj, key, value) => key in obj ? __defProp24(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField24 = (obj, key, value) => { __defNormalProp24(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var SAOPass = (() => { class SAOPass2 extends Pass { constructor(scene, camera, useDepthTexture = false, useNormals = false, resolution = new Vector2(256, 256)) { super(); this.scene = scene; this.camera = camera; this.clear = true; this.needsSwap = false; this.supportsDepthTextureExtension = useDepthTexture; this.supportsNormalTexture = useNormals; 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(); this.beautyRenderTarget = this.saoRenderTarget.clone(); this.normalRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { minFilter: NearestFilter, magFilter: NearestFilter, type: HalfFloatType }); this.depthRenderTarget = this.normalRenderTarget.clone(); let depthTexture; if (this.supportsDepthTextureExtension) { depthTexture = new DepthTexture(); depthTexture.type = UnsignedShortType; this.beautyRenderTarget.depthTexture = depthTexture; this.beautyRenderTarget.depthBuffer = true; } this.depthMaterial = new MeshDepthMaterial(); this.depthMaterial.depthPacking = RGBADepthPacking; this.depthMaterial.blending = NoBlending; 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.extensions.derivatives = true; this.saoMaterial.defines["DEPTH_PACKING"] = this.supportsDepthTextureExtension ? 0 : 1; this.saoMaterial.defines["NORMAL_TEXTURE"] = this.supportsNormalTexture ? 1 : 0; this.saoMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; this.saoMaterial.uniforms["tDepth"].value = this.supportsDepthTextureExtension ? depthTexture : this.depthRenderTarget.texture; 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"] = this.supportsDepthTextureExtension ? 0 : 1; this.vBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; this.vBlurMaterial.uniforms["tDiffuse"].value = this.saoRenderTarget.texture; this.vBlurMaterial.uniforms["tDepth"].value = this.supportsDepthTextureExtension ? depthTexture : this.depthRenderTarget.texture; 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"] = this.supportsDepthTextureExtension ? 0 : 1; this.hBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; this.hBlurMaterial.uniforms["tDiffuse"].value = this.blurIntermediateRenderTarget.texture; this.hBlurMaterial.uniforms["tDepth"].value = this.supportsDepthTextureExtension ? depthTexture : this.depthRenderTarget.texture; 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.depthCopy = new ShaderMaterial({ uniforms: UniformsUtils.clone(UnpackDepthRGBAShader.uniforms), vertexShader: UnpackDepthRGBAShader.vertexShader, fragmentShader: UnpackDepthRGBAShader.fragmentShader, blending: NoBlending }); this.fsQuad = new FullScreenQuad(null); } render(renderer, writeBuffer, readBuffer) { if (this.renderToScreen) { this.materialCopy.blending = NoBlending; this.materialCopy.uniforms["tDiffuse"].value = readBuffer.texture; this.materialCopy.needsUpdate = true; this.renderPass(renderer, this.materialCopy, null); } if (this.params.output === 1) { return; } renderer.getClearColor(this._oldClearColor); this.oldClearAlpha = renderer.getClearAlpha(); const oldAutoClear = renderer.autoClear; renderer.autoClear = false; renderer.setRenderTarget(this.depthRenderTarget); renderer.clear(); 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; } renderer.setClearColor(0); renderer.setRenderTarget(this.beautyRenderTarget); renderer.clear(); renderer.render(this.scene, this.camera); if (!this.supportsDepthTextureExtension) { this.renderOverride(renderer, this.depthMaterial, this.depthRenderTarget, 0, 1); } if (this.supportsNormalTexture) { this.renderOverride(renderer, this.normalMaterial, this.normalRenderTarget, 7829503, 1); } this.renderPass(renderer, this.saoMaterial, this.saoRenderTarget, 16777215, 1); if (this.params.saoBlur) { this.renderPass(renderer, this.vBlurMaterial, this.blurIntermediateRenderTarget, 16777215, 1); this.renderPass(renderer, this.hBlurMaterial, this.saoRenderTarget, 16777215, 1); } let outputMaterial = this.materialCopy; if (this.params.output === 3) { if (this.supportsDepthTextureExtension) { this.materialCopy.uniforms["tDiffuse"].value = this.beautyRenderTarget.depthTexture; this.materialCopy.needsUpdate = true; } else { this.depthCopy.uniforms["tDiffuse"].value = this.depthRenderTarget.texture; this.depthCopy.needsUpdate = true; outputMaterial = this.depthCopy; } } else if (this.params.output === 4) { 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 === 0) { outputMaterial.blending = CustomBlending; } else { outputMaterial.blending = NoBlending; } this.renderPass(renderer, outputMaterial, this.renderToScreen ? null : readBuffer); renderer.setClearColor(this._oldClearColor, this.oldClearAlpha); renderer.autoClear = oldAutoClear; } renderPass(renderer, passMaterial, renderTarget, clearColor, clearAlpha) { renderer.getClearColor(this.originalClearColor); const originalClearAlpha = renderer.getClearAlpha(); const originalAutoClear = renderer.autoClear; renderer.setRenderTarget(renderTarget); renderer.autoClear = false; if (clearColor !== void 0 && clearColor !== null) { renderer.setClearColor(clearColor); renderer.setClearAlpha(clearAlpha || 0); renderer.clear(); } this.fsQuad.material = passMaterial; this.fsQuad.render(renderer); renderer.autoClear = originalAutoClear; renderer.setClearColor(this.originalClearColor); renderer.setClearAlpha(originalClearAlpha); } renderOverride(renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { renderer.getClearColor(this.originalClearColor); const originalClearAlpha = renderer.getClearAlpha(); const originalAutoClear = renderer.autoClear; renderer.setRenderTarget(renderTarget); renderer.autoClear = false; clearColor = overrideMaterial.clearColor || clearColor; clearAlpha = overrideMaterial.clearAlpha || clearAlpha; if (clearColor !== void 0 && clearColor !== null) { renderer.setClearColor(clearColor); renderer.setClearAlpha(clearAlpha || 0); renderer.clear(); } this.scene.overrideMaterial = overrideMaterial; renderer.render(this.scene, this.camera); this.scene.overrideMaterial = null; renderer.autoClear = originalAutoClear; renderer.setClearColor(this.originalClearColor); renderer.setClearAlpha(originalClearAlpha); } setSize(width, height) { this.beautyRenderTarget.setSize(width, height); this.saoRenderTarget.setSize(width, height); this.blurIntermediateRenderTarget.setSize(width, height); this.normalRenderTarget.setSize(width, height); this.depthRenderTarget.setSize(width, height); this.saoMaterial.uniforms["size"].value.set(width, height); 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(width, height); this.vBlurMaterial.needsUpdate = true; this.hBlurMaterial.uniforms["size"].value.set(width, height); this.hBlurMaterial.needsUpdate = true; } dispose() { this.saoRenderTarget.dispose(); this.blurIntermediateRenderTarget.dispose(); this.beautyRenderTarget.dispose(); this.normalRenderTarget.dispose(); this.depthRenderTarget.dispose(); this.depthMaterial.dispose(); this.normalMaterial.dispose(); this.saoMaterial.dispose(); this.vBlurMaterial.dispose(); this.hBlurMaterial.dispose(); this.materialCopy.dispose(); this.depthCopy.dispose(); this.fsQuad.dispose(); } } __publicField24(SAOPass2, "OUTPUT", { Beauty: 1, Default: 0, SAO: 2, Depth: 3, Normal: 4 }); return SAOPass2; })(); // node_modules/three-stdlib/postprocessing/MaskPass.js var __defProp25 = Object.defineProperty; var __defNormalProp25 = (obj, key, value) => key in obj ? __defProp25(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField25 = (obj, key, value) => { __defNormalProp25(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var MaskPass = class extends Pass { constructor(scene, camera) { super(); __publicField25(this, "scene"); __publicField25(this, "camera"); __publicField25(this, "inverse"); this.scene = scene; this.camera = camera; this.clear = true; this.needsSwap = false; this.inverse = false; } render(renderer, writeBuffer, readBuffer) { const context12 = renderer.getContext(); const state = renderer.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(context12.REPLACE, context12.REPLACE, context12.REPLACE); state.buffers.stencil.setFunc(context12.ALWAYS, writeValue, 4294967295); state.buffers.stencil.setClear(clearValue); state.buffers.stencil.setLocked(true); renderer.setRenderTarget(readBuffer); if (this.clear) renderer.clear(); renderer.render(this.scene, this.camera); renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); renderer.render(this.scene, this.camera); state.buffers.color.setLocked(false); state.buffers.depth.setLocked(false); state.buffers.stencil.setLocked(false); state.buffers.stencil.setFunc(context12.EQUAL, 1, 4294967295); state.buffers.stencil.setOp(context12.KEEP, context12.KEEP, context12.KEEP); state.buffers.stencil.setLocked(true); } }; var ClearMaskPass = class extends Pass { constructor() { super(); this.needsSwap = false; } render(renderer) { renderer.state.buffers.stencil.setLocked(false); renderer.state.buffers.stencil.setTest(false); } }; // node_modules/three-stdlib/postprocessing/EffectComposer.js var __defProp26 = Object.defineProperty; var __defNormalProp26 = (obj, key, value) => key in obj ? __defProp26(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField26 = (obj, key, value) => { __defNormalProp26(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var EffectComposer = class { constructor(renderer, renderTarget) { __publicField26(this, "renderer"); __publicField26(this, "_pixelRatio"); __publicField26(this, "_width"); __publicField26(this, "_height"); __publicField26(this, "renderTarget1"); __publicField26(this, "renderTarget2"); __publicField26(this, "writeBuffer"); __publicField26(this, "readBuffer"); __publicField26(this, "renderToScreen"); __publicField26(this, "passes", []); __publicField26(this, "copyPass"); __publicField26(this, "clock"); this.renderer = renderer; if (renderTarget === void 0) { const parameters = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }; const size2 = renderer.getSize(new Vector2()); this._pixelRatio = renderer.getPixelRatio(); this._width = size2.width; this._height = size2.height; renderTarget = new WebGLRenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, parameters ); renderTarget.texture.name = "EffectComposer.rt1"; } else { this._pixelRatio = 1; 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; if (CopyShader === void 0) { console.error("THREE.EffectComposer relies on CopyShader"); } if (ShaderPass === void 0) { console.error("THREE.EffectComposer relies on ShaderPass"); } this.copyPass = new ShaderPass(CopyShader); this.copyPass.material.blending = NoBlending; this.clock = new Clock(); } swapBuffers() { const tmp = this.readBuffer; this.readBuffer = this.writeBuffer; this.writeBuffer = tmp; } addPass(pass) { this.passes.push(pass); pass.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio); } insertPass(pass, index2) { this.passes.splice(index2, 0, pass); pass.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio); } removePass(pass) { const index2 = this.passes.indexOf(pass); if (index2 !== -1) { this.passes.splice(index2, 1); } } isLastEnabledPass(passIndex) { for (let i4 = passIndex + 1; i4 < this.passes.length; i4++) { if (this.passes[i4].enabled) { return false; } } return true; } render(deltaTime) { if (deltaTime === void 0) { deltaTime = this.clock.getDelta(); } const currentRenderTarget = this.renderer.getRenderTarget(); let maskActive = false; const il = this.passes.length; for (let i4 = 0; i4 < il; i4++) { const pass = this.passes[i4]; if (pass.enabled === false) continue; pass.renderToScreen = this.renderToScreen && this.isLastEnabledPass(i4); pass.render(this.renderer, this.writeBuffer, this.readBuffer, deltaTime, maskActive); if (pass.needsSwap) { if (maskActive) { const context12 = this.renderer.getContext(); const stencil = this.renderer.state.buffers.stencil; stencil.setFunc(context12.NOTEQUAL, 1, 4294967295); this.copyPass.render(this.renderer, this.writeBuffer, this.readBuffer, deltaTime); stencil.setFunc(context12.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); } 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; } setSize(width, height) { this._width = width; this._height = height; const effectiveWidth = this._width * this._pixelRatio; const effectiveHeight = this._height * this._pixelRatio; this.renderTarget1.setSize(effectiveWidth, effectiveHeight); this.renderTarget2.setSize(effectiveWidth, effectiveHeight); for (let i4 = 0; i4 < this.passes.length; i4++) { this.passes[i4].setSize(effectiveWidth, effectiveHeight); } } setPixelRatio(pixelRatio) { this._pixelRatio = pixelRatio; this.setSize(this._width, this._height); } dispose() { this.renderTarget1.dispose(); this.renderTarget2.dispose(); this.copyPass.dispose(); } }; // node_modules/three-stdlib/shaders/DotScreenShader.js var 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-stdlib/shaders/SSRShader.js var SSRShader = { defines: { MAX_STEP: 0, isPerspectiveCamera: true, isDistanceAttenuation: true, isFresnel: true, isInfiniteThick: false, isSelective: 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 }, surfDist: { value: 7e-3 }, thickTolerance: { value: 0.03 } }, 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 surfDist; uniform mat4 cameraProjectionMatrix; uniform mat4 cameraInverseProjectionMatrix; uniform float thickTolerance; #include 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 isPerspectiveCamera 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 isSelective 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 isPerspectiveCamera vec3 viewIncidenceDir=normalize(viewPosition); vec3 viewReflectDir=reflect(viewIncidenceDir,viewNormal); #else vec3 viewIncidenceDir=vec3(0,0,-1); vec3 viewReflectDir=reflect(viewIncidenceDir,viewNormal); #endif float maxReflectRayLen=maxDistance/dot(-viewIncidenceDir,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 isPerspectiveCamera 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=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 isPerspectiveCamera // https://www.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)); float sD=surfDist*cW; #else float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z); float sD=surfDist; #endif if(viewReflectRayZ-sD>vZ) continue; #ifdef isInfiniteThick if(viewReflectRayZ+thickTolerance*clipW=0.) continue; float distance=pointPlaneDistance(vP,viewPosition,viewNormal); if(distance>maxDistance) break; #ifdef isDistanceAttenuation float ratio=1.-(distance/maxDistance); float attenuation=ratio*ratio; op=opacity*attenuation; #endif #ifdef isFresnel float fresnel=(dot(viewIncidenceDir,viewReflectDir)+1.)/2.; op*=fresnel; #endif vec4 reflectColor=texture2D(tDiffuse,uv); gl_FragColor.xyz=reflectColor.xyz; gl_FragColor.a=op; break; } } } ` ) }; var 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 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 = { 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-stdlib/postprocessing/SSRPass.js var __defProp27 = Object.defineProperty; var __defNormalProp27 = (obj, key, value) => key in obj ? __defProp27(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField27 = (obj, key, value) => { __defNormalProp27(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var SSRPass = (() => { const _SSRPass = class extends Pass { constructor({ renderer, scene, camera, width, height, selects, bouncing = false, groundReflector }) { super(); this.width = width !== void 0 ? width : 512; this.height = height !== void 0 ? height : 512; this.clear = true; this.renderer = renderer; 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(val) { if (this._selects === val) return; this._selects = val; if (Array.isArray(val)) { 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(val) { if (this._bouncing === val) return; this._bouncing = val; if (val) { 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(val) { if (this._distanceAttenuation === val) return; this._distanceAttenuation = val; this.ssrMaterial.defines.DISTANCE_ATTENUATION = val; this.ssrMaterial.needsUpdate = true; } }); this._fresnel = SSRShader.defines.FRESNEL; Object.defineProperty(this, "fresnel", { get() { return this._fresnel; }, set(val) { if (this._fresnel === val) return; this._fresnel = val; this.ssrMaterial.defines.FRESNEL = val; this.ssrMaterial.needsUpdate = true; } }); this._infiniteThick = SSRShader.defines.INFINITE_THICK; Object.defineProperty(this, "infiniteThick", { get() { return this._infiniteThick; }, set(val) { if (this._infiniteThick === val) return; this._infiniteThick = val; this.ssrMaterial.defines.INFINITE_THICK = val; 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(); } 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(); } render(renderer, writeBuffer) { renderer.setRenderTarget(this.beautyRenderTarget); renderer.clear(); if (this.groundReflector) { this.groundReflector.visible = false; this.groundReflector.doRender(this.renderer, this.scene, this.camera); this.groundReflector.visible = true; } renderer.render(this.scene, this.camera); if (this.groundReflector) this.groundReflector.visible = false; this.renderOverride(renderer, this.normalMaterial, this.normalRenderTarget, 0, 0); if (this.selective) { this.renderMetalness(renderer, 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(renderer, this.ssrMaterial, this.ssrRenderTarget); if (this.blur) { this.renderPass(renderer, this.blurMaterial, this.blurRenderTarget); this.renderPass(renderer, 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(renderer, 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(renderer, this.copyMaterial, this.prevRenderTarget); this.copyMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture; this.copyMaterial.blending = NoBlending; this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); } else { this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; this.copyMaterial.blending = NoBlending; this.renderPass(renderer, 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(renderer, 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(renderer, 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(renderer, this.copyMaterial, this.prevRenderTarget); this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; this.copyMaterial.blending = NormalBlending; this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); } break; case _SSRPass.OUTPUT.Beauty: this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; this.copyMaterial.blending = NoBlending; this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); break; case _SSRPass.OUTPUT.Depth: this.renderPass(renderer, 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(renderer, 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(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); break; default: console.warn("THREE.SSRPass: Unknown output type."); } } renderPass(renderer, passMaterial, renderTarget, clearColor, clearAlpha) { this.originalClearColor.copy(renderer.getClearColor(this.tempColor)); const originalClearAlpha = renderer.getClearAlpha(this.tempColor); const originalAutoClear = renderer.autoClear; renderer.setRenderTarget(renderTarget); renderer.autoClear = false; if (clearColor !== void 0 && clearColor !== null) { renderer.setClearColor(clearColor); renderer.setClearAlpha(clearAlpha || 0); renderer.clear(); } this.fsQuad.material = passMaterial; this.fsQuad.render(renderer); renderer.autoClear = originalAutoClear; renderer.setClearColor(this.originalClearColor); renderer.setClearAlpha(originalClearAlpha); } renderOverride(renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { this.originalClearColor.copy(renderer.getClearColor(this.tempColor)); const originalClearAlpha = renderer.getClearAlpha(this.tempColor); const originalAutoClear = renderer.autoClear; renderer.setRenderTarget(renderTarget); renderer.autoClear = false; clearColor = overrideMaterial.clearColor || clearColor; clearAlpha = overrideMaterial.clearAlpha || clearAlpha; if (clearColor !== void 0 && clearColor !== null) { renderer.setClearColor(clearColor); renderer.setClearAlpha(clearAlpha || 0); renderer.clear(); } this.scene.overrideMaterial = overrideMaterial; renderer.render(this.scene, this.camera); this.scene.overrideMaterial = null; renderer.autoClear = originalAutoClear; renderer.setClearColor(this.originalClearColor); renderer.setClearAlpha(originalClearAlpha); } renderMetalness(renderer, overrideMaterial, renderTarget, clearColor, clearAlpha) { this.originalClearColor.copy(renderer.getClearColor(this.tempColor)); const originalClearAlpha = renderer.getClearAlpha(this.tempColor); const originalAutoClear = renderer.autoClear; renderer.setRenderTarget(renderTarget); renderer.autoClear = false; clearColor = overrideMaterial.clearColor || clearColor; clearAlpha = overrideMaterial.clearAlpha || clearAlpha; if (clearColor !== void 0 && clearColor !== null) { renderer.setClearColor(clearColor); renderer.setClearAlpha(clearAlpha || 0); renderer.clear(); } this.scene.traverseVisible((child) => { child._SSRPassBackupMaterial = child.material; if (this._selects.includes(child)) { child.material = this.metalnessOnMaterial; } else { child.material = this.metalnessOffMaterial; } }); renderer.render(this.scene, this.camera); this.scene.traverseVisible((child) => { child.material = child._SSRPassBackupMaterial; }); renderer.autoClear = originalAutoClear; renderer.setClearColor(this.originalClearColor); renderer.setClearAlpha(originalClearAlpha); } setSize(width, height) { this.width = width; this.height = height; this.ssrMaterial.defines.MAX_STEP = Math.sqrt(width * width + height * height); this.ssrMaterial.needsUpdate = true; this.beautyRenderTarget.setSize(width, height); this.prevRenderTarget.setSize(width, height); this.ssrRenderTarget.setSize(width, height); this.normalRenderTarget.setSize(width, height); this.metalnessRenderTarget.setSize(width, height); this.blurRenderTarget.setSize(width, height); this.blurRenderTarget2.setSize(width, height); this.ssrMaterial.uniforms["resolution"].value.set(width, height); this.ssrMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); this.ssrMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); this.blurMaterial.uniforms["resolution"].value.set(width, height); this.blurMaterial2.uniforms["resolution"].value.set(width, height); } }; let SSRPass2 = _SSRPass; __publicField27(SSRPass2, "OUTPUT", { Default: 0, SSR: 1, Beauty: 3, Depth: 4, Normal: 5, Metalness: 7 }); return SSRPass2; })(); // node_modules/three-stdlib/postprocessing/RenderPass.js var __defProp28 = Object.defineProperty; var __defNormalProp28 = (obj, key, value) => key in obj ? __defProp28(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField28 = (obj, key, value) => { __defNormalProp28(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var RenderPass = class extends Pass { constructor(scene, camera, overrideMaterial, clearColor, clearAlpha = 0) { super(); __publicField28(this, "scene"); __publicField28(this, "camera"); __publicField28(this, "overrideMaterial"); __publicField28(this, "clearColor"); __publicField28(this, "clearAlpha"); __publicField28(this, "clearDepth", false); __publicField28(this, "_oldClearColor", new Color()); this.scene = scene; this.camera = camera; this.overrideMaterial = overrideMaterial; this.clearColor = clearColor; this.clearAlpha = clearAlpha; this.clear = true; this.needsSwap = false; } render(renderer, writeBuffer, readBuffer) { let oldAutoClear = renderer.autoClear; renderer.autoClear = false; let oldClearAlpha; let oldOverrideMaterial = null; if (this.overrideMaterial !== void 0) { oldOverrideMaterial = this.scene.overrideMaterial; this.scene.overrideMaterial = this.overrideMaterial; } if (this.clearColor) { renderer.getClearColor(this._oldClearColor); oldClearAlpha = renderer.getClearAlpha(); renderer.setClearColor(this.clearColor, this.clearAlpha); } if (this.clearDepth) { renderer.clearDepth(); } renderer.setRenderTarget(this.renderToScreen ? null : readBuffer); if (this.clear) renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); renderer.render(this.scene, this.camera); if (this.clearColor) { renderer.setClearColor(this._oldClearColor, oldClearAlpha); } if (this.overrideMaterial !== void 0) { this.scene.overrideMaterial = oldOverrideMaterial; } renderer.autoClear = oldAutoClear; } }; // node_modules/three-stdlib/shaders/ConvolutionShader.js var 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; } ` ), buildKernel: function(sigma) { function gauss(x, sigma2) { return Math.exp(-(x * x) / (2 * sigma2 * sigma2)); } const kMaxKernelSize = 25; const kernelSize = Math.min(2 * Math.ceil(sigma * 3) + 1, kMaxKernelSize); const halfWidth = (kernelSize - 1) * 0.5; const values = new Array(kernelSize); let sum = 0; for (let i4 = 0; i4 < kernelSize; ++i4) { values[i4] = gauss(i4 - halfWidth, sigma); sum += values[i4]; } for (let i4 = 0; i4 < kernelSize; ++i4) values[i4] /= sum; return values; } }; // node_modules/three-stdlib/_polyfill/LoaderUtils.js function decodeText(array) { if (typeof TextDecoder !== "undefined") { return new TextDecoder().decode(array); } let s2 = ""; for (let i4 = 0, il = array.length; i4 < il; i4++) { s2 += String.fromCharCode(array[i4]); } try { return decodeURIComponent(escape(s2)); } catch (e2) { return s2; } } // node_modules/three-stdlib/loaders/GLTFLoader.js var SRGBColorSpace2 = "srgb"; var LinearSRGBColorSpace2 = "srgb-linear"; var sRGBEncoding = 3001; var LinearEncoding = 3e3; var GLTFLoader = class extends Loader { 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 GLTFMaterialsDispersionExtension(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 GLTFMaterialsBumpExtension(parser); }); this.register(function(parser) { return new GLTFLightsExtension(parser); }); this.register(function(parser) { return new GLTFMeshoptCompression(parser); }); this.register(function(parser) { return new GLTFMeshGpuInstancing(parser); }); } 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(e2) { if (onError) { onError(e2); } else { console.error(e2); } scope.manager.itemError(url); scope.manager.itemEnd(url); }; const loader2 = new FileLoader(this.manager); loader2.setPath(this.path); loader2.setResponseType("arraybuffer"); loader2.setRequestHeader(this.requestHeader); loader2.setWithCredentials(this.withCredentials); loader2.load( url, function(data) { try { scope.parse( data, resourcePath, function(gltf) { onLoad(gltf); scope.manager.itemEnd(url); }, _onError ); } catch (e2) { _onError(e2); } }, onProgress, _onError ); } setDRACOLoader(dracoLoader2) { this.dracoLoader = dracoLoader2; return this; } setDDSLoader() { throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".'); } setKTX2Loader(ktx2Loader) { this.ktx2Loader = ktx2Loader; return this; } setMeshoptDecoder(meshoptDecoder) { this.meshoptDecoder = meshoptDecoder; return this; } register(callback) { if (this.pluginCallbacks.indexOf(callback) === -1) { this.pluginCallbacks.push(callback); } return this; } unregister(callback) { if (this.pluginCallbacks.indexOf(callback) !== -1) { this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); } return this; } parse(data, path, onLoad, onError) { let json; const extensions2 = {}; const plugins = {}; if (typeof data === "string") { json = JSON.parse(data); } else if (data instanceof ArrayBuffer) { const magic = decodeText(new Uint8Array(data.slice(0, 4))); if (magic === BINARY_EXTENSION_HEADER_MAGIC) { try { extensions2[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data); } catch (error) { if (onError) onError(error); return; } json = JSON.parse(extensions2[EXTENSIONS.KHR_BINARY_GLTF].content); } else { json = JSON.parse(decodeText(new Uint8Array(data))); } } else { json = data; } 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 i4 = 0; i4 < this.pluginCallbacks.length; i4++) { const plugin = this.pluginCallbacks[i4](parser); if (!plugin.name) console.error("THREE.GLTFLoader: Invalid plugin found: missing name"); plugins[plugin.name] = plugin; extensions2[plugin.name] = true; } if (json.extensionsUsed) { for (let i4 = 0; i4 < json.extensionsUsed.length; ++i4) { const extensionName = json.extensionsUsed[i4]; const extensionsRequired = json.extensionsRequired || []; switch (extensionName) { case EXTENSIONS.KHR_MATERIALS_UNLIT: extensions2[extensionName] = new GLTFMaterialsUnlitExtension2(); break; case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: extensions2[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader); break; case EXTENSIONS.KHR_TEXTURE_TRANSFORM: extensions2[extensionName] = new GLTFTextureTransformExtension(); break; case EXTENSIONS.KHR_MESH_QUANTIZATION: extensions2[extensionName] = new GLTFMeshQuantizationExtension(); break; default: if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === void 0) { console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".'); } } } } parser.setExtensions(extensions2); parser.setPlugins(plugins); parser.parse(onLoad, onError); } parseAsync(data, path) { const scope = this; return new Promise(function(resolve, reject) { scope.parse(data, path, resolve, reject); }); } }; function GLTFRegistry() { let objects = {}; return { get: function(key) { return objects[key]; }, add: function(key, object) { objects[key] = object; }, remove: function(key) { delete objects[key]; }, 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 extensions2 = json.extensions && json.extensions[this.name] || {}; const lightDefs = extensions2.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], LinearSRGBColorSpace2); 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); lightNode.decay = 2; 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], LinearSRGBColorSpace2); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace2)); } } 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 scale5 = extension.clearcoatNormalTexture.scale; materialParams.clearcoatNormalScale = new Vector2(scale5, scale5); } } return Promise.all(pending); } }; var GLTFMaterialsDispersionExtension = 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], LinearSRGBColorSpace2); } if (extension.sheenRoughnessFactor !== void 0) { materialParams.sheenRoughness = extension.sheenRoughnessFactor; } if (extension.sheenColorTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "sheenColorMap", extension.sheenColorTexture, SRGBColorSpace2)); } 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], LinearSRGBColorSpace2 ); 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], LinearSRGBColorSpace2); if (extension.specularColorTexture !== void 0) { pending.push( parser.assignTexture(materialParams, "specularColorMap", extension.specularColorTexture, SRGBColorSpace2) ); } return Promise.all(pending); } }; var GLTFMaterialsBumpExtension = 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 loader2 = parser.options.ktx2Loader; if (!loader2) { 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, loader2); } }; var GLTFTextureWebPExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.EXT_TEXTURE_WEBP; this.isSupported = null; } loadTexture(textureIndex) { const name = this.name; const parser = this.parser; const json = parser.json; const textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[name]) { return null; } const extension = textureDef.extensions[name]; const source = json.images[extension.source]; let loader2 = parser.textureLoader; if (source.uri) { const handler = parser.options.manager.getHandler(source.uri); if (handler !== null) loader2 = handler; } return this.detectSupport().then(function(isSupported) { if (isSupported) return parser.loadTextureImage(textureIndex, extension.source, loader2); if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) { throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported."); } return parser.loadTexture(textureIndex); }); } detectSupport() { if (!this.isSupported) { this.isSupported = new Promise(function(resolve) { const image = new Image(); image.src = "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA"; image.onload = image.onerror = function() { resolve(image.height === 1); }; }); } return this.isSupported; } }; var GLTFTextureAVIFExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.EXT_TEXTURE_AVIF; this.isSupported = null; } loadTexture(textureIndex) { const name = this.name; const parser = this.parser; const json = parser.json; const textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[name]) { return null; } const extension = textureDef.extensions[name]; const source = json.images[extension.source]; let loader2 = parser.textureLoader; if (source.uri) { const handler = parser.options.manager.getHandler(source.uri); if (handler !== null) loader2 = handler; } return this.detectSupport().then(function(isSupported) { if (isSupported) return parser.loadTextureImage(textureIndex, extension.source, loader2); if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) { throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported."); } return parser.loadTexture(textureIndex); }); } detectSupport() { if (!this.isSupported) { this.isSupported = new Promise(function(resolve) { const image = new Image(); image.src = "data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI="; image.onload = image.onerror = function() { resolve(image.height === 1); }; }); } return this.isSupported; } }; 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 buffer2 = 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 buffer2.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 GLTFMeshGpuInstancing = 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 key in attributesDef) { pending.push( this.parser.getDependency("accessor", attributesDef[key]).then((accessor) => { attributes[key] = accessor; return attributes[key]; }) ); } 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 p2 = new Vector3(); const q = new Quaternion(); const s2 = new Vector3(1, 1, 1); const instancedMesh = new InstancedMesh(mesh.geometry, mesh.material, count); for (let i4 = 0; i4 < count; i4++) { if (attributes.TRANSLATION) { p2.fromBufferAttribute(attributes.TRANSLATION, i4); } if (attributes.ROTATION) { q.fromBufferAttribute(attributes.ROTATION, i4); } if (attributes.SCALE) { s2.fromBufferAttribute(attributes.SCALE, i4); } instancedMesh.setMatrixAt(i4, m.compose(p2, q, s2)); } 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(data) { this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; const headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH); this.header = { magic: decodeText(new Uint8Array(data.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(data, 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(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength); this.content = decodeText(contentArray); } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) { const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice(byteOffset, byteOffset + chunkLength); } chunkIndex += chunkLength; } if (this.content === null) { throw new Error("THREE.GLTFLoader: JSON content not found."); } } }; var GLTFDracoMeshCompressionExtension = class { constructor(json, dracoLoader2) { if (!dracoLoader2) { throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided."); } this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader2; this.dracoLoader.preload(); } decodePrimitive(primitive, parser) { const json = this.json; const dracoLoader2 = 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, reject) { dracoLoader2.decodeDracoFile( bufferView, function(geometry3) { for (const attributeName in geometry3.attributes) { const attribute = geometry3.attributes[attributeName]; const normalized = attributeNormalizedMap[attributeName]; if (normalized !== void 0) attribute.normalized = normalized; } resolve(geometry3); }, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace2, reject ); }); }); } }; var GLTFTextureTransformExtension = class { constructor() { this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } extendTexture(texture, transform) { if ((transform.texCoord === void 0 || transform.texCoord === texture.channel) && transform.offset === void 0 && transform.rotation === void 0 && transform.scale === void 0) { return texture; } texture = texture.clone(); if (transform.texCoord !== void 0) { texture.channel = transform.texCoord; } if (transform.offset !== void 0) { texture.offset.fromArray(transform.offset); } if (transform.rotation !== void 0) { texture.rotation = transform.rotation; } if (transform.scale !== void 0) { texture.repeat.fromArray(transform.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, values = this.sampleValues, valueSize = this.valueSize, offset = index2 * valueSize * 3 + valueSize; for (let i4 = 0; i4 !== valueSize; i4++) { result[i4] = values[offset + i4]; } return result; } interpolate_(i1, t0, t3, t1) { const result = this.resultBuffer; const values = this.sampleValues; const stride = this.valueSize; const stride2 = stride * 2; const stride3 = stride * 3; const td2 = t1 - t0; const p2 = (t3 - t0) / td2; const pp = p2 * p2; const ppp = pp * p2; 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 + p2; for (let i4 = 0; i4 !== stride; i4++) { const p0 = values[offset0 + i4 + stride]; const m0 = values[offset0 + i4 + stride2] * td2; const p1 = values[offset1 + i4 + stride]; const m1 = values[offset1 + i4] * td2; result[i4] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; } return result; } }; var _q4 = new Quaternion(); var GLTFCubicSplineQuaternionInterpolant = class extends GLTFCubicSplineInterpolant { interpolate_(i1, t0, t3, t1) { const result = super.interpolate_(i1, t0, t3, t1); _q4.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", // uv => uv1, 4 uv channels // https://github.com/mrdoob/three.js/pull/25943 // https://github.com/mrdoob/three.js/pull/25788 ...version >= 152 ? { TEXCOORD_0: "uv", TEXCOORD_1: "uv1", TEXCOORD_2: "uv2", TEXCOORD_3: "uv3" } : { TEXCOORD_0: "uv", TEXCOORD_1: "uv2" }, 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 name in objectDef.extensions) { if (knownExtensions[name] === void 0) { object.userData.gltfExtensions = object.userData.gltfExtensions || {}; object.userData.gltfExtensions[name] = objectDef.extensions[name]; } } } 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(geometry3, targets, parser) { let hasMorphPosition = false; let hasMorphNormal = false; let hasMorphColor = false; for (let i4 = 0, il = targets.length; i4 < il; i4++) { const target2 = targets[i4]; if (target2.POSITION !== void 0) hasMorphPosition = true; if (target2.NORMAL !== void 0) hasMorphNormal = true; if (target2.COLOR_0 !== void 0) hasMorphColor = true; if (hasMorphPosition && hasMorphNormal && hasMorphColor) break; } if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) return Promise.resolve(geometry3); const pendingPositionAccessors = []; const pendingNormalAccessors = []; const pendingColorAccessors = []; for (let i4 = 0, il = targets.length; i4 < il; i4++) { const target2 = targets[i4]; if (hasMorphPosition) { const pendingAccessor = target2.POSITION !== void 0 ? parser.getDependency("accessor", target2.POSITION) : geometry3.attributes.position; pendingPositionAccessors.push(pendingAccessor); } if (hasMorphNormal) { const pendingAccessor = target2.NORMAL !== void 0 ? parser.getDependency("accessor", target2.NORMAL) : geometry3.attributes.normal; pendingNormalAccessors.push(pendingAccessor); } if (hasMorphColor) { const pendingAccessor = target2.COLOR_0 !== void 0 ? parser.getDependency("accessor", target2.COLOR_0) : geometry3.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) geometry3.morphAttributes.position = morphPositions; if (hasMorphNormal) geometry3.morphAttributes.normal = morphNormals; if (hasMorphColor) geometry3.morphAttributes.color = morphColors; geometry3.morphTargetsRelative = true; return geometry3; }); } function updateMorphTargets(mesh, meshDef) { mesh.updateMorphTargets(); if (meshDef.weights !== void 0) { for (let i4 = 0, il = meshDef.weights.length; i4 < il; i4++) { mesh.morphTargetInfluences[i4] = meshDef.weights[i4]; } } if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) { const targetNames = meshDef.extras.targetNames; if (mesh.morphTargetInfluences.length === targetNames.length) { mesh.morphTargetDictionary = {}; for (let i4 = 0, il = targetNames.length; i4 < il; i4++) { mesh.morphTargetDictionary[targetNames[i4]] = i4; } } 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 i4 = 0, il = primitiveDef.targets.length; i4 < il; i4++) { geometryKey += ":" + createAttributesKey(primitiveDef.targets[i4]); } } return geometryKey; } function createAttributesKey(attributes) { let attributesKey = ""; const keys = Object.keys(attributes).sort(); for (let i4 = 0, il = keys.length; i4 < il; i4++) { attributesKey += keys[i4] + ":" + attributes[keys[i4]] + ";"; } 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"; return "image/png"; } var _identityMatrix2 = 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 isSafari = false; let isFirefox = false; let firefoxVersion = -1; if (typeof navigator !== "undefined" && typeof navigator.userAgent !== "undefined") { isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) === true; isFirefox = navigator.userAgent.indexOf("Firefox") > -1; firefoxVersion = isFirefox ? navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1; } if (typeof createImageBitmap === "undefined" || isSafari || 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(extensions2) { this.extensions = extensions2; } setPlugins(plugins) { this.plugins = plugins; } parse(onLoad, onError) { const parser = this; const json = this.json; const extensions2 = 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(extensions2, 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. */ _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 i4 = 0, il = joints.length; i4 < il; i4++) { nodeDefs[joints[i4]].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. */ _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. */ _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 [i4, child] of original.children.entries()) { updateMappings(child, clone2.children[i4]); } }; updateMappings(object, ref); ref.name += "_instance_" + cache.uses[index2]++; return ref; } _invokeOne(func) { const extensions2 = Object.values(this.plugins); extensions2.push(this); for (let i4 = 0; i4 < extensions2.length; i4++) { const result = func(extensions2[i4]); if (result) return result; } return null; } _invokeAll(func) { const extensions2 = Object.values(this.plugins); extensions2.unshift(this); const pending = []; for (let i4 = 0; i4 < extensions2.length; i4++) { const result = func(extensions2[i4]); if (result) pending.push(result); } return pending; } /** * Requests the specified dependency asynchronously, with caching. * @param {string} type * @param {number} index * @return {Promise} */ 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. * @param {string} type * @return {Promise>} */ 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 * @param {number} bufferIndex * @return {Promise} */ loadBuffer(bufferIndex) { const bufferDef = this.json.buffers[bufferIndex]; const loader2 = 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, reject) { loader2.load(LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, void 0, function() { reject(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 * @param {number} bufferViewIndex * @return {Promise} */ loadBufferView(bufferViewIndex) { const bufferViewDef = this.json.bufferViews[bufferViewIndex]; return this.getDependency("buffer", bufferViewDef.buffer).then(function(buffer2) { const byteLength = bufferViewDef.byteLength || 0; const byteOffset = bufferViewDef.byteOffset || 0; return buffer2.slice(byteOffset, byteOffset + byteLength); }); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex * @return {Promise} */ 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 ); } for (let i4 = 0, il = sparseIndices.length; i4 < il; i4++) { const index2 = sparseIndices[i4]; bufferAttribute.setX(index2, sparseValues[i4 * itemSize]); if (itemSize >= 2) bufferAttribute.setY(index2, sparseValues[i4 * itemSize + 1]); if (itemSize >= 3) bufferAttribute.setZ(index2, sparseValues[i4 * itemSize + 2]); if (itemSize >= 4) bufferAttribute.setW(index2, sparseValues[i4 * itemSize + 3]); if (itemSize >= 5) throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute."); } } return bufferAttribute; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * @param {number} textureIndex * @return {Promise} */ 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 loader2 = this.textureLoader; if (sourceDef.uri) { const handler = options.manager.getHandler(sourceDef.uri); if (handler !== null) loader2 = handler; } return this.loadTextureImage(textureIndex, sourceIndex, loader2); } loadTextureImage(textureIndex, sourceIndex, loader2) { 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, loader2).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; parser.associations.set(texture, { textures: textureIndex }); return texture; }).catch(function() { return null; }); this.textureCache[cacheKey] = promise; return promise; } loadImageSource(sourceIndex, loader2) { 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, reject) { let onLoad = resolve; if (loader2.isImageBitmapLoader === true) { onLoad = function(imageBitmap) { const texture = new Texture(imageBitmap); texture.needsUpdate = true; resolve(texture); }; } loader2.load(LoaderUtils.resolveURL(sourceURI2, options.path), onLoad, void 0, reject); }); }).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. * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef * @return {Promise} */ 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 transform = mapDef.extensions !== void 0 ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : void 0; if (transform) { const gltfReference = parser.associations.get(texture); texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform); parser.associations.set(texture, gltfReference); } } if (colorSpace !== void 0) { if (typeof colorSpace === "number") colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace2 : LinearSRGBColorSpace2; if ("colorSpace" in texture) texture.colorSpace = colorSpace; else texture.encoding = colorSpace === SRGBColorSpace2 ? sRGBEncoding : LinearEncoding; } 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. * @param {Object3D} mesh Mesh, Line, or Points instance. */ assignFinalMaterial(mesh) { const geometry3 = mesh.geometry; let material = mesh.material; const useDerivativeTangents = geometry3.attributes.tangent === void 0; const useVertexColors = geometry3.attributes.color !== void 0; const useFlatShading = geometry3.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 * @param {number} materialIndex * @return {Promise} */ loadMaterial(materialIndex) { const parser = this; const json = this.json; const extensions2 = 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 = extensions2[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], LinearSRGBColorSpace2); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace2)); } 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 scale5 = materialDef.normalTexture.scale; materialParams.normalScale.set(scale5, scale5); } } 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], LinearSRGBColorSpace2 ); } if (materialDef.emissiveTexture !== void 0 && materialType !== MeshBasicMaterial) { pending.push(parser.assignTexture(materialParams, "emissiveMap", materialDef.emissiveTexture, SRGBColorSpace2)); } 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(extensions2, material, materialDef); return material; }); } /** When Object3D instances are targeted by animation, they need unique names. */ 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. * * @param {Array} primitives * @return {Promise>} */ loadGeometries(primitives) { const parser = this; const extensions2 = this.extensions; const cache = this.primitiveCache; function createDracoPrimitive(primitive) { return extensions2[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function(geometry3) { return addPrimitiveAttributes(geometry3, primitive, parser); }); } const pending = []; for (let i4 = 0, il = primitives.length; i4 < il; i4++) { const primitive = primitives[i4]; 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 * @param {number} meshIndex * @return {Promise} */ loadMesh(meshIndex) { const parser = this; const json = this.json; const extensions2 = this.extensions; const meshDef = json.meshes[meshIndex]; const primitives = meshDef.primitives; const pending = []; for (let i4 = 0, il = primitives.length; i4 < il; i4++) { const material = primitives[i4].material === void 0 ? createDefaultMaterial(this.cache) : this.getDependency("material", primitives[i4].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 i4 = 0, il = geometries.length; i4 < il; i4++) { const geometry3 = geometries[i4]; const primitive = primitives[i4]; let mesh; const material = materials[i4]; 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(geometry3, material) : new Mesh(geometry3, 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(geometry3, material); } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_STRIP) { mesh = new Line(geometry3, material); } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_LOOP) { mesh = new LineLoop(geometry3, material); } else if (primitive.mode === WEBGL_CONSTANTS2.POINTS) { mesh = new Points(geometry3, 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(extensions2, mesh, primitive); parser.assignFinalMaterial(mesh); meshes.push(mesh); } for (let i4 = 0, il = meshes.length; i4 < il; i4++) { parser.associations.set(meshes[i4], { meshes: meshIndex, primitives: i4 }); } if (meshes.length === 1) { if (meshDef.extensions) addUnknownExtensionsToUserData(extensions2, meshes[0], meshDef); return meshes[0]; } const group = new Group(); if (meshDef.extensions) addUnknownExtensionsToUserData(extensions2, group, meshDef); parser.associations.set(group, { meshes: meshIndex }); for (let i4 = 0, il = meshes.length; i4 < il; i4++) { group.add(meshes[i4]); } return group; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras * @param {number} cameraIndex * @return {Promise} */ 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 * @param {number} skinIndex * @return {Promise} */ loadSkin(skinIndex) { const skinDef = this.json.skins[skinIndex]; const pending = []; for (let i4 = 0, il = skinDef.joints.length; i4 < il; i4++) { pending.push(this._loadNodeShallow(skinDef.joints[i4])); } 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 i4 = 0, il = jointNodes.length; i4 < il; i4++) { const jointNode = jointNodes[i4]; if (jointNode) { bones.push(jointNode); const mat2 = new Matrix4(); if (inverseBindMatrices !== null) { mat2.fromArray(inverseBindMatrices.array, i4 * 16); } boneInverses.push(mat2); } else { console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[i4]); } } return new Skeleton(bones, boneInverses); }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex * @return {Promise} */ 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 i4 = 0, il = animationDef.channels.length; i4 < il; i4++) { const channel = animationDef.channels[i4]; const sampler = animationDef.samplers[channel.sampler]; const target2 = channel.target; const name = target2.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 (target2.node === void 0) continue; pendingNodes.push(this.getDependency("node", name)); pendingInputAccessors.push(this.getDependency("accessor", input)); pendingOutputAccessors.push(this.getDependency("accessor", output)); pendingSamplers.push(sampler); pendingTargets.push(target2); } 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 i4 = 0, il = nodes.length; i4 < il; i4++) { const node = nodes[i4]; const inputAccessor = inputAccessors[i4]; const outputAccessor = outputAccessors[i4]; const sampler = samplers[i4]; const target2 = targets[i4]; if (node === void 0) continue; if (node.updateMatrix) { node.updateMatrix(); } const createdTracks = parser._createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target2); if (createdTracks) { for (let k = 0; k < createdTracks.length; k++) { tracks.push(createdTracks[k]); } } } 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(o2) { if (!o2.isMesh) return; for (let i4 = 0, il = nodeDef.weights.length; i4 < il; i4++) { o2.morphTargetInfluences[i4] = nodeDef.weights[i4]; } }); } return node; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy * @param {number} nodeIndex * @return {Promise} */ 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 i4 = 0, il = childrenDef.length; i4 < il; i4++) { childPending.push(parser.getDependency("node", childrenDef[i4])); } 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, _identityMatrix2); }); } for (let i4 = 0, il = children.length; i4 < il; i4++) { node.add(children[i4]); } 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 extensions2 = 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 i4 = 0, il = objects.length; i4 < il; i4++) { node.add(objects[i4]); } } if (nodeDef.name) { node.userData.name = nodeDef.name; node.name = nodeName; } assignExtrasToUserData(node, nodeDef); if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions2, node, nodeDef); if (nodeDef.matrix !== void 0) { const matrix6 = new Matrix4(); matrix6.fromArray(nodeDef.matrix); node.applyMatrix4(matrix6); } 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, {}); } parser.associations.get(node).nodes = nodeIndex; return node; }); return this.nodeCache[nodeIndex]; } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes * @param {number} sceneIndex * @return {Promise} */ loadScene(sceneIndex) { const extensions2 = 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(extensions2, scene, sceneDef); const nodeIds = sceneDef.nodes || []; const pending = []; for (let i4 = 0, il = nodeIds.length; i4 < il; i4++) { pending.push(parser.getDependency("node", nodeIds[i4])); } return Promise.all(pending).then(function(nodes) { for (let i4 = 0, il = nodes.length; i4 < il; i4++) { scene.add(nodes[i4]); } const reduceAssociations = (node) => { const reducedAssociations = /* @__PURE__ */ new Map(); for (const [key, value] of parser.associations) { if (key instanceof Material || key instanceof Texture) { reducedAssociations.set(key, value); } } 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, target2) { const tracks = []; const targetName = node.name ? node.name : node.uuid; const targetNames = []; if (PATH_PROPERTIES2[target2.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[target2.path]) { case PATH_PROPERTIES2.weights: TypedKeyframeTrack = NumberKeyframeTrack; break; case PATH_PROPERTIES2.rotation: TypedKeyframeTrack = QuaternionKeyframeTrack; break; case PATH_PROPERTIES2.position: 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 j = 0, jl = targetNames.length; j < jl; j++) { const track = new TypedKeyframeTrack( targetNames[j] + "." + PATH_PROPERTIES2[target2.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 scale5 = getNormalizedComponentScale(outputArray.constructor); const scaled = new Float32Array(outputArray.length); for (let j = 0, jl = outputArray.length; j < jl; j++) { scaled[j] = outputArray[j] * scale5; } 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(geometry3, 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 i4 = 0, il = targets.length; i4 < il; i4++) { const target2 = targets[i4]; if (target2.POSITION !== void 0) { const accessor = parser.json.accessors[target2.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); } geometry3.boundingBox = box; const sphere = new Sphere(); box.getCenter(sphere.center); sphere.radius = box.min.distanceTo(box.max) / 2; geometry3.boundingSphere = sphere; } function addPrimitiveAttributes(geometry3, primitiveDef, parser) { const attributes = primitiveDef.attributes; const pending = []; function assignAttributeAccessor(accessorIndex, attributeName) { return parser.getDependency("accessor", accessorIndex).then(function(accessor) { geometry3.setAttribute(attributeName, accessor); }); } for (const gltfAttributeName in attributes) { const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); if (threeAttributeName in geometry3.attributes) continue; pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName)); } if (primitiveDef.indices !== void 0 && !geometry3.index) { const accessor = parser.getDependency("accessor", primitiveDef.indices).then(function(accessor2) { geometry3.setIndex(accessor2); }); pending.push(accessor); } assignExtrasToUserData(geometry3, primitiveDef); computeBounds(geometry3, primitiveDef, parser); return Promise.all(pending).then(function() { return primitiveDef.targets !== void 0 ? addMorphTargets(geometry3, primitiveDef.targets, parser) : geometry3; }); } // node_modules/three-stdlib/webxr/OculusHandPointerModel.js var YAXIS = new Vector3(0, 1, 0); var ZAXIS = new Vector3(0, 0, 1); // node_modules/three-stdlib/webxr/VRButton.js var __defProp29 = Object.defineProperty; var __defNormalProp29 = (obj, key, value) => key in obj ? __defProp29(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField29 = (obj, key, value) => { __defNormalProp29(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var VRButton = (() => { const _VRButton = class { static createButton(renderer, sessionInit = {}) { const button = document.createElement("button"); function showEnterVR() { let currentSession = null; async function onSessionStarted(session) { session.addEventListener("end", onSessionEnded); await renderer.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"; button.onmouseenter = () => { button.style.opacity = "1.0"; }; button.onmouseleave = () => { button.style.opacity = "0.5"; }; button.onclick = () => { var _a3; if (currentSession === null) { const optionalFeatures = [sessionInit.optionalFeatures, "local-floor", "bounded-floor", "hand-tracking"].flat().filter(Boolean); (_a3 = navigator.xr) == null ? void 0 : _a3.requestSession("immersive-vr", { ...sessionInit, optionalFeatures }).then(onSessionStarted); } else { currentSession.end(); } }; } 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 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) { stylizeElement(button); button.id = "VRButton"; button.style.display = "none"; navigator.xr.isSessionSupported("immersive-vr").then((supported) => { supported ? showEnterVR() : showWebXRNotFound(); if (supported && _VRButton.xrSessionIsGranted) { button.click(); } }); 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; } } static registerSessionGrantedListener() { if (typeof navigator !== "undefined" && "xr" in navigator) { navigator.xr.addEventListener("sessiongranted", () => { _VRButton.xrSessionIsGranted = true; }); } } }; let VRButton2 = _VRButton; __publicField29(VRButton2, "xrSessionIsGranted", false); VRButton2.registerSessionGrantedListener(); return VRButton2; })(); // node_modules/three-stdlib/libs/MotionControllers.js var MotionControllerConstants = { Handedness: { NONE: "none", LEFT: "left", RIGHT: "right" }, ComponentState: { DEFAULT: "default", TOUCHED: "touched", PRESSED: "pressed" }, ComponentProperty: { BUTTON: "button", X_AXIS: "xAxis", Y_AXIS: "yAxis", STATE: "state" }, ComponentType: { TRIGGER: "trigger", SQUEEZE: "squeeze", TOUCHPAD: "touchpad", THUMBSTICK: "thumbstick", BUTTON: "button" }, ButtonTouchThreshold: 0.05, AxisTouchThreshold: 0.1, VisualResponseProperty: { TRANSFORM: "transform", VISIBILITY: "visibility" } }; var defaultComponentValues = { xAxis: 0, yAxis: 0, button: 0, state: MotionControllerConstants.ComponentState.DEFAULT }; // node_modules/three-stdlib/webxr/XRHandPrimitiveModel.js var _matrix4 = new Matrix4(); var _vector4 = new Vector3(); // node_modules/three-stdlib/geometries/RoundedBoxGeometry.js var tempNormal = new Vector3(); // node_modules/three-stdlib/geometries/DecalGeometry.js var DecalGeometry = class extends BufferGeometry { constructor(mesh, position2, orientation, size2) { super(); const vertices = []; const normals = []; const uvs = []; const plane = new Vector3(); 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("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); function generate() { let i4; let decalVertices = []; const vertex = new Vector3(); const normal2 = new Vector3(); if (mesh.geometry.isGeometry === true) { console.error("THREE.DecalGeometry no longer supports THREE.Geometry. Use BufferGeometry instead."); return; } const geometry3 = mesh.geometry; const positionAttribute = geometry3.attributes.position; const normalAttribute = geometry3.attributes.normal; if (geometry3.index !== null) { const index2 = geometry3.index; for (i4 = 0; i4 < index2.count; i4++) { vertex.fromBufferAttribute(positionAttribute, index2.getX(i4)); normal2.fromBufferAttribute(normalAttribute, index2.getX(i4)); pushDecalVertex(decalVertices, vertex, normal2); } } else { for (i4 = 0; i4 < positionAttribute.count; i4++) { vertex.fromBufferAttribute(positionAttribute, i4); normal2.fromBufferAttribute(normalAttribute, i4); pushDecalVertex(decalVertices, vertex, normal2); } } decalVertices = clipGeometry(decalVertices, plane.set(1, 0, 0)); decalVertices = clipGeometry(decalVertices, plane.set(-1, 0, 0)); decalVertices = clipGeometry(decalVertices, plane.set(0, 1, 0)); decalVertices = clipGeometry(decalVertices, plane.set(0, -1, 0)); decalVertices = clipGeometry(decalVertices, plane.set(0, 0, 1)); decalVertices = clipGeometry(decalVertices, plane.set(0, 0, -1)); for (i4 = 0; i4 < decalVertices.length; i4++) { const decalVertex = decalVertices[i4]; 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); normals.push(decalVertex.normal.x, decalVertex.normal.y, decalVertex.normal.z); } } function pushDecalVertex(decalVertices, vertex, normal2) { vertex.applyMatrix4(mesh.matrixWorld); vertex.applyMatrix4(projectorMatrixInverse); normal2.transformDirection(mesh.matrixWorld); decalVertices.push(new DecalVertex(vertex.clone(), normal2.clone())); } function clipGeometry(inVertices, plane2) { const outVertices = []; const s2 = 0.5 * Math.abs(size2.dot(plane2)); for (let i4 = 0; i4 < inVertices.length; i4 += 3) { let v1Out, v2Out, v3Out, total = 0; let nV1, nV2, nV3, nV4; const d1 = inVertices[i4 + 0].position.dot(plane2) - s2; const d2 = inVertices[i4 + 1].position.dot(plane2) - s2; const d3 = inVertices[i4 + 2].position.dot(plane2) - s2; v1Out = d1 > 0; v2Out = d2 > 0; v3Out = d3 > 0; total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0); switch (total) { case 0: { outVertices.push(inVertices[i4]); outVertices.push(inVertices[i4 + 1]); outVertices.push(inVertices[i4 + 2]); break; } case 1: { if (v1Out) { nV1 = inVertices[i4 + 1]; nV2 = inVertices[i4 + 2]; nV3 = clip(inVertices[i4], nV1, plane2, s2); nV4 = clip(inVertices[i4], nV2, plane2, s2); } if (v2Out) { nV1 = inVertices[i4]; nV2 = inVertices[i4 + 2]; nV3 = clip(inVertices[i4 + 1], nV1, plane2, s2); nV4 = clip(inVertices[i4 + 1], nV2, plane2, s2); 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[i4]; nV2 = inVertices[i4 + 1]; nV3 = clip(inVertices[i4 + 2], nV1, plane2, s2); nV4 = clip(inVertices[i4 + 2], nV2, plane2, s2); } 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[i4].clone(); nV2 = clip(nV1, inVertices[i4 + 1], plane2, s2); nV3 = clip(nV1, inVertices[i4 + 2], plane2, s2); outVertices.push(nV1); outVertices.push(nV2); outVertices.push(nV3); } if (!v2Out) { nV1 = inVertices[i4 + 1].clone(); nV2 = clip(nV1, inVertices[i4 + 2], plane2, s2); nV3 = clip(nV1, inVertices[i4], plane2, s2); outVertices.push(nV1); outVertices.push(nV2); outVertices.push(nV3); } if (!v3Out) { nV1 = inVertices[i4 + 2].clone(); nV2 = clip(nV1, inVertices[i4], plane2, s2); nV3 = clip(nV1, inVertices[i4 + 1], plane2, s2); outVertices.push(nV1); outVertices.push(nV2); outVertices.push(nV3); } break; } } } return outVertices; } function clip(v0, v13, p2, s2) { const d0 = v0.position.dot(p2) - s2; const d1 = v13.position.dot(p2) - s2; const s0 = d0 / (d0 - d1); const v5 = new DecalVertex( new Vector3( v0.position.x + s0 * (v13.position.x - v0.position.x), v0.position.y + s0 * (v13.position.y - v0.position.y), v0.position.z + s0 * (v13.position.z - v0.position.z) ), new Vector3( v0.normal.x + s0 * (v13.normal.x - v0.normal.x), v0.normal.y + s0 * (v13.normal.y - v0.normal.y), v0.normal.z + s0 * (v13.normal.z - v0.normal.z) ) ); return v5; } } }; var DecalVertex = class { constructor(position2, normal2) { this.position = position2; this.normal = normal2; } clone() { return new this.constructor(this.position.clone(), this.normal.clone()); } }; // node_modules/three-stdlib/geometries/TextGeometry.js var TextGeometry = class extends ExtrudeGeometry { constructor(text, parameters = {}) { const { bevelEnabled = false, bevelSize = 8, bevelThickness = 10, font, height = 50, size: size2 = 100, lineHeight = 1, letterSpacing = 0, ...rest } = parameters; if (font === void 0) { super(); } else { const shapes = font.generateShapes(text, size2, { lineHeight, letterSpacing }); super(shapes, { ...rest, bevelEnabled, bevelSize, bevelThickness, depth: height }); } this.type = "TextGeometry"; } }; // node_modules/three-stdlib/csm/CSMFrustum.js var inverseProjectionMatrix = new Matrix4(); var CSMFrustum = class _CSMFrustum { constructor(data) { data = data || {}; this.vertices = { near: [new Vector3(), new Vector3(), new Vector3(), new Vector3()], far: [new Vector3(), new Vector3(), new Vector3(), new Vector3()] }; if (data.projectionMatrix !== void 0) { this.setFromProjectionMatrix(data.projectionMatrix, data.maxFar || 1e4); } } setFromProjectionMatrix(projectionMatrix, maxFar) { const isOrthographic2 = projectionMatrix.elements[2 * 4 + 3] === 0; inverseProjectionMatrix.copy(projectionMatrix).invert(); this.vertices.near[0].set(1, 1, -1); this.vertices.near[1].set(1, -1, -1); this.vertices.near[2].set(-1, -1, -1); this.vertices.near[3].set(-1, 1, -1); this.vertices.near.forEach(function(v5) { v5.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(v5) { v5.applyMatrix4(inverseProjectionMatrix); const absZ = Math.abs(v5.z); if (isOrthographic2) { v5.z *= Math.min(maxFar / absZ, 1); } else { v5.multiplyScalar(Math.min(maxFar / absZ, 1)); } }); return this.vertices; } split(breaks, target2) { while (breaks.length > target2.length) { target2.push(new _CSMFrustum()); } target2.length = breaks.length; for (let i4 = 0; i4 < breaks.length; i4++) { const cascade = target2[i4]; if (i4 === 0) { for (let j = 0; j < 4; j++) { cascade.vertices.near[j].copy(this.vertices.near[j]); } } else { for (let j = 0; j < 4; j++) { cascade.vertices.near[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i4 - 1]); } } if (i4 === breaks.length - 1) { for (let j = 0; j < 4; j++) { cascade.vertices.far[j].copy(this.vertices.far[j]); } } else { for (let j = 0; j < 4; j++) { cascade.vertices.far[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i4]); } } } } toSpace(cameraMatrix, target2) { for (let i4 = 0; i4 < 4; i4++) { target2.vertices.near[i4].copy(this.vertices.near[i4]).applyMatrix4(cameraMatrix); target2.vertices.far[i4].copy(this.vertices.far[i4]).applyMatrix4(cameraMatrix); } } }; // node_modules/three-stdlib/csm/CSM.js var _cameraToLightMatrix = new Matrix4(); var _lightSpaceFrustum = new CSMFrustum(); var _center2 = new Vector3(); var _bbox = new Box3(); // node_modules/three-stdlib/shaders/ColorCorrectionShader.js var 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-stdlib/shaders/ColorifyShader.js var 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 ); vec3 luma = vec3( 0.299, 0.587, 0.114 ); float v = dot( texel.xyz, luma ); gl_FragColor = vec4( v * color, texel.w ); } ` ) }; // node_modules/three-stdlib/shaders/FXAAShader.js var 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 */ ` precision highp float; uniform sampler2D tDiffuse; uniform vec2 resolution; varying vec2 vUv; // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com) //---------------------------------------------------------------------------------- // File: es3-keplerFXAAassetsshaders/FXAA_DefaultES.frag // SDK Version: v3.00 // Email: gameworks@nvidia.com // Site: http://developer.nvidia.com/ // // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AS IS AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------- #define FXAA_PC 1 #define FXAA_GLSL_100 1 #define FXAA_QUALITY_PRESET 12 #define FXAA_GREEN_AS_LUMA 1 /*--------------------------------------------------------------------------*/ #ifndef FXAA_PC_CONSOLE // // The console algorithm for PC is included // for developers targeting really low spec machines. // Likely better to just run FXAA_PC, and use a really low preset. // #define FXAA_PC_CONSOLE 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_GLSL_120 #define FXAA_GLSL_120 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_GLSL_130 #define FXAA_GLSL_130 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_HLSL_3 #define FXAA_HLSL_3 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_HLSL_4 #define FXAA_HLSL_4 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_HLSL_5 #define FXAA_HLSL_5 0 #endif /*==========================================================================*/ #ifndef FXAA_GREEN_AS_LUMA // // For those using non-linear color, // and either not able to get luma in alpha, or not wanting to, // this enables FXAA to run using green as a proxy for luma. // So with this enabled, no need to pack luma in alpha. // // This will turn off AA on anything which lacks some amount of green. // Pure red and blue or combination of only R and B, will get no AA. // // Might want to lower the settings for both, // fxaaConsoleEdgeThresholdMin // fxaaQualityEdgeThresholdMin // In order to insure AA does not get turned off on colors // which contain a minor amount of green. // // 1 = On. // 0 = Off. // #define FXAA_GREEN_AS_LUMA 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_EARLY_EXIT // // Controls algorithms early exit path. // On PS3 turning this ON adds 2 cycles to the shader. // On 360 turning this OFF adds 10ths of a millisecond to the shader. // Turning this off on console will result in a more blurry image. // So this defaults to on. // // 1 = On. // 0 = Off. // #define FXAA_EARLY_EXIT 1 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_DISCARD // // Only valid for PC OpenGL currently. // Probably will not work when FXAA_GREEN_AS_LUMA = 1. // // 1 = Use discard on pixels which dont need AA. // For APIs which enable concurrent TEX+ROP from same surface. // 0 = Return unchanged color on pixels which dont need AA. // #define FXAA_DISCARD 0 #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_FAST_PIXEL_OFFSET // // Used for GLSL 120 only. // // 1 = GL API supports fast pixel offsets // 0 = do not use fast pixel offsets // #ifdef GL_EXT_gpu_shader4 #define FXAA_FAST_PIXEL_OFFSET 1 #endif #ifdef GL_NV_gpu_shader5 #define FXAA_FAST_PIXEL_OFFSET 1 #endif #ifdef GL_ARB_gpu_shader5 #define FXAA_FAST_PIXEL_OFFSET 1 #endif #ifndef FXAA_FAST_PIXEL_OFFSET #define FXAA_FAST_PIXEL_OFFSET 0 #endif #endif /*--------------------------------------------------------------------------*/ #ifndef FXAA_GATHER4_ALPHA // // 1 = API supports gather4 on alpha channel. // 0 = API does not support gather4 on alpha channel. // #if (FXAA_HLSL_5 == 1) #define FXAA_GATHER4_ALPHA 1 #endif #ifdef GL_ARB_gpu_shader5 #define FXAA_GATHER4_ALPHA 1 #endif #ifdef GL_NV_gpu_shader5 #define FXAA_GATHER4_ALPHA 1 #endif #ifndef FXAA_GATHER4_ALPHA #define FXAA_GATHER4_ALPHA 0 #endif #endif /*============================================================================ FXAA QUALITY - TUNING KNOBS ------------------------------------------------------------------------------ NOTE the other tuning knobs are now in the shader function inputs! ============================================================================*/ #ifndef FXAA_QUALITY_PRESET // // Choose the quality preset. // This needs to be compiled into the shader as it effects code. // Best option to include multiple presets is to // in each shader define the preset, then include this file. // // OPTIONS // ----------------------------------------------------------------------- // 10 to 15 - default medium dither (10=fastest, 15=highest quality) // 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality) // 39 - no dither, very expensive // // NOTES // ----------------------------------------------------------------------- // 12 = slightly faster then FXAA 3.9 and higher edge quality (default) // 13 = about same speed as FXAA 3.9 and better than 12 // 23 = closest to FXAA 3.9 visually and performance wise // _ = the lowest digit is directly related to performance // _ = the highest digit is directly related to style // #define FXAA_QUALITY_PRESET 12 #endif /*============================================================================ FXAA QUALITY - PRESETS ============================================================================*/ /*============================================================================ FXAA QUALITY - MEDIUM DITHER PRESETS ============================================================================*/ #if (FXAA_QUALITY_PRESET == 10) #define FXAA_QUALITY_PS 3 #define FXAA_QUALITY_P0 1.5 #define FXAA_QUALITY_P1 3.0 #define FXAA_QUALITY_P2 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 11) #define FXAA_QUALITY_PS 4 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 3.0 #define FXAA_QUALITY_P3 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 12) #define FXAA_QUALITY_PS 5 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 4.0 #define FXAA_QUALITY_P4 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 13) #define FXAA_QUALITY_PS 6 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 4.0 #define FXAA_QUALITY_P5 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 14) #define FXAA_QUALITY_PS 7 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 4.0 #define FXAA_QUALITY_P6 12.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 15) #define FXAA_QUALITY_PS 8 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 4.0 #define FXAA_QUALITY_P7 12.0 #endif /*============================================================================ FXAA QUALITY - LOW DITHER PRESETS ============================================================================*/ #if (FXAA_QUALITY_PRESET == 20) #define FXAA_QUALITY_PS 3 #define FXAA_QUALITY_P0 1.5 #define FXAA_QUALITY_P1 2.0 #define FXAA_QUALITY_P2 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 21) #define FXAA_QUALITY_PS 4 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 22) #define FXAA_QUALITY_PS 5 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 23) #define FXAA_QUALITY_PS 6 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 24) #define FXAA_QUALITY_PS 7 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 3.0 #define FXAA_QUALITY_P6 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 25) #define FXAA_QUALITY_PS 8 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 4.0 #define FXAA_QUALITY_P7 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 26) #define FXAA_QUALITY_PS 9 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 4.0 #define FXAA_QUALITY_P8 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 27) #define FXAA_QUALITY_PS 10 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 2.0 #define FXAA_QUALITY_P8 4.0 #define FXAA_QUALITY_P9 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 28) #define FXAA_QUALITY_PS 11 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 2.0 #define FXAA_QUALITY_P8 2.0 #define FXAA_QUALITY_P9 4.0 #define FXAA_QUALITY_P10 8.0 #endif /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PRESET == 29) #define FXAA_QUALITY_PS 12 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 2.0 #define FXAA_QUALITY_P8 2.0 #define FXAA_QUALITY_P9 2.0 #define FXAA_QUALITY_P10 4.0 #define FXAA_QUALITY_P11 8.0 #endif /*============================================================================ FXAA QUALITY - EXTREME QUALITY ============================================================================*/ #if (FXAA_QUALITY_PRESET == 39) #define FXAA_QUALITY_PS 12 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.0 #define FXAA_QUALITY_P2 1.0 #define FXAA_QUALITY_P3 1.0 #define FXAA_QUALITY_P4 1.0 #define FXAA_QUALITY_P5 1.5 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 2.0 #define FXAA_QUALITY_P8 2.0 #define FXAA_QUALITY_P9 2.0 #define FXAA_QUALITY_P10 4.0 #define FXAA_QUALITY_P11 8.0 #endif /*============================================================================ API PORTING ============================================================================*/ #if (FXAA_GLSL_100 == 1) || (FXAA_GLSL_120 == 1) || (FXAA_GLSL_130 == 1) #define FxaaBool bool #define FxaaDiscard discard #define FxaaFloat float #define FxaaFloat2 vec2 #define FxaaFloat3 vec3 #define FxaaFloat4 vec4 #define FxaaHalf float #define FxaaHalf2 vec2 #define FxaaHalf3 vec3 #define FxaaHalf4 vec4 #define FxaaInt2 ivec2 #define FxaaSat(x) clamp(x, 0.0, 1.0) #define FxaaTex sampler2D #else #define FxaaBool bool #define FxaaDiscard clip(-1) #define FxaaFloat float #define FxaaFloat2 float2 #define FxaaFloat3 float3 #define FxaaFloat4 float4 #define FxaaHalf half #define FxaaHalf2 half2 #define FxaaHalf3 half3 #define FxaaHalf4 half4 #define FxaaSat(x) saturate(x) #endif /*--------------------------------------------------------------------------*/ #if (FXAA_GLSL_100 == 1) #define FxaaTexTop(t, p) texture2D(t, p, 0.0) #define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r), 0.0) #endif /*--------------------------------------------------------------------------*/ #if (FXAA_GLSL_120 == 1) // Requires, // #version 120 // And at least, // #extension GL_EXT_gpu_shader4 : enable // (or set FXAA_FAST_PIXEL_OFFSET 1 to work like DX9) #define FxaaTexTop(t, p) texture2DLod(t, p, 0.0) #if (FXAA_FAST_PIXEL_OFFSET == 1) #define FxaaTexOff(t, p, o, r) texture2DLodOffset(t, p, 0.0, o) #else #define FxaaTexOff(t, p, o, r) texture2DLod(t, p + (o * r), 0.0) #endif #if (FXAA_GATHER4_ALPHA == 1) // use #extension GL_ARB_gpu_shader5 : enable #define FxaaTexAlpha4(t, p) textureGather(t, p, 3) #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3) #define FxaaTexGreen4(t, p) textureGather(t, p, 1) #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1) #endif #endif /*--------------------------------------------------------------------------*/ #if (FXAA_GLSL_130 == 1) // Requires "#version 130" or better #define FxaaTexTop(t, p) textureLod(t, p, 0.0) #define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o) #if (FXAA_GATHER4_ALPHA == 1) // use #extension GL_ARB_gpu_shader5 : enable #define FxaaTexAlpha4(t, p) textureGather(t, p, 3) #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3) #define FxaaTexGreen4(t, p) textureGather(t, p, 1) #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1) #endif #endif /*--------------------------------------------------------------------------*/ #if (FXAA_HLSL_3 == 1) #define FxaaInt2 float2 #define FxaaTex sampler2D #define FxaaTexTop(t, p) tex2Dlod(t, float4(p, 0.0, 0.0)) #define FxaaTexOff(t, p, o, r) tex2Dlod(t, float4(p + (o * r), 0, 0)) #endif /*--------------------------------------------------------------------------*/ #if (FXAA_HLSL_4 == 1) #define FxaaInt2 int2 struct FxaaTex { SamplerState smpl; Texture2D tex; }; #define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0) #define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o) #endif /*--------------------------------------------------------------------------*/ #if (FXAA_HLSL_5 == 1) #define FxaaInt2 int2 struct FxaaTex { SamplerState smpl; Texture2D tex; }; #define FxaaTexTop(t, p) t.tex.SampleLevel(t.smpl, p, 0.0) #define FxaaTexOff(t, p, o, r) t.tex.SampleLevel(t.smpl, p, 0.0, o) #define FxaaTexAlpha4(t, p) t.tex.GatherAlpha(t.smpl, p) #define FxaaTexOffAlpha4(t, p, o) t.tex.GatherAlpha(t.smpl, p, o) #define FxaaTexGreen4(t, p) t.tex.GatherGreen(t.smpl, p) #define FxaaTexOffGreen4(t, p, o) t.tex.GatherGreen(t.smpl, p, o) #endif /*============================================================================ GREEN AS LUMA OPTION SUPPORT FUNCTION ============================================================================*/ #if (FXAA_GREEN_AS_LUMA == 0) FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.w; } #else FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; } #endif /*============================================================================ FXAA3 QUALITY - PC ============================================================================*/ #if (FXAA_PC == 1) /*--------------------------------------------------------------------------*/ FxaaFloat4 FxaaPixelShader( // // Use noperspective interpolation here (turn off perspective interpolation). // {xy} = center of pixel FxaaFloat2 pos, // // Used only for FXAA Console, and not used on the 360 version. // Use noperspective interpolation here (turn off perspective interpolation). // {xy_} = upper left of pixel // {_zw} = lower right of pixel FxaaFloat4 fxaaConsolePosPos, // // Input color texture. // {rgb_} = color in linear or perceptual color space // if (FXAA_GREEN_AS_LUMA == 0) // {__a} = luma in perceptual color space (not linear) FxaaTex tex, // // Only used on the optimized 360 version of FXAA Console. // For everything but 360, just use the same input here as for "tex". // For 360, same texture, just alias with a 2nd sampler. // This sampler needs to have an exponent bias of -1. FxaaTex fxaaConsole360TexExpBiasNegOne, // // Only used on the optimized 360 version of FXAA Console. // For everything but 360, just use the same input here as for "tex". // For 360, same texture, just alias with a 3nd sampler. // This sampler needs to have an exponent bias of -2. FxaaTex fxaaConsole360TexExpBiasNegTwo, // // Only used on FXAA Quality. // This must be from a constant/uniform. // {x_} = 1.0/screenWidthInPixels // {_y} = 1.0/screenHeightInPixels FxaaFloat2 fxaaQualityRcpFrame, // // Only used on FXAA Console. // This must be from a constant/uniform. // This effects sub-pixel AA quality and inversely sharpness. // Where N ranges between, // N = 0.50 (default) // N = 0.33 (sharper) // {x__} = -N/screenWidthInPixels // {_y_} = -N/screenHeightInPixels // {_z_} = N/screenWidthInPixels // {__w} = N/screenHeightInPixels FxaaFloat4 fxaaConsoleRcpFrameOpt, // // Only used on FXAA Console. // Not used on 360, but used on PS3 and PC. // This must be from a constant/uniform. // {x__} = -2.0/screenWidthInPixels // {_y_} = -2.0/screenHeightInPixels // {_z_} = 2.0/screenWidthInPixels // {__w} = 2.0/screenHeightInPixels FxaaFloat4 fxaaConsoleRcpFrameOpt2, // // Only used on FXAA Console. // Only used on 360 in place of fxaaConsoleRcpFrameOpt2. // This must be from a constant/uniform. // {x__} = 8.0/screenWidthInPixels // {_y_} = 8.0/screenHeightInPixels // {_z_} = -4.0/screenWidthInPixels // {__w} = -4.0/screenHeightInPixels FxaaFloat4 fxaaConsole360RcpFrameOpt2, // // Only used on FXAA Quality. // This used to be the FXAA_QUALITY_SUBPIX define. // It is here now to allow easier tuning. // Choose the amount of sub-pixel aliasing removal. // This can effect sharpness. // 1.00 - upper limit (softer) // 0.75 - default amount of filtering // 0.50 - lower limit (sharper, less sub-pixel aliasing removal) // 0.25 - almost off // 0.00 - completely off FxaaFloat fxaaQualitySubpix, // // Only used on FXAA Quality. // This used to be the FXAA_QUALITY_EDGE_THRESHOLD define. // It is here now to allow easier tuning. // The minimum amount of local contrast required to apply algorithm. // 0.333 - too little (faster) // 0.250 - low quality // 0.166 - default // 0.125 - high quality // 0.063 - overkill (slower) FxaaFloat fxaaQualityEdgeThreshold, // // Only used on FXAA Quality. // This used to be the FXAA_QUALITY_EDGE_THRESHOLD_MIN define. // It is here now to allow easier tuning. // Trims the algorithm from processing darks. // 0.0833 - upper limit (default, the start of visible unfiltered edges) // 0.0625 - high quality (faster) // 0.0312 - visible limit (slower) // Special notes when using FXAA_GREEN_AS_LUMA, // Likely want to set this to zero. // As colors that are mostly not-green // will appear very dark in the green channel! // Tune by looking at mostly non-green content, // then start at zero and increase until aliasing is a problem. FxaaFloat fxaaQualityEdgeThresholdMin, // // Only used on FXAA Console. // This used to be the FXAA_CONSOLE_EDGE_SHARPNESS define. // It is here now to allow easier tuning. // This does not effect PS3, as this needs to be compiled in. // Use FXAA_CONSOLE_PS3_EDGE_SHARPNESS for PS3. // Due to the PS3 being ALU bound, // there are only three safe values here: 2 and 4 and 8. // These options use the shaders ability to a free *|/ by 2|4|8. // For all other platforms can be a non-power of two. // 8.0 is sharper (default!!!) // 4.0 is softer // 2.0 is really soft (good only for vector graphics inputs) FxaaFloat fxaaConsoleEdgeSharpness, // // Only used on FXAA Console. // This used to be the FXAA_CONSOLE_EDGE_THRESHOLD define. // It is here now to allow easier tuning. // This does not effect PS3, as this needs to be compiled in. // Use FXAA_CONSOLE_PS3_EDGE_THRESHOLD for PS3. // Due to the PS3 being ALU bound, // there are only two safe values here: 1/4 and 1/8. // These options use the shaders ability to a free *|/ by 2|4|8. // The console setting has a different mapping than the quality setting. // Other platforms can use other values. // 0.125 leaves less aliasing, but is softer (default!!!) // 0.25 leaves more aliasing, and is sharper FxaaFloat fxaaConsoleEdgeThreshold, // // Only used on FXAA Console. // This used to be the FXAA_CONSOLE_EDGE_THRESHOLD_MIN define. // It is here now to allow easier tuning. // Trims the algorithm from processing darks. // The console setting has a different mapping than the quality setting. // This only applies when FXAA_EARLY_EXIT is 1. // This does not apply to PS3, // PS3 was simplified to avoid more shader instructions. // 0.06 - faster but more aliasing in darks // 0.05 - default // 0.04 - slower and less aliasing in darks // Special notes when using FXAA_GREEN_AS_LUMA, // Likely want to set this to zero. // As colors that are mostly not-green // will appear very dark in the green channel! // Tune by looking at mostly non-green content, // then start at zero and increase until aliasing is a problem. FxaaFloat fxaaConsoleEdgeThresholdMin, // // Extra constants for 360 FXAA Console only. // Use zeros or anything else for other platforms. // These must be in physical constant registers and NOT immediates. // Immediates will result in compiler un-optimizing. // {xyzw} = float4(1.0, -1.0, 0.25, -0.25) FxaaFloat4 fxaaConsole360ConstDir ) { /*--------------------------------------------------------------------------*/ FxaaFloat2 posM; posM.x = pos.x; posM.y = pos.y; #if (FXAA_GATHER4_ALPHA == 1) #if (FXAA_DISCARD == 0) FxaaFloat4 rgbyM = FxaaTexTop(tex, posM); #if (FXAA_GREEN_AS_LUMA == 0) #define lumaM rgbyM.w #else #define lumaM rgbyM.y #endif #endif #if (FXAA_GREEN_AS_LUMA == 0) FxaaFloat4 luma4A = FxaaTexAlpha4(tex, posM); FxaaFloat4 luma4B = FxaaTexOffAlpha4(tex, posM, FxaaInt2(-1, -1)); #else FxaaFloat4 luma4A = FxaaTexGreen4(tex, posM); FxaaFloat4 luma4B = FxaaTexOffGreen4(tex, posM, FxaaInt2(-1, -1)); #endif #if (FXAA_DISCARD == 1) #define lumaM luma4A.w #endif #define lumaE luma4A.z #define lumaS luma4A.x #define lumaSE luma4A.y #define lumaNW luma4B.w #define lumaN luma4B.z #define lumaW luma4B.x #else FxaaFloat4 rgbyM = FxaaTexTop(tex, posM); #if (FXAA_GREEN_AS_LUMA == 0) #define lumaM rgbyM.w #else #define lumaM rgbyM.y #endif #if (FXAA_GLSL_100 == 1) FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 0.0, 1.0), fxaaQualityRcpFrame.xy)); FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 1.0, 0.0), fxaaQualityRcpFrame.xy)); FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 0.0,-1.0), fxaaQualityRcpFrame.xy)); FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2(-1.0, 0.0), fxaaQualityRcpFrame.xy)); #else FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy)); FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy)); #endif #endif /*--------------------------------------------------------------------------*/ FxaaFloat maxSM = max(lumaS, lumaM); FxaaFloat minSM = min(lumaS, lumaM); FxaaFloat maxESM = max(lumaE, maxSM); FxaaFloat minESM = min(lumaE, minSM); FxaaFloat maxWN = max(lumaN, lumaW); FxaaFloat minWN = min(lumaN, lumaW); FxaaFloat rangeMax = max(maxWN, maxESM); FxaaFloat rangeMin = min(minWN, minESM); FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold; FxaaFloat range = rangeMax - rangeMin; FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled); FxaaBool earlyExit = range < rangeMaxClamped; /*--------------------------------------------------------------------------*/ if(earlyExit) #if (FXAA_DISCARD == 1) FxaaDiscard; #else return rgbyM; #endif /*--------------------------------------------------------------------------*/ #if (FXAA_GATHER4_ALPHA == 0) #if (FXAA_GLSL_100 == 1) FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2(-1.0,-1.0), fxaaQualityRcpFrame.xy)); FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 1.0, 1.0), fxaaQualityRcpFrame.xy)); FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2( 1.0,-1.0), fxaaQualityRcpFrame.xy)); FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaFloat2(-1.0, 1.0), fxaaQualityRcpFrame.xy)); #else FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy)); #endif #else FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy)); #endif /*--------------------------------------------------------------------------*/ FxaaFloat lumaNS = lumaN + lumaS; FxaaFloat lumaWE = lumaW + lumaE; FxaaFloat subpixRcpRange = 1.0/range; FxaaFloat subpixNSWE = lumaNS + lumaWE; FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS; FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE; /*--------------------------------------------------------------------------*/ FxaaFloat lumaNESE = lumaNE + lumaSE; FxaaFloat lumaNWNE = lumaNW + lumaNE; FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE; FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE; /*--------------------------------------------------------------------------*/ FxaaFloat lumaNWSW = lumaNW + lumaSW; FxaaFloat lumaSWSE = lumaSW + lumaSE; FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2); FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2); FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW; FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE; FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4; FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4; /*--------------------------------------------------------------------------*/ FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE; FxaaFloat lengthSign = fxaaQualityRcpFrame.x; FxaaBool horzSpan = edgeHorz >= edgeVert; FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE; /*--------------------------------------------------------------------------*/ if(!horzSpan) lumaN = lumaW; if(!horzSpan) lumaS = lumaE; if(horzSpan) lengthSign = fxaaQualityRcpFrame.y; FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM; /*--------------------------------------------------------------------------*/ FxaaFloat gradientN = lumaN - lumaM; FxaaFloat gradientS = lumaS - lumaM; FxaaFloat lumaNN = lumaN + lumaM; FxaaFloat lumaSS = lumaS + lumaM; FxaaBool pairN = abs(gradientN) >= abs(gradientS); FxaaFloat gradient = max(abs(gradientN), abs(gradientS)); if(pairN) lengthSign = -lengthSign; FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange); /*--------------------------------------------------------------------------*/ FxaaFloat2 posB; posB.x = posM.x; posB.y = posM.y; FxaaFloat2 offNP; offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x; offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y; if(!horzSpan) posB.x += lengthSign * 0.5; if( horzSpan) posB.y += lengthSign * 0.5; /*--------------------------------------------------------------------------*/ FxaaFloat2 posN; posN.x = posB.x - offNP.x * FXAA_QUALITY_P0; posN.y = posB.y - offNP.y * FXAA_QUALITY_P0; FxaaFloat2 posP; posP.x = posB.x + offNP.x * FXAA_QUALITY_P0; posP.y = posB.y + offNP.y * FXAA_QUALITY_P0; FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0; FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN)); FxaaFloat subpixE = subpixC * subpixC; FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP)); /*--------------------------------------------------------------------------*/ if(!pairN) lumaNN = lumaSS; FxaaFloat gradientScaled = gradient * 1.0/4.0; FxaaFloat lumaMM = lumaM - lumaNN * 0.5; FxaaFloat subpixF = subpixD * subpixE; FxaaBool lumaMLTZero = lumaMM < 0.0; /*--------------------------------------------------------------------------*/ lumaEndN -= lumaNN * 0.5; lumaEndP -= lumaNN * 0.5; FxaaBool doneN = abs(lumaEndN) >= gradientScaled; FxaaBool doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P1; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P1; FxaaBool doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P1; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P1; /*--------------------------------------------------------------------------*/ if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P2; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P2; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P2; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P2; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 3) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P3; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P3; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P3; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P3; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 4) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P4; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P4; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P4; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P4; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 5) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P5; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P5; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P5; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P5; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 6) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P6; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P6; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P6; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P6; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 7) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P7; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P7; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P7; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P7; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 8) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P8; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P8; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P8; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P8; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 9) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P9; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P9; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P9; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P9; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 10) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P10; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P10; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P10; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P10; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 11) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P11; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P11; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P11; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P11; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 12) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P12; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P12; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P12; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P12; /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } /*--------------------------------------------------------------------------*/ FxaaFloat dstN = posM.x - posN.x; FxaaFloat dstP = posP.x - posM.x; if(!horzSpan) dstN = posM.y - posN.y; if(!horzSpan) dstP = posP.y - posM.y; /*--------------------------------------------------------------------------*/ FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero; FxaaFloat spanLength = (dstP + dstN); FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero; FxaaFloat spanLengthRcp = 1.0/spanLength; /*--------------------------------------------------------------------------*/ FxaaBool directionN = dstN < dstP; FxaaFloat dst = min(dstN, dstP); FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP; FxaaFloat subpixG = subpixF * subpixF; FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5; FxaaFloat subpixH = subpixG * fxaaQualitySubpix; /*--------------------------------------------------------------------------*/ FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0; FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH); if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign; if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign; #if (FXAA_DISCARD == 1) return FxaaTexTop(tex, posM); #else return FxaaFloat4(FxaaTexTop(tex, posM).xyz, lumaM); #endif } /*==========================================================================*/ #endif void main() { gl_FragColor = FxaaPixelShader( vUv, vec4(0.0), tDiffuse, tDiffuse, tDiffuse, resolution, vec4(0.0), vec4(0.0), vec4(0.0), 0.75, 0.166, 0.0833, 0.0, 0.0, 0.0, vec4(0.0) ); // TODO avoid querying texture twice for same texel gl_FragColor.a = texture2D(tDiffuse, vUv).a; } ` ) }; // node_modules/three-stdlib/shaders/FreiChenShader.js var 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 vectors 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-stdlib/shaders/GammaCorrectionShader.js var 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 ); #ifdef LinearTosRGB gl_FragColor = LinearTosRGB( tex ); #else gl_FragColor = sRGBTransferOETF( tex ); #endif } ` ) }; // node_modules/three-stdlib/shaders/GodRaysShader.js var 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 didnt do much on my hardware (ATI Mobility Radeon 3450), // so ive just left the loop for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) { // Accumulate samples, making sure we dont 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 dont 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 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-stdlib/shaders/HorizontalBlurShader.js var 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-stdlib/shaders/HorizontalTiltShiftShader.js var 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-stdlib/shaders/NormalMapShader.js var 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-stdlib/shaders/SobelOperatorShader.js var 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; // magnitute of the total gradient float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) ); gl_FragColor = vec4( vec3( G ), 1 ); } ` ) }; // node_modules/three-stdlib/shaders/ToonShader.js var 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 ); } } ` ) }; 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 ); } } ` ) }; 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 ); } } } ` ) }; 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 ); } } } ` ) }; // node_modules/three-stdlib/shaders/TriangleBlurShader.js var 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 #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-stdlib/shaders/VerticalBlurShader.js var 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-stdlib/shaders/VerticalTiltShiftShader.js var 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-stdlib/shaders/VolumeShader.js var 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= 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= 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 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 devision) 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-stdlib/interactive/InteractiveGroup.js var _pointer = new Vector2(); // node_modules/three-stdlib/interactive/SelectionBox.js var frustum = new Frustum(); var center2 = 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 SelectionBox = class { constructor(camera, scene, deep) { this.camera = camera; this.scene = scene; this.startPoint = new Vector3(); this.endPoint = new Vector3(); this.collection = []; this.deep = deep || Number.MAX_VALUE; } 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; } 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); var 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); var 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(frustum2, object) { if (object.isMesh || object.isLine || object.isPoints) { if (object.material !== void 0) { if (object.geometry.boundingSphere === null) object.geometry.computeBoundingSphere(); center2.copy(object.geometry.boundingSphere.center); center2.applyMatrix4(object.matrixWorld); if (frustum2.containsPoint(center2)) { this.collection.push(object); } } } if (object.children.length > 0) { for (let x = 0; x < object.children.length; x++) { this.searchChildInFrustum(frustum2, object.children[x]); } } } }; // node_modules/three-stdlib/effects/AsciiEffect.js var AsciiEffect = class { constructor(renderer, 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 width, height; 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) { width = w; height = h; renderer.setSize(w, h); initAsciiSize(); }; this.render = function(scene, camera) { renderer.render(scene, camera); asciifyImage(oAscii); }; this.domElement = domElement; function initAsciiSize() { iWidth = Math.floor(width * fResolution); iHeight = Math.floor(height * fResolution); oCanvas.width = iWidth; oCanvas.height = iHeight; oImg = renderer.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 aDefaultCharList = " .,:;i1tfLCG08@".split(""); const aDefaultColorCharList = " CGO08@".split(""); const strFont = "courier new, monospace"; const oCanvasImg = renderer.domElement; const oCanvas = document.createElement("canvas"); if (!oCanvas.getContext) { return; } const oCtx = oCanvas.getContext("2d"); if (!oCtx.getImageData) { return; } let aCharList = bColor ? aDefaultColorCharList : aDefaultCharList; if (charSet) aCharList = charSet; 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 x = 0; x < iWidth; x++) { const iOffset = (y * iWidth + x) * 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 = " "; if (bColor) { strChars += "" + strThisChar + ""; } else { strChars += strThisChar; } } strChars += "
"; } oAscii2.innerHTML = `${strChars}`; } } }; // node_modules/three-stdlib/curves/NURBSUtils.js function findSpan(p2, u, U) { const n2 = U.length - p2 - 1; if (u >= U[n2]) { return n2 - 1; } if (u <= U[p2]) { return p2; } let low = p2; let high = n2; let mid = Math.floor((low + high) / 2); while (u < U[mid] || u >= U[mid + 1]) { if (u < U[mid]) { high = mid; } else { low = mid; } mid = Math.floor((low + high) / 2); } return mid; } function calcBasisFunctions(span, u, p2, U) { const N = []; const left = []; const right = []; N[0] = 1; for (let j = 1; j <= p2; ++j) { left[j] = u - U[span + 1 - j]; right[j] = U[span + j] - u; let saved = 0; for (let r2 = 0; r2 < j; ++r2) { const rv = right[r2 + 1]; const lv = left[j - r2]; const temp5 = N[r2] / (rv + lv); N[r2] = saved + rv * temp5; saved = lv * temp5; } N[j] = saved; } return N; } function calcBSplinePoint(p2, U, P, u) { const span = findSpan(p2, u, U); const N = calcBasisFunctions(span, u, p2, U); const C = new Vector4(0, 0, 0, 0); for (let j = 0; j <= p2; ++j) { const point = P[span - p2 + j]; const Nj = N[j]; const wNj = point.w * Nj; C.x += point.x * wNj; C.y += point.y * wNj; C.z += point.z * wNj; C.w += point.w * Nj; } return C; } function calcBasisFunctionDerivatives(span, u, p2, n2, U) { const zeroArr = []; for (let i4 = 0; i4 <= p2; ++i4) zeroArr[i4] = 0; const ders = []; for (let i4 = 0; i4 <= n2; ++i4) ders[i4] = zeroArr.slice(0); const ndu = []; for (let i4 = 0; i4 <= p2; ++i4) ndu[i4] = zeroArr.slice(0); ndu[0][0] = 1; const left = zeroArr.slice(0); const right = zeroArr.slice(0); for (let j = 1; j <= p2; ++j) { left[j] = u - U[span + 1 - j]; right[j] = U[span + j] - u; let saved = 0; for (let r22 = 0; r22 < j; ++r22) { const rv = right[r22 + 1]; const lv = left[j - r22]; ndu[j][r22] = rv + lv; const temp5 = ndu[r22][j - 1] / ndu[j][r22]; ndu[r22][j] = saved + rv * temp5; saved = lv * temp5; } ndu[j][j] = saved; } for (let j = 0; j <= p2; ++j) { ders[0][j] = ndu[j][p2]; } for (let r22 = 0; r22 <= p2; ++r22) { let s1 = 0; let s2 = 1; const a6 = []; for (let i4 = 0; i4 <= p2; ++i4) { a6[i4] = zeroArr.slice(0); } a6[0][0] = 1; for (let k = 1; k <= n2; ++k) { let d2 = 0; const rk = r22 - k; const pk = p2 - k; if (r22 >= k) { a6[s2][0] = a6[s1][0] / ndu[pk + 1][rk]; d2 = a6[s2][0] * ndu[rk][pk]; } const j1 = rk >= -1 ? 1 : -rk; const j2 = r22 - 1 <= pk ? k - 1 : p2 - r22; for (let j3 = j1; j3 <= j2; ++j3) { a6[s2][j3] = (a6[s1][j3] - a6[s1][j3 - 1]) / ndu[pk + 1][rk + j3]; d2 += a6[s2][j3] * ndu[rk + j3][pk]; } if (r22 <= pk) { a6[s2][k] = -a6[s1][k - 1] / ndu[pk + 1][r22]; d2 += a6[s2][k] * ndu[r22][pk]; } ders[k][r22] = d2; const j = s1; s1 = s2; s2 = j; } } let r2 = p2; for (let k = 1; k <= n2; ++k) { for (let j = 0; j <= p2; ++j) { ders[k][j] *= r2; } r2 *= p2 - k; } return ders; } function calcBSplineDerivatives(p2, U, P, u, nd) { const du = nd < p2 ? nd : p2; const CK = []; const span = findSpan(p2, u, U); const nders = calcBasisFunctionDerivatives(span, u, p2, du, U); const Pw = []; for (let i4 = 0; i4 < P.length; ++i4) { const point = P[i4].clone(); const w = point.w; point.x *= w; point.y *= w; point.z *= w; Pw[i4] = point; } for (let k = 0; k <= du; ++k) { const point = Pw[span - p2].clone().multiplyScalar(nders[k][0]); for (let j = 1; j <= p2; ++j) { point.add(Pw[span - p2 + j].clone().multiplyScalar(nders[k][j])); } CK[k] = point; } for (let k = du + 1; k <= nd + 1; ++k) { CK[k] = new Vector4(0, 0, 0); } return CK; } function calcKoverI(k, i4) { let nom = 1; for (let j = 2; j <= k; ++j) { nom *= j; } let denom = 1; for (let j = 2; j <= i4; ++j) { denom *= j; } for (let j = 2; j <= k - i4; ++j) { denom *= j; } return nom / denom; } function calcRationalCurveDerivatives(Pders) { const nd = Pders.length; const Aders = []; const wders = []; for (let i4 = 0; i4 < nd; ++i4) { const point = Pders[i4]; Aders[i4] = new Vector3(point.x, point.y, point.z); wders[i4] = point.w; } const CK = []; for (let k = 0; k < nd; ++k) { const v5 = Aders[k].clone(); for (let i4 = 1; i4 <= k; ++i4) { v5.sub(CK[k - i4].clone().multiplyScalar(calcKoverI(k, i4) * wders[i4])); } CK[k] = v5.divideScalar(wders[0]); } return CK; } function calcNURBSDerivatives(p2, U, P, u, nd) { const Pders = calcBSplineDerivatives(p2, U, P, u, nd); return calcRationalCurveDerivatives(Pders); } // node_modules/three-stdlib/curves/NURBSCurve.js var NURBSCurve = class extends Curve { constructor(degree, knots, controlPoints, startKnot, endKnot) { super(); this.degree = degree; this.knots = knots; this.controlPoints = []; this.startKnot = startKnot || 0; this.endKnot = endKnot || this.knots.length - 1; for (let i4 = 0; i4 < controlPoints.length; ++i4) { const point = controlPoints[i4]; this.controlPoints[i4] = new Vector4(point.x, point.y, point.z, point.w); } } getPoint(t3, optionalTarget) { const point = optionalTarget || new Vector3(); const u = this.knots[this.startKnot] + t3 * (this.knots[this.endKnot] - this.knots[this.startKnot]); const hpoint = calcBSplinePoint(this.degree, this.knots, this.controlPoints, u); if (hpoint.w != 1) { hpoint.divideScalar(hpoint.w); } return point.set(hpoint.x, hpoint.y, hpoint.z); } getTangent(t3, optionalTarget) { const tangent = optionalTarget || new Vector3(); const u = this.knots[0] + t3 * (this.knots[this.knots.length - 1] - this.knots[0]); const ders = calcNURBSDerivatives(this.degree, this.knots, this.controlPoints, u, 1); tangent.copy(ders[1]).normalize(); return tangent; } }; // node_modules/three-stdlib/loaders/FBXLoader.js var fbxTree; var connections; var sceneGraph; var FBXLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const path = scope.path === "" ? LoaderUtils.extractUrlBase(url) : scope.path; const loader2 = new FileLoader(this.manager); loader2.setPath(scope.path); loader2.setResponseType("arraybuffer"); loader2.setRequestHeader(scope.requestHeader); loader2.setWithCredentials(scope.withCredentials); loader2.load( url, function(buffer2) { try { onLoad(scope.parse(buffer2, path)); } catch (e2) { if (onError) { onError(e2); } else { console.error(e2); } scope.manager.itemError(url); } }, onProgress, onError ); } 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 content = 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; default: console.warn('FBXLoader: Image type "' + extension + '" is not supported.'); return; } if (typeof content === "string") { return "data:" + type + ";base64," + content; } else { const array = new Uint8Array(content); 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 values = textureNode.Scaling.value; texture.repeat.x = values[0]; texture.repeat.y = values[1]; } return texture; } // load a texture specified as a blob or data URI, or via an external URL using TextureLoader loadTexture(textureNode, images) { let fileName; const currentPath = this.textureLoader.path; const children = connections.get(textureNode.id).children; 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) { this.textureLoader.setPath(void 0); } } let texture; const extension = textureNode.FileName.slice(-3).toLowerCase(); if (extension === "tga") { const loader2 = this.manager.getHandler(".tga"); if (loader2 === null) { console.warn("FBXLoader: TGA loader not found, creating placeholder texture for", textureNode.RelativeFilename); texture = new Texture(); } else { loader2.setPath(this.textureLoader.path); texture = loader2.load(fileName); } } else if (extension === "psd") { console.warn( "FBXLoader: PSD textures are not supported, creating placeholder texture for", textureNode.RelativeFilename ); texture = new Texture(); } else { texture = this.textureLoader.load(fileName); } this.textureLoader.setPath(currentPath); 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 name = 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 = name; 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 = new Color().fromArray(materialNode.Diffuse.value); } else if (materialNode.DiffuseColor && (materialNode.DiffuseColor.type === "Color" || materialNode.DiffuseColor.type === "ColorRGB")) { parameters.color = new Color().fromArray(materialNode.DiffuseColor.value); } if (materialNode.DisplacementFactor) { parameters.displacementScale = materialNode.DisplacementFactor.value; } if (materialNode.Emissive) { parameters.emissive = new Color().fromArray(materialNode.Emissive.value); } else if (materialNode.EmissiveColor && (materialNode.EmissiveColor.type === "Color" || materialNode.EmissiveColor.type === "ColorRGB")) { parameters.emissive = new Color().fromArray(materialNode.EmissiveColor.value); } if (materialNode.EmissiveFactor) { parameters.emissiveIntensity = parseFloat(materialNode.EmissiveFactor.value); } if (materialNode.Opacity) { parameters.opacity = parseFloat(materialNode.Opacity.value); } 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 = new Color().fromArray(materialNode.Specular.value); } else if (materialNode.SpecularColor && materialNode.SpecularColor.type === "Color") { parameters.specular = new Color().fromArray(materialNode.SpecularColor.value); } 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) { if ("colorSpace" in parameters.map) parameters.map.colorSpace = "srgb"; else parameters.map.encoding = 3001; } 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) { if ("colorSpace" in parameters.emissiveMap) parameters.emissiveMap.colorSpace = "srgb"; else parameters.emissiveMap.encoding = 3001; } 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; if ("colorSpace" in parameters.envMap) parameters.envMap.colorSpace = "srgb"; else parameters.envMap.encoding = 3001; } break; case "SpecularColor": parameters.specularMap = scope.getTexture(textureMap, child.ID); if (parameters.specularMap !== void 0) { if ("colorSpace" in parameters.specularMap) parameters.specularMap.colorSpace = "srgb"; else parameters.specularMap.encoding = 3001; } break; case "TransparentColor": case "TransparencyFactor": parameters.alphaMap = scope.getTexture(textureMap, child.ID); parameters.transparent = true; break; case "AmbientColor": case "ShininessExponent": case "SpecularFactor": case "VectorDisplacementColor": 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 i4 = 0; i4 < relationships.children.length; i4++) { const child = relationships.children[i4]; 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 parent = modelMap.get(connection.ID); if (parent !== void 0) parent.add(model); }); if (model.parent === null) { sceneGraph.add(model); } }); this.bindSkeleton(deformers.skeletons, geometryMap, modelMap); this.createAmbientLight(); 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 transform = generateTransform(node.userData.transformData); node.applyMatrix4(transform); 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.ID = id; } this.getTransformData(model, node); modelMap.set(id, model); } return modelMap; } buildSkeleton(relationships, skeletons, id, name) { let bone = null; relationships.parents.forEach(function(parent) { for (const ID in skeletons) { const skeleton = skeletons[ID]; skeleton.rawBones.forEach(function(rawBone, i4) { if (rawBone.ID === parent.ID) { const subBone = bone; bone = new Bone(); bone.matrixWorld.copy(rawBone.transformLink); bone.name = name ? PropertyBinding.sanitizeNodeName(name) : ""; bone.ID = id; skeleton.bones[i4] = 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 width = window.innerWidth; let height = window.innerHeight; if (cameraAttribute.AspectWidth !== void 0 && cameraAttribute.AspectHeight !== void 0) { width = cameraAttribute.AspectWidth.value; height = cameraAttribute.AspectHeight.value; } const aspect = width / height; 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: model = new OrthographicCamera( -width / 2, width / 2, height / 2, -height / 2, nearClippingPlane, farClippingPlane ); 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 = new Color().fromArray(lightAttribute.Color.value); } let intensity = lightAttribute.Intensity === void 0 ? 1 : lightAttribute.Intensity.value / 100; if (lightAttribute.CastLightOnObject !== void 0 && lightAttribute.CastLightOnObject.value === 0) { intensity = 0; } let distance3 = 0; if (lightAttribute.FarAttenuationEnd !== void 0) { if (lightAttribute.EnableFarAttenuation !== void 0 && lightAttribute.EnableFarAttenuation.value === 0) { distance3 = 0; } else { distance3 = lightAttribute.FarAttenuationEnd.value; } } const decay = 1; switch (type) { case 0: model = new PointLight(color, intensity, distance3, 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, distance3, 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 geometry3 = null; let material = null; const materials = []; relationships.children.forEach(function(child) { if (geometryMap.has(child.ID)) { geometry3 = 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({ color: 13421772 }); materials.push(material); } if ("color" in geometry3.attributes) { materials.forEach(function(material2) { material2.vertexColors = true; }); } if (geometry3.FBX_Deformer) { model = new SkinnedMesh(geometry3, material); model.normalizeSkinWeights(); } else { model = new Mesh(geometry3, material); } return model; } createCurve(relationships, geometryMap) { const geometry3 = relationships.children.reduce(function(geo, child) { if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID); return geo; }, null); const material = new LineBasicMaterial({ color: 3342591, linewidth: 1 }); return new Line(geometry3, 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 = "ZYX"; 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(parent) { if (geometryMap.has(parent.ID)) { const geoID = parent.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; } // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light createAmbientLight() { if ("GlobalSettings" in fbxTree && "AmbientColor" in fbxTree.GlobalSettings) { const ambientColor = fbxTree.GlobalSettings.AmbientColor.value; const r2 = ambientColor[0]; const g = ambientColor[1]; const b5 = ambientColor[2]; if (r2 !== 0 || g !== 0 || b5 !== 0) { const color = new Color(r2, g, b5); sceneGraph.add(new AmbientLight(color, 1)); } } } }; var GeometryParser = class { // 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); } } return geometryMap; } // Parse single node in FBXTree.Objects.Geometry parseGeometry(relationships, geoNode, deformers) { switch (geoNode.attrType) { case "Mesh": return this.parseMeshGeometry(relationships, geoNode, deformers); case "NurbsCurve": return this.parseNurbsGeometry(geoNode); } } // 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(parent) { return fbxTree.Objects.Model[parent.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 transform = generateTransform(transformData); return this.genGeometry(geoNode, skeleton, morphTargets, transform); } // 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, i4) { if (UV1 === "uv2") i4++; const name = i4 === 0 ? "uv" : `uv${i4}`; geo.setAttribute(name, new Float32BufferAttribute(buffers.uvs[i4], 2)); }); if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") { let prevMaterialIndex = buffers.materialIndex[0]; let startIndex = 0; buffers.materialIndex.forEach(function(currentIndex, i4) { if (currentIndex !== prevMaterialIndex) { geo.addGroup(startIndex, i4 - startIndex, prevMaterialIndex); prevMaterialIndex = currentIndex; startIndex = i4; } }); 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) { 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 i4 = 0; while (geoNode.LayerElementUV[i4]) { if (geoNode.LayerElementUV[i4].UV) { geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i4])); } i4++; } } geoInfo.weightTable = {}; if (skeleton !== null) { geoInfo.skeleton = skeleton; skeleton.rawBones.forEach(function(rawBone, i4) { rawBone.indices.forEach(function(index2, j) { if (geoInfo.weightTable[index2] === void 0) geoInfo.weightTable[index2] = []; geoInfo.weightTable[index2].push({ id: i4, weight: rawBone.weights[j] }); }); }); } 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 data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color); faceColors.push(data[0], data[1], data[2]); } if (geoInfo.skeleton) { if (geoInfo.weightTable[vertexIndex] !== void 0) { geoInfo.weightTable[vertexIndex].forEach(function(wt) { weights.push(wt.weight); weightIndices.push(wt.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 i4 = 0; i4 < 4; ++i4) { faceWeights.push(weights[i4]); faceWeightIndices.push(weightIndices[i4]); } } if (geoInfo.normal) { const data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal); faceNormals.push(data[0], data[1], data[2]); } if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") { materialIndex = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material)[0]; } if (geoInfo.uv) { geoInfo.uv.forEach(function(uv, i4) { const data = getData(polygonVertexIndex, polygonIndex, vertexIndex, uv); if (faceUVs[i4] === void 0) { faceUVs[i4] = []; } faceUVs[i4].push(data[0]); faceUVs[i4].push(data[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; } // 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) { for (let i4 = 2; i4 < faceLength; i4++) { buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[0]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[1]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[2]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i4 - 1) * 3]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i4 - 1) * 3 + 1]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i4 - 1) * 3 + 2]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i4 * 3]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i4 * 3 + 1]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i4 * 3 + 2]]); if (geoInfo.skeleton) { buffers.vertexWeights.push(faceWeights[0]); buffers.vertexWeights.push(faceWeights[1]); buffers.vertexWeights.push(faceWeights[2]); buffers.vertexWeights.push(faceWeights[3]); buffers.vertexWeights.push(faceWeights[(i4 - 1) * 4]); buffers.vertexWeights.push(faceWeights[(i4 - 1) * 4 + 1]); buffers.vertexWeights.push(faceWeights[(i4 - 1) * 4 + 2]); buffers.vertexWeights.push(faceWeights[(i4 - 1) * 4 + 3]); buffers.vertexWeights.push(faceWeights[i4 * 4]); buffers.vertexWeights.push(faceWeights[i4 * 4 + 1]); buffers.vertexWeights.push(faceWeights[i4 * 4 + 2]); buffers.vertexWeights.push(faceWeights[i4 * 4 + 3]); buffers.weightsIndices.push(faceWeightIndices[0]); buffers.weightsIndices.push(faceWeightIndices[1]); buffers.weightsIndices.push(faceWeightIndices[2]); buffers.weightsIndices.push(faceWeightIndices[3]); buffers.weightsIndices.push(faceWeightIndices[(i4 - 1) * 4]); buffers.weightsIndices.push(faceWeightIndices[(i4 - 1) * 4 + 1]); buffers.weightsIndices.push(faceWeightIndices[(i4 - 1) * 4 + 2]); buffers.weightsIndices.push(faceWeightIndices[(i4 - 1) * 4 + 3]); buffers.weightsIndices.push(faceWeightIndices[i4 * 4]); buffers.weightsIndices.push(faceWeightIndices[i4 * 4 + 1]); buffers.weightsIndices.push(faceWeightIndices[i4 * 4 + 2]); buffers.weightsIndices.push(faceWeightIndices[i4 * 4 + 3]); } if (geoInfo.color) { buffers.colors.push(faceColors[0]); buffers.colors.push(faceColors[1]); buffers.colors.push(faceColors[2]); buffers.colors.push(faceColors[(i4 - 1) * 3]); buffers.colors.push(faceColors[(i4 - 1) * 3 + 1]); buffers.colors.push(faceColors[(i4 - 1) * 3 + 2]); buffers.colors.push(faceColors[i4 * 3]); buffers.colors.push(faceColors[i4 * 3 + 1]); buffers.colors.push(faceColors[i4 * 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[0]); buffers.normal.push(faceNormals[1]); buffers.normal.push(faceNormals[2]); buffers.normal.push(faceNormals[(i4 - 1) * 3]); buffers.normal.push(faceNormals[(i4 - 1) * 3 + 1]); buffers.normal.push(faceNormals[(i4 - 1) * 3 + 2]); buffers.normal.push(faceNormals[i4 * 3]); buffers.normal.push(faceNormals[i4 * 3 + 1]); buffers.normal.push(faceNormals[i4 * 3 + 2]); } if (geoInfo.uv) { geoInfo.uv.forEach(function(uv, j) { if (buffers.uvs[j] === void 0) buffers.uvs[j] = []; buffers.uvs[j].push(faceUVs[j][0]); buffers.uvs[j].push(faceUVs[j][1]); buffers.uvs[j].push(faceUVs[j][(i4 - 1) * 2]); buffers.uvs[j].push(faceUVs[j][(i4 - 1) * 2 + 1]); buffers.uvs[j].push(faceUVs[j][i4 * 2]); buffers.uvs[j].push(faceUVs[j][i4 * 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, name) { const vertexIndices = parentGeoNode.PolygonVertexIndex !== void 0 ? parentGeoNode.PolygonVertexIndex.a : []; const morphPositionsSparse = morphGeoNode.Vertices !== void 0 ? morphGeoNode.Vertices.a : []; const indices = morphGeoNode.Indexes !== void 0 ? morphGeoNode.Indexes.a : []; const length3 = parentGeo.attributes.position.count * 3; const morphPositions = new Float32Array(length3); for (let i4 = 0; i4 < indices.length; i4++) { const morphIndex = indices[i4] * 3; morphPositions[morphIndex] = morphPositionsSparse[i4 * 3]; morphPositions[morphIndex + 1] = morphPositionsSparse[i4 * 3 + 1]; morphPositions[morphIndex + 2] = morphPositionsSparse[i4 * 3 + 2]; } const morphGeoInfo = { vertexIndices, vertexPositions: morphPositions }; const morphBuffers = this.genBuffers(morphGeoInfo); const positionAttribute = new Float32BufferAttribute(morphBuffers.vertex, 3); positionAttribute.name = name || 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 buffer2 = 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: buffer2, 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 buffer2 = UVNode.UV.a; let indexBuffer = []; if (referenceType === "IndexToDirect") { indexBuffer = UVNode.UVIndex.a; } return { dataSize: 2, buffer: buffer2, 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 buffer2 = ColorNode.Colors.a; let indexBuffer = []; if (referenceType === "IndexToDirect") { indexBuffer = ColorNode.ColorIndex.a; } return { dataSize: 4, buffer: buffer2, 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 i4 = 0; i4 < materialIndexBuffer.length; ++i4) { materialIndices.push(i4); } return { dataSize: 1, buffer: materialIndexBuffer, indices: materialIndices, mappingType, referenceType }; } // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry parseNurbsGeometry(geoNode) { if (NURBSCurve === void 0) { console.error( "THREE.FBXLoader: The loader relies on NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry." ); return new BufferGeometry(); } 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 i4 = 0, l2 = pointsValues.length; i4 < l2; i4 += 4) { controlPoints.push(new Vector4().fromArray(pointsValues, i4)); } 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 i4 = 0; i4 < degree; ++i4) { controlPoints.push(controlPoints[i4]); } } 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 key in rawClips) { const rawClip = rawClips[key]; 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(/d|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, i4) { 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[i4] === void 0) { const modelID = connections.get(child.ID).parents.filter(function(parent) { return parent.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[i4] = node; } } if (layerCurveNodes[i4]) layerCurveNodes[i4][curveNode.attr] = curveNode; } else if (curveNode.curves.morph !== void 0) { if (layerCurveNodes[i4] === void 0) { const deformerID = connections.get(child.ID).parents.filter(function(parent) { return parent.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[i4] = node; } layerCurveNodes[i4][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 a 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 initialRotation = new Quaternion(); let initialScale = new Vector3(); if (rawTracks.transform) rawTracks.transform.decompose(initialPosition, initialRotation, initialScale); initialPosition = initialPosition.toArray(); initialRotation = new Euler().setFromQuaternion(initialRotation, rawTracks.eulerOrder).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, initialRotation, 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 values = this.getKeyframeTrackValues(times, curves, initialValue); return new VectorKeyframeTrack(modelName + "." + type, times, values); } generateRotationTrack(modelName, curves, initialValue, preRotation, postRotation, eulerOrder) { if (curves.x !== void 0) { this.interpolateRotations(curves.x); curves.x.values = curves.x.values.map(MathUtils.degToRad); } if (curves.y !== void 0) { this.interpolateRotations(curves.y); curves.y.values = curves.y.values.map(MathUtils.degToRad); } if (curves.z !== void 0) { this.interpolateRotations(curves.z); curves.z.values = curves.z.values.map(MathUtils.degToRad); } const times = this.getTimesForAllAxes(curves); const values = this.getKeyframeTrackValues(times, curves, initialValue); if (preRotation !== void 0) { preRotation = preRotation.map(MathUtils.degToRad); preRotation.push(eulerOrder); preRotation = new Euler().fromArray(preRotation); preRotation = new Quaternion().setFromEuler(preRotation); } if (postRotation !== void 0) { postRotation = postRotation.map(MathUtils.degToRad); postRotation.push(eulerOrder); postRotation = new Euler().fromArray(postRotation); postRotation = new Quaternion().setFromEuler(postRotation).invert(); } const quaternion = new Quaternion(); const euler = new Euler(); const quaternionValues = []; for (let i4 = 0; i4 < values.length; i4 += 3) { euler.set(values[i4], values[i4 + 1], values[i4 + 2], eulerOrder); quaternion.setFromEuler(euler); if (preRotation !== void 0) quaternion.premultiply(preRotation); if (postRotation !== void 0) quaternion.multiply(postRotation); quaternion.toArray(quaternionValues, i4 / 3 * 4); } return new QuaternionKeyframeTrack(modelName + ".quaternion", times, quaternionValues); } generateMorphTrack(rawTracks) { const curves = rawTracks.DeformPercent.curves.morph; const values = curves.values.map(function(val) { return val / 100; }); const morphNum = sceneGraph.getObjectByName(rawTracks.modelName).morphTargetDictionary[rawTracks.morphName]; return new NumberKeyframeTrack( rawTracks.modelName + ".morphTargetInfluences[" + morphNum + "]", curves.times, values ); } // 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(a6, b5) { return a6 - b5; }); if (times.length > 1) { let targetIndex = 1; let lastValue = times[0]; for (let i4 = 1; i4 < times.length; i4++) { const currentValue = times[i4]; if (currentValue !== lastValue) { times[targetIndex] = currentValue; lastValue = currentValue; targetIndex++; } } times = times.slice(0, targetIndex); } return times; } getKeyframeTrackValues(times, curves, initialValue) { const prevValue = initialValue; const values = []; let xIndex = -1; let yIndex = -1; let zIndex = -1; times.forEach(function(time) { if (curves.x) xIndex = curves.x.times.indexOf(time); if (curves.y) yIndex = curves.y.times.indexOf(time); if (curves.z) zIndex = curves.z.times.indexOf(time); if (xIndex !== -1) { const xValue = curves.x.values[xIndex]; values.push(xValue); prevValue[0] = xValue; } else { values.push(prevValue[0]); } if (yIndex !== -1) { const yValue = curves.y.values[yIndex]; values.push(yValue); prevValue[1] = yValue; } else { values.push(prevValue[1]); } if (zIndex !== -1) { const zValue = curves.z.values[zIndex]; values.push(zValue); prevValue[2] = zValue; } else { values.push(prevValue[2]); } }); return values; } // 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(curve) { for (let i4 = 1; i4 < curve.values.length; i4++) { const initialValue = curve.values[i4 - 1]; const valuesSpan = curve.values[i4] - initialValue; const absoluteSpan = Math.abs(valuesSpan); if (absoluteSpan >= 180) { const numSubIntervals = absoluteSpan / 180; const step = valuesSpan / numSubIntervals; let nextValue = initialValue + step; const initialTime = curve.times[i4 - 1]; const timeSpan = curve.times[i4] - initialTime; const interval = timeSpan / numSubIntervals; let nextTime = initialTime + interval; const interpolatedTimes = []; const interpolatedValues = []; while (nextTime < curve.times[i4]) { interpolatedTimes.push(nextTime); nextTime += interval; interpolatedValues.push(nextValue); nextValue += step; } curve.times = inject(curve.times, i4, interpolatedTimes); curve.values = inject(curve.values, i4, interpolatedValues); } } } }; 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(val, name) { this.currentProp = val; this.currentPropName = name; } parse(text) { this.currentIndent = 0; this.allNodes = new FBXTree(); this.nodeStack = []; this.currentProp = []; this.currentPropName = ""; const scope = this; const split = text.split(/[\r\n]+/); split.forEach(function(line, i4) { const matchComment = line.match(/^[\s\t]*;/); const matchEmpty = line.match(/^[\s\t]*$/); if (matchComment || matchEmpty) return; const matchBeginning = line.match("^\\t{" + scope.currentIndent + "}(\\w+):(.*){", ""); const matchProperty = line.match("^\\t{" + scope.currentIndent + "}(\\w+):[\\s\\t\\r\\n](.*)"); const matchEnd = line.match("^\\t{" + (scope.currentIndent - 1) + "}}"); if (matchBeginning) { scope.parseNodeBegin(line, matchBeginning); } else if (matchProperty) { scope.parseNodeProperty(line, matchProperty, split[++i4]); } else if (matchEnd) { scope.popStack(); } else if (line.match(/^[^\s\t}]/)) { scope.parseNodePropertyContinued(line); } }); return this.allNodes; } parseNodeBegin(line, property) { const nodeName = property[1].trim().replace(/^"/, "").replace(/"$/, ""); const nodeAttrs = property[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 name = "", type = ""; if (attrs.length > 1) { name = attrs[1].replace(/^(\w+)::/, ""); type = attrs[2]; } return { id, name, type }; } parseNodeProperty(line, property, contentLine) { let propName = property[1].replace(/^"/, "").replace(/"$/, "").trim(); let propValue = property[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(line, 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(elem) { return elem.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(line) { const currentNode = this.getCurrentNode(); currentNode.a += line; if (line.slice(-1) !== ",") { currentNode.a = parseNumberArray(currentNode.a); } } // parse "Property70" parseNodeSpecialProperty(line, 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(buffer2) { const reader = new BinaryReader(buffer2); reader.skip(23); const version4 = reader.getUint32(); if (version4 < 6400) { throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: " + version4); } const allNodes = new FBXTree(); while (!this.endOfContent(reader)) { const node = this.parseNode(reader, version4); 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, version4) { const node = {}; const endOffset = version4 >= 7500 ? reader.getUint64() : reader.getUint32(); const numProperties = version4 >= 7500 ? reader.getUint64() : reader.getUint32(); version4 >= 7500 ? reader.getUint64() : reader.getUint32(); const nameLen = reader.getUint8(); const name = reader.getString(nameLen); if (endOffset === 0) return null; const propertyList = []; for (let i4 = 0; i4 < numProperties; i4++) { 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, version4); if (subNode !== null) this.parseSubNode(name, node, subNode); } node.propertyList = propertyList; if (typeof id === "number") node.id = id; if (attrName !== "") node.attrName = attrName; if (attrType !== "") node.attrType = attrType; if (name !== "") node.name = name; return node; } parseSubNode(name, node, subNode) { if (subNode.singleProperty === true) { const value = subNode.propertyList[0]; if (Array.isArray(value)) { node[subNode.name] = subNode; subNode.a = value; } else { node[subNode.name] = value; } } else if (name === "Connections" && subNode.name === "C") { const array = []; subNode.propertyList.forEach(function(property, i4) { if (i4 !== 0) array.push(property); }); if (node.connections === void 0) { node.connections = []; } node.connections.push(array); } else if (subNode.name === "Properties70") { const keys = Object.keys(subNode); keys.forEach(function(key) { node[key] = subNode[key]; }); } else if (name === "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 length3; 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": length3 = reader.getUint32(); return reader.getArrayBuffer(length3); case "S": length3 = reader.getUint32(); return reader.getString(length3); 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 data = unzlibSync(new Uint8Array(reader.getArrayBuffer(compressedLength))); const reader2 = new BinaryReader(data.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); } default: throw new Error("THREE.FBXLoader: Unknown property type " + type); } } }; var BinaryReader = class { constructor(buffer2, littleEndian) { this.dv = new DataView(buffer2); this.offset = 0; this.littleEndian = littleEndian !== void 0 ? littleEndian : true; } getOffset() { return this.offset; } size() { return this.dv.buffer.byteLength; } skip(length3) { this.offset += length3; } // 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 a6 = []; for (let i4 = 0; i4 < size2; i4++) { a6.push(this.getBoolean()); } return a6; } getUint8() { const value = this.dv.getUint8(this.offset); this.offset += 1; return value; } getInt16() { const value = this.dv.getInt16(this.offset, this.littleEndian); this.offset += 2; return value; } getInt32() { const value = this.dv.getInt32(this.offset, this.littleEndian); this.offset += 4; return value; } getInt32Array(size2) { const a6 = []; for (let i4 = 0; i4 < size2; i4++) { a6.push(this.getInt32()); } return a6; } getUint32() { const value = this.dv.getUint32(this.offset, this.littleEndian); this.offset += 4; return value; } // 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 a6 = []; for (let i4 = 0; i4 < size2; i4++) { a6.push(this.getInt64()); } return a6; } // 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 value = this.dv.getFloat32(this.offset, this.littleEndian); this.offset += 4; return value; } getFloat32Array(size2) { const a6 = []; for (let i4 = 0; i4 < size2; i4++) { a6.push(this.getFloat32()); } return a6; } getFloat64() { const value = this.dv.getFloat64(this.offset, this.littleEndian); this.offset += 8; return value; } getFloat64Array(size2) { const a6 = []; for (let i4 = 0; i4 < size2; i4++) { a6.push(this.getFloat64()); } return a6; } getArrayBuffer(size2) { const value = this.dv.buffer.slice(this.offset, this.offset + size2); this.offset += size2; return value; } getString(size2) { let a6 = []; for (let i4 = 0; i4 < size2; i4++) { a6[i4] = this.getUint8(); } const nullByte = a6.indexOf(0); if (nullByte >= 0) a6 = a6.slice(0, nullByte); return decodeText(new Uint8Array(a6)); } }; var FBXTree = class { add(key, val) { this[key] = val; } }; function isFbxFormatBinary(buffer2) { const CORRECT = "Kaydara FBX Binary \0"; return buffer2.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString(buffer2, 0, CORRECT.length); } function isFbxFormatASCII(text) { const CORRECT = [ "K", "a", "y", "d", "a", "r", "a", "\\", "F", "B", "X", "\\", "B", "i", "n", "a", "r", "y", "\\", "\\" ]; let cursor = 0; function read2(offset) { const result = text[offset - 1]; text = text.slice(cursor + offset); cursor++; return result; } for (let i4 = 0; i4 < CORRECT.length; ++i4) { const num = read2(1); if (num === CORRECT[i4]) { return false; } } return true; } function getFbxVersion(text) { const versionRegExp = /FBXVersion: (\d+)/; const match = text.match(versionRegExp); if (match) { const version4 = parseInt(match[1]); return version4; } throw new Error("THREE.FBXLoader: Cannot find the version number for the file given."); } function convertFBXTimeToSeconds(time) { return time / 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)); if (transformData.preRotation) { const array = transformData.preRotation.map(MathUtils.degToRad); array.push(transformData.eulerOrder); lPreRotationM.makeRotationFromEuler(tempEuler.fromArray(array)); } if (transformData.rotation) { const array = transformData.rotation.map(MathUtils.degToRad); array.push(transformData.eulerOrder); lRotationM.makeRotationFromEuler(tempEuler.fromArray(array)); } if (transformData.postRotation) { const array = transformData.postRotation.map(MathUtils.degToRad); array.push(transformData.eulerOrder); 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(value) { const array = value.split(",").map(function(val) { return parseFloat(val); }); return array; } function convertArrayBufferToString(buffer2, from, to) { if (from === void 0) from = 0; if (to === void 0) to = buffer2.byteLength; return decodeText(new Uint8Array(buffer2, from, to)); } function append(a6, b5) { for (let i4 = 0, j = a6.length, l2 = b5.length; i4 < l2; i4++, j++) { a6[j] = b5[i4]; } } function slice(a6, b5, from, to) { for (let i4 = from, j = 0; i4 < to; i4++, j++) { a6[j] = b5[i4]; } return a6; } function inject(a1, index2, a22) { return a1.slice(0, index2).concat(a22).concat(a1.slice(index2)); } // node_modules/three-stdlib/loaders/FontLoader.js var __defProp30 = Object.defineProperty; var __defNormalProp30 = (obj, key, value) => key in obj ? __defProp30(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField30 = (obj, key, value) => { __defNormalProp30(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var FontLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const loader2 = new FileLoader(this.manager); loader2.setPath(this.path); loader2.setRequestHeader(this.requestHeader); loader2.setWithCredentials(this.withCredentials); loader2.load( url, (response) => { if (typeof response !== "string") throw new Error("unsupported data type"); const json = JSON.parse(response); const font = this.parse(json); if (onLoad) onLoad(font); }, onProgress, onError ); } loadAsync(url, onProgress) { return super.loadAsync(url, onProgress); } parse(json) { return new Font(json); } }; var Font = class { constructor(data) { __publicField30(this, "data"); __publicField30(this, "isFont", true); __publicField30(this, "type", "Font"); this.data = data; } generateShapes(text, size2 = 100, _options) { const shapes = []; const options = { letterSpacing: 0, lineHeight: 1, ..._options }; const paths = createPaths(text, size2, this.data, options); for (let p2 = 0, pl = paths.length; p2 < pl; p2++) { Array.prototype.push.apply(shapes, paths[p2].toShapes(false)); } return shapes; } }; function createPaths(text, size2, data, options) { const chars = Array.from(text); const scale5 = size2 / data.resolution; const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale5; const paths = []; let offsetX = 0, offsetY = 0; for (let i4 = 0; i4 < chars.length; i4++) { const char = chars[i4]; if (char === "\n") { offsetX = 0; offsetY -= line_height * options.lineHeight; } else { const ret = createPath(char, scale5, offsetX, offsetY, data); if (ret) { offsetX += ret.offsetX + options.letterSpacing; paths.push(ret.path); } } } return paths; } function createPath(char, scale5, offsetX, offsetY, data) { const glyph = data.glyphs[char] || data.glyphs["?"]; if (!glyph) { console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + "."); return; } const path = new ShapePath(); let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; if (glyph.o) { const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(" ")); for (let i4 = 0, l2 = outline.length; i4 < l2; ) { const action = outline[i4++]; switch (action) { case "m": x = parseInt(outline[i4++]) * scale5 + offsetX; y = parseInt(outline[i4++]) * scale5 + offsetY; path.moveTo(x, y); break; case "l": x = parseInt(outline[i4++]) * scale5 + offsetX; y = parseInt(outline[i4++]) * scale5 + offsetY; path.lineTo(x, y); break; case "q": cpx = parseInt(outline[i4++]) * scale5 + offsetX; cpy = parseInt(outline[i4++]) * scale5 + offsetY; cpx1 = parseInt(outline[i4++]) * scale5 + offsetX; cpy1 = parseInt(outline[i4++]) * scale5 + offsetY; path.quadraticCurveTo(cpx1, cpy1, cpx, cpy); break; case "b": cpx = parseInt(outline[i4++]) * scale5 + offsetX; cpy = parseInt(outline[i4++]) * scale5 + offsetY; cpx1 = parseInt(outline[i4++]) * scale5 + offsetX; cpy1 = parseInt(outline[i4++]) * scale5 + offsetY; cpx2 = parseInt(outline[i4++]) * scale5 + offsetX; cpy2 = parseInt(outline[i4++]) * scale5 + offsetY; path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy); break; } } } return { offsetX: glyph.ha * scale5, path }; } // node_modules/three-stdlib/_polyfill/Data3DTexture.js var Data3DTexture = class extends Texture { constructor(data = null, width = 1, height = 1, depth = 1) { super(null); this.isData3DTexture = true; this.image = { data, width, height, depth }; this.magFilter = NearestFilter; this.minFilter = NearestFilter; this.wrapR = ClampToEdgeWrapping; this.generateMipmaps = false; this.flipY = false; this.unpackAlignment = 1; } }; // node_modules/three-stdlib/loaders/XLoader.js var XLoader = (function() { var classCallCheck = function(instance2, Constructor) { if (!(instance2 instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = /* @__PURE__ */ (function() { function defineProperties(target2, props) { for (let i22 = 0; i22 < props.length; i22++) { var descriptor = props[i22]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target2, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var XboneInf = function XboneInf2() { classCallCheck(this, XboneInf2); this.boneName = ""; this.BoneIndex = 0; this.Indeces = []; this.Weights = []; this.initMatrix = null; this.OffsetMatrix = null; }; var XAnimationInfo = function XAnimationInfo2() { classCallCheck(this, XAnimationInfo2); this.animeName = ""; this.boneName = ""; this.targetBone = null; this.keyType = 4; this.frameStartLv = 0; this.keyFrames = []; this.InverseMx = null; }; var XAnimationObj = (function() { function XAnimationObj2(_flags) { classCallCheck(this, XAnimationObj2); this.fps = 30; this.name = "xanimation"; this.length = 0; this.hierarchy = []; this.putFlags = _flags; if (this.putFlags.putPos === void 0) { this.putFlags.putPos = true; } if (this.putFlags.putRot === void 0) { this.putFlags.putRot = true; } if (this.putFlags.putScl === void 0) { this.putFlags.putScl = true; } } createClass(XAnimationObj2, [ { key: "make", value: function make(XAnimationInfoArray) { for (let i22 = 0; i22 < XAnimationInfoArray.length; i22++) { this.hierarchy.push(this.makeBonekeys(XAnimationInfoArray[i22])); } this.length = this.hierarchy[0].keys[this.hierarchy[0].keys.length - 1].time; } }, { key: "clone", value: function clone2() { return Object.assign({}, this); } }, { key: "makeBonekeys", value: function makeBonekeys(XAnimationInfo2) { var refObj = {}; refObj.name = XAnimationInfo2.boneName; refObj.parent = ""; refObj.keys = this.keyFrameRefactor(XAnimationInfo2); refObj.copy = function() { return Object.assign({}, this); }; return refObj; } }, { key: "keyFrameRefactor", value: function keyFrameRefactor(XAnimationInfo2) { var keys = []; for (let i22 = 0; i22 < XAnimationInfo2.keyFrames.length; i22++) { var keyframe = {}; keyframe.time = XAnimationInfo2.keyFrames[i22].time * this.fps; if (XAnimationInfo2.keyFrames[i22].pos && this.putFlags.putPos) { keyframe.pos = XAnimationInfo2.keyFrames[i22].pos; } if (XAnimationInfo2.keyFrames[i22].rot && this.putFlags.putRot) { keyframe.rot = XAnimationInfo2.keyFrames[i22].rot; } if (XAnimationInfo2.keyFrames[i22].scl && this.putFlags.putScl) { keyframe.scl = XAnimationInfo2.keyFrames[i22].scl; } if (XAnimationInfo2.keyFrames[i22].matrix) { keyframe.matrix = XAnimationInfo2.keyFrames[i22].matrix; if (this.putFlags.putPos) { keyframe.pos = new Vector3().setFromMatrixPosition(keyframe.matrix); } if (this.putFlags.putRot) { keyframe.rot = new Quaternion().setFromRotationMatrix(keyframe.matrix); } if (this.putFlags.putScl) { keyframe.scl = new Vector3().setFromMatrixScale(keyframe.matrix); } } keys.push(keyframe); } return keys; } } ]); return XAnimationObj2; })(); var XKeyFrameInfo = function XKeyFrameInfo2() { classCallCheck(this, XKeyFrameInfo2); this.index = 0; this.Frame = 0; this.time = 0; this.matrix = null; }; var XLoader2 = (function() { function XLoader3(manager) { Loader.call(this, manager); classCallCheck(this, XLoader3); this.debug = false; this.texloader = new TextureLoader(this.manager); this.url = ""; this._putMatLength = 0; this._nowMat = null; this._nowFrameName = ""; this.frameHierarchie = []; this.Hierarchies = {}; this.HieStack = []; this._currentObject = {}; this._currentFrame = {}; this._data = null; this.onLoad = null; this.IsUvYReverse = true; this.Meshes = []; this.animations = []; this.animTicksPerSecond = 30; this._currentGeo = null; this._currentAnime = null; this._currentAnimeFrames = null; } createClass(XLoader3, [ { key: "_setArgOption", value: function _setArgOption(_arg) { var _start3 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; if (!_arg) { return; } for (let i22 = _start3; i22 < _arg.length; i22++) { switch (i22) { case 0: this.url = _arg[i22]; break; case 1: this.options = _arg[i22]; break; } } if (this.options === void 0) { this.options = {}; } } }, { key: "load", value: function load2(_arg, onLoad, onProgress, onError) { var _this = this; this._setArgOption(_arg); var loader2 = new FileLoader(this.manager); loader2.setPath(this.path); loader2.setResponseType("arraybuffer"); loader2.setRequestHeader(this.requestHeader); loader2.setWithCredentials(this.withCredentials); loader2.load( this.url, function(response) { try { _this.parse(response, onLoad); } catch (e2) { if (onError) { onError(e2); } else { console.error(e2); } _this.manager.itemError(_this.url); } }, onProgress, onError ); } }, { key: "_readLine", value: function _readLine(line) { var readed = 0; while (true) { var find = -1; find = line.indexOf("//", readed); if (find === -1) { find = line.indexOf("#", readed); } if (find > -1 && find < 2) { var foundNewLine = -1; foundNewLine = line.indexOf("\r\n", readed); if (foundNewLine > 0) { readed = foundNewLine + 2; } else { foundNewLine = line.indexOf("\r", readed); if (foundNewLine > 0) { readed = foundNewLine + 1; } else { readed = line.indexOf("\n", readed) + 1; } } } else { break; } } return line.substr(readed); } }, { key: "_readLine", value: function _readLine(line) { var readed = 0; while (true) { var find = -1; find = line.indexOf("//", readed); if (find === -1) { find = line.indexOf("#", readed); } if (find > -1 && find < 2) { var foundNewLine = -1; foundNewLine = line.indexOf("\r\n", readed); if (foundNewLine > 0) { readed = foundNewLine + 2; } else { foundNewLine = line.indexOf("\r", readed); if (foundNewLine > 0) { readed = foundNewLine + 1; } else { readed = line.indexOf("\n", readed) + 1; } } } else { break; } } return line.substr(readed); } }, { key: "_isBinary", value: function _isBinary(binData) { var reader = new DataView(binData); var face_size = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8; var n_faces = reader.getUint32(80, true); var expect = 80 + 32 / 8 + n_faces * face_size; if (expect === reader.byteLength) { return true; } var fileLength = reader.byteLength; for (let index2 = 0; index2 < fileLength; index2++) { if (reader.getUint8(index2, false) > 127) { return true; } } return false; } }, { key: "_ensureBinary", value: function _ensureBinary(buf) { if (typeof buf === "string") { var array_buffer = new Uint8Array(buf.length); for (let i22 = 0; i22 < buf.length; i22++) { array_buffer[i22] = buf.charCodeAt(i22) & 255; } return array_buffer.buffer || array_buffer; } else { return buf; } } }, { key: "_ensureString", value: function _ensureString(buf) { if (typeof buf !== "string") { return decodeText(new Uint8Array(buf)); } else { return buf; } } }, { key: "parse", value: function _parse(data, onLoad) { var binData = this._ensureBinary(data); this._data = this._ensureString(data); this.onLoad = onLoad; return this._isBinary(binData) ? this._parseBinary(binData) : this._parseASCII(); } }, { key: "_parseBinary", value: function _parseBinary(data) { return this._parseASCII(decodeText(new Uint8Array(data))); } }, { key: "_parseASCII", value: function _parseASCII() { var path; if (this.resourcePath !== "") { path = this.resourcePath; } else if (this.path !== "") { path = this.path; } else { path = LoaderUtils.extractUrlBase(this.url); } this.texloader.setPath(path).setCrossOrigin(this.crossOrigin); var endRead = 16; this.Hierarchies.children = []; this._hierarchieParse(this.Hierarchies, endRead); this._changeRoot(); this._currentObject = this.Hierarchies.children.shift(); this._mainloop(); } }, { key: "_hierarchieParse", value: function _hierarchieParse(_parent, _end3) { var endRead = _end3; while (true) { var find1 = this._data.indexOf("{", endRead) + 1; var findEnd = this._data.indexOf("}", endRead); var findNext = this._data.indexOf("{", find1) + 1; if (find1 > 0 && findEnd > find1) { var _currentObject = {}; _currentObject.children = []; var nameData = this._readLine(this._data.substr(endRead, find1 - endRead - 1)).trim(); var word = nameData.split(/ /g); if (word.length > 0) { _currentObject.type = word[0]; if (word.length >= 2) { _currentObject.name = word[1]; } else { _currentObject.name = word[0] + this.Hierarchies.children.length; } } else { _currentObject.name = nameData; _currentObject.type = ""; } if (_currentObject.type === "Animation") { _currentObject.data = this._data.substr(findNext, findEnd - findNext).trim(); var refs = this._hierarchieParse(_currentObject, findEnd + 1); endRead = refs.end; _currentObject.children = refs.parent.children; } else { var DataEnder = this._data.lastIndexOf(";", findNext > 0 ? Math.min(findNext, findEnd) : findEnd); _currentObject.data = this._data.substr(find1, DataEnder - find1).trim(); if (findNext <= 0 || findEnd < findNext) { endRead = findEnd + 1; } else { var nextStart = Math.max(DataEnder + 1, find1); var _refs = this._hierarchieParse(_currentObject, nextStart); endRead = _refs.end; _currentObject.children = _refs.parent.children; } } _currentObject.parent = _parent; if (_currentObject.type != "template") { _parent.children.push(_currentObject); } } else { endRead = find1 === -1 ? this._data.length : findEnd + 1; break; } } return { parent: _parent, end: endRead }; } }, { key: "_mainloop", value: function _mainloop() { var _this2 = this; this._mainProc(); if (this._currentObject.parent || this._currentObject.children.length > 0 || !this._currentObject.worked) { setTimeout(function() { _this2._mainloop(); }, 1); } else { setTimeout(function() { _this2.onLoad({ models: _this2.Meshes, animations: _this2.animations }); }, 1); } } }, { key: "_mainProc", value: function _mainProc() { var breakFlag = false; while (true) { if (!this._currentObject.worked) { switch (this._currentObject.type) { case "template": break; case "AnimTicksPerSecond": this.animTicksPerSecond = parseInt(this._currentObject.data); break; case "Frame": this._setFrame(); break; case "FrameTransformMatrix": this._setFrameTransformMatrix(); break; case "Mesh": this._changeRoot(); this._currentGeo = {}; this._currentGeo.name = this._currentObject.name.trim(); this._currentGeo.parentName = this._getParentName(this._currentObject).trim(); this._currentGeo.VertexSetedBoneCount = []; this._currentGeo.GeometryData = { vertices: [], normals: [], uvs: [], skinIndices: [], skinWeights: [], indices: [], materialIndices: [] }; this._currentGeo.Materials = []; this._currentGeo.normalVectors = []; this._currentGeo.BoneInfs = []; this._currentGeo.baseFrame = this._currentFrame; this._makeBoneFrom_CurrentFrame(); this._readVertexDatas(); breakFlag = true; break; case "MeshNormals": this._readVertexDatas(); break; case "MeshTextureCoords": this._setMeshTextureCoords(); break; case "VertexDuplicationIndices": break; case "MeshMaterialList": this._setMeshMaterialList(); break; case "Material": this._setMaterial(); break; case "SkinWeights": this._setSkinWeights(); break; case "AnimationSet": this._changeRoot(); this._currentAnime = {}; this._currentAnime.name = this._currentObject.name.trim(); this._currentAnime.AnimeFrames = []; break; case "Animation": if (this._currentAnimeFrames) { this._currentAnime.AnimeFrames.push(this._currentAnimeFrames); } this._currentAnimeFrames = new XAnimationInfo(); this._currentAnimeFrames.boneName = this._currentObject.data.trim(); break; case "AnimationKey": this._readAnimationKey(); breakFlag = true; break; } this._currentObject.worked = true; } if (this._currentObject.children.length > 0) { this._currentObject = this._currentObject.children.shift(); if (this.debug) { console.log("processing " + this._currentObject.name); } if (breakFlag) break; } else { if (this._currentObject.worked) { if (this._currentObject.parent && !this._currentObject.parent.parent) { this._changeRoot(); } } if (this._currentObject.parent) { this._currentObject = this._currentObject.parent; } else { breakFlag = true; } if (breakFlag) break; } } return; } }, { key: "_changeRoot", value: function _changeRoot() { if (this._currentGeo != null && this._currentGeo.name) { this._makeOutputGeometry(); } this._currentGeo = {}; if (this._currentAnime != null && this._currentAnime.name) { if (this._currentAnimeFrames) { this._currentAnime.AnimeFrames.push(this._currentAnimeFrames); this._currentAnimeFrames = null; } this._makeOutputAnimation(); } this._currentAnime = {}; } }, { key: "_getParentName", value: function _getParentName(_obj2) { if (_obj2.parent) { if (_obj2.parent.name) { return _obj2.parent.name; } else { return this._getParentName(_obj2.parent); } } else { return ""; } } }, { key: "_setFrame", value: function _setFrame() { this._nowFrameName = this._currentObject.name.trim(); this._currentFrame = {}; this._currentFrame.name = this._nowFrameName; this._currentFrame.children = []; if (this._currentObject.parent && this._currentObject.parent.name) { this._currentFrame.parentName = this._currentObject.parent.name; } this.frameHierarchie.push(this._nowFrameName); this.HieStack[this._nowFrameName] = this._currentFrame; } }, { key: "_setFrameTransformMatrix", value: function _setFrameTransformMatrix() { this._currentFrame.FrameTransformMatrix = new Matrix4(); var data = this._currentObject.data.split(","); this._ParseMatrixData(this._currentFrame.FrameTransformMatrix, data); this._makeBoneFrom_CurrentFrame(); } }, { key: "_makeBoneFrom_CurrentFrame", value: function _makeBoneFrom_CurrentFrame() { if (!this._currentFrame.FrameTransformMatrix) { return; } var b5 = new Bone(); b5.name = this._currentFrame.name; b5.applyMatrix4(this._currentFrame.FrameTransformMatrix); b5.matrixWorld = b5.matrix; b5.FrameTransformMatrix = this._currentFrame.FrameTransformMatrix; this._currentFrame.putBone = b5; if (this._currentFrame.parentName) { for (let frame in this.HieStack) { if (this.HieStack[frame].name === this._currentFrame.parentName) { this.HieStack[frame].putBone.add(this._currentFrame.putBone); } } } } }, { key: "_readVertexDatas", value: function _readVertexDatas() { var endRead = 0; var mode = 0; var mode_local = 0; var maxLength = 0; while (true) { var changeMode = false; if (mode_local === 0) { var refO = this._readInt1(endRead); endRead = refO.endRead; mode_local = 1; maxLength = this._currentObject.data.indexOf(";;", endRead) + 1; if (maxLength <= 0) { maxLength = this._currentObject.data.length; } } else { var find = 0; switch (mode) { case 0: find = this._currentObject.data.indexOf(",", endRead) + 1; break; case 1: find = this._currentObject.data.indexOf(";,", endRead) + 1; break; } if (find === 0 || find > maxLength) { find = maxLength; mode_local = 0; changeMode = true; } switch (this._currentObject.type) { case "Mesh": switch (mode) { case 0: this._readVertex1(this._currentObject.data.substr(endRead, find - endRead)); break; case 1: this._readFace1(this._currentObject.data.substr(endRead, find - endRead)); break; } break; case "MeshNormals": switch (mode) { case 0: this._readNormalVector1(this._currentObject.data.substr(endRead, find - endRead)); break; } break; } endRead = find + 1; if (changeMode) { mode++; } } if (endRead >= this._currentObject.data.length) { break; } } } }, { key: "_readInt1", value: function _readInt1(start) { var find = this._currentObject.data.indexOf(";", start); return { refI: parseInt(this._currentObject.data.substr(start, find - start)), endRead: find + 1 }; } }, { key: "_readVertex1", value: function _readVertex1(line) { var data = this._readLine(line.trim()).substr(0, line.length - 2).split(";"); this._currentGeo.GeometryData.vertices.push(parseFloat(data[0]), parseFloat(data[1]), parseFloat(data[2])); this._currentGeo.GeometryData.skinIndices.push(0, 0, 0, 0); this._currentGeo.GeometryData.skinWeights.push(1, 0, 0, 0); this._currentGeo.VertexSetedBoneCount.push(0); } }, { key: "_readFace1", value: function _readFace1(line) { var data = this._readLine(line.trim()).substr(2, line.length - 4).split(","); this._currentGeo.GeometryData.indices.push( parseInt(data[0], 10), parseInt(data[1], 10), parseInt(data[2], 10) ); } }, { key: "_readNormalVector1", value: function _readNormalVector1(line) { var data = this._readLine(line.trim()).substr(0, line.length - 2).split(";"); this._currentGeo.GeometryData.normals.push(parseFloat(data[0]), parseFloat(data[1]), parseFloat(data[2])); } }, { key: "_buildGeometry", value: function _buildGeometry() { var bufferGeometry = new BufferGeometry(); var position2 = []; var normals = []; var uvs = []; var skinIndices = []; var skinWeights = []; var data = this._currentGeo.GeometryData; for (let i22 = 0, l2 = data.indices.length; i22 < l2; i22++) { var stride2 = data.indices[i22] * 2; var stride3 = data.indices[i22] * 3; var stride4 = data.indices[i22] * 4; position2.push(data.vertices[stride3], data.vertices[stride3 + 1], data.vertices[stride3 + 2]); normals.push(data.normals[stride3], data.normals[stride3 + 1], data.normals[stride3 + 2]); skinIndices.push( data.skinIndices[stride4], data.skinIndices[stride4 + 1], data.skinIndices[stride4 + 2], data.skinIndices[stride4 + 3] ); skinWeights.push( data.skinWeights[stride4], data.skinWeights[stride4 + 1], data.skinWeights[stride4 + 2], data.skinWeights[stride4 + 3] ); uvs.push(data.uvs[stride2], data.uvs[stride2 + 1]); } bufferGeometry.setAttribute("position", new Float32BufferAttribute(position2, 3)); bufferGeometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); bufferGeometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); bufferGeometry.setAttribute("skinIndex", new Uint16BufferAttribute(skinIndices, 4)); bufferGeometry.setAttribute("skinWeight", new Float32BufferAttribute(skinWeights, 4)); this._computeGroups(bufferGeometry, data.materialIndices); return bufferGeometry; } }, { key: "_computeGroups", value: function _computeGroups(bufferGeometry, materialIndices) { var group; var groups = []; var materialIndex = void 0; for (let i22 = 0; i22 < materialIndices.length; i22++) { var currentMaterialIndex = materialIndices[i22]; if (currentMaterialIndex !== materialIndex) { materialIndex = currentMaterialIndex; if (group !== void 0) { group.count = i22 * 3 - group.start; groups.push(group); } group = { start: i22 * 3, materialIndex }; } } if (group !== void 0) { group.count = i * 3 - group.start; groups.push(group); } bufferGeometry.groups = groups; } }, { key: "_setMeshTextureCoords", value: function _setMeshTextureCoords() { var endRead = 0; var mode = 0; var mode_local = 0; while (true) { switch (mode) { case 0: if (mode_local === 0) { var refO = this._readInt1(0); endRead = refO.endRead; mode_local = 1; } else { var find = this._currentObject.data.indexOf(",", endRead) + 1; if (find === 0) { find = this._currentObject.data.length; mode = 2; mode_local = 0; } var line = this._currentObject.data.substr(endRead, find - endRead); var data = this._readLine(line.trim()).split(";"); if (this.IsUvYReverse) { this._currentGeo.GeometryData.uvs.push(parseFloat(data[0]), 1 - parseFloat(data[1])); } else { this._currentGeo.GeometryData.uvs.push(parseFloat(data[0]), parseFloat(data[1])); } endRead = find + 1; } break; } if (endRead >= this._currentObject.data.length) { break; } } } }, { key: "_setMeshMaterialList", value: function _setMeshMaterialList() { var endRead = 0; var mode = 0; var mode_local = 0; while (true) { if (mode_local < 2) { var refO = this._readInt1(endRead); endRead = refO.endRead; mode_local++; } else { var find = this._currentObject.data.indexOf(";", endRead); if (find === -1) { find = this._currentObject.data.length; mode = 3; mode_local = 0; } var line = this._currentObject.data.substr(endRead, find - endRead); var data = this._readLine(line.trim()).split(","); for (let i22 = 0; i22 < data.length; i22++) { this._currentGeo.GeometryData.materialIndices[i22] = parseInt(data[i22]); } endRead = this._currentObject.data.length; } if (endRead >= this._currentObject.data.length || mode >= 3) { break; } } } }, { key: "_setMaterial", value: function _setMaterial() { var _nowMat = new MeshPhongMaterial({ color: Math.random() * 16777215 }); _nowMat.side = FrontSide; _nowMat.name = this._currentObject.name; var endRead = 0; var find = this._currentObject.data.indexOf(";;", endRead); var line = this._currentObject.data.substr(endRead, find - endRead); var data = this._readLine(line.trim()).split(";"); _nowMat.color.r = parseFloat(data[0]); _nowMat.color.g = parseFloat(data[1]); _nowMat.color.b = parseFloat(data[2]); endRead = find + 2; find = this._currentObject.data.indexOf(";", endRead); line = this._currentObject.data.substr(endRead, find - endRead); _nowMat.shininess = parseFloat(this._readLine(line)); endRead = find + 1; find = this._currentObject.data.indexOf(";;", endRead); line = this._currentObject.data.substr(endRead, find - endRead); var data2 = this._readLine(line.trim()).split(";"); _nowMat.specular.r = parseFloat(data2[0]); _nowMat.specular.g = parseFloat(data2[1]); _nowMat.specular.b = parseFloat(data2[2]); endRead = find + 2; find = this._currentObject.data.indexOf(";;", endRead); if (find === -1) { find = this._currentObject.data.length; } line = this._currentObject.data.substr(endRead, find - endRead); var data3 = this._readLine(line.trim()).split(";"); _nowMat.emissive.r = parseFloat(data3[0]); _nowMat.emissive.g = parseFloat(data3[1]); _nowMat.emissive.b = parseFloat(data3[2]); var localObject = null; while (true) { if (this._currentObject.children.length > 0) { localObject = this._currentObject.children.shift(); if (this.debug) { console.log("processing " + localObject.name); } var fileName = localObject.data.substr(1, localObject.data.length - 2); switch (localObject.type) { case "TextureFilename": _nowMat.map = this.texloader.load(fileName); break; case "BumpMapFilename": _nowMat.bumpMap = this.texloader.load(fileName); _nowMat.bumpScale = 0.05; break; case "NormalMapFilename": _nowMat.normalMap = this.texloader.load(fileName); _nowMat.normalScale = new Vector2(2, 2); break; case "EmissiveMapFilename": _nowMat.emissiveMap = this.texloader.load(fileName); break; case "LightMapFilename": _nowMat.lightMap = this.texloader.load(fileName); break; } } else { break; } } this._currentGeo.Materials.push(_nowMat); } }, { key: "_setSkinWeights", value: function _setSkinWeights() { var boneInf = new XboneInf(); var endRead = 0; var find = this._currentObject.data.indexOf(";", endRead); var line = this._currentObject.data.substr(endRead, find - endRead); endRead = find + 1; boneInf.boneName = line.substr(1, line.length - 2); boneInf.BoneIndex = this._currentGeo.BoneInfs.length; find = this._currentObject.data.indexOf(";", endRead); endRead = find + 1; find = this._currentObject.data.indexOf(";", endRead); line = this._currentObject.data.substr(endRead, find - endRead); var data = this._readLine(line.trim()).split(","); for (let i22 = 0; i22 < data.length; i22++) { boneInf.Indeces.push(parseInt(data[i22])); } endRead = find + 1; find = this._currentObject.data.indexOf(";", endRead); line = this._currentObject.data.substr(endRead, find - endRead); var data2 = this._readLine(line.trim()).split(","); for (let _i = 0; _i < data2.length; _i++) { boneInf.Weights.push(parseFloat(data2[_i])); } endRead = find + 1; find = this._currentObject.data.indexOf(";", endRead); if (find <= 0) { find = this._currentObject.data.length; } line = this._currentObject.data.substr(endRead, find - endRead); var data3 = this._readLine(line.trim()).split(","); boneInf.OffsetMatrix = new Matrix4(); this._ParseMatrixData(boneInf.OffsetMatrix, data3); this._currentGeo.BoneInfs.push(boneInf); } }, { key: "_makePutBoneList", value: function _makePutBoneList(_RootName, _bones) { var putting = false; for (let frame in this.HieStack) { if (this.HieStack[frame].name === _RootName || putting) { putting = true; var b5 = new Bone(); b5.name = this.HieStack[frame].name; b5.applyMatrix4(this.HieStack[frame].FrameTransformMatrix); b5.matrixWorld = b5.matrix; b5.FrameTransformMatrix = this.HieStack[frame].FrameTransformMatrix; b5.pos = new Vector3().setFromMatrixPosition(b5.FrameTransformMatrix).toArray(); b5.rotq = new Quaternion().setFromRotationMatrix(b5.FrameTransformMatrix).toArray(); b5.scl = new Vector3().setFromMatrixScale(b5.FrameTransformMatrix).toArray(); if (this.HieStack[frame].parentName && this.HieStack[frame].parentName.length > 0) { for (let i22 = 0; i22 < _bones.length; i22++) { if (this.HieStack[frame].parentName === _bones[i22].name) { _bones[i22].add(b5); b5.parent = i22; break; } } } _bones.push(b5); } } } }, { key: "_makeOutputGeometry", value: function _makeOutputGeometry() { var mesh = null; if (this._currentGeo.BoneInfs.length > 0) { var putBones = []; this._makePutBoneList(this._currentGeo.baseFrame.parentName, putBones); for (let bi = 0; bi < this._currentGeo.BoneInfs.length; bi++) { var boneIndex = 0; for (let bb2 = 0; bb2 < putBones.length; bb2++) { if (putBones[bb2].name === this._currentGeo.BoneInfs[bi].boneName) { boneIndex = bb2; putBones[bb2].OffsetMatrix = new Matrix4(); putBones[bb2].OffsetMatrix.copy(this._currentGeo.BoneInfs[bi].OffsetMatrix); break; } } for (let vi = 0; vi < this._currentGeo.BoneInfs[bi].Indeces.length; vi++) { var nowVertexID = this._currentGeo.BoneInfs[bi].Indeces[vi]; var nowVal = this._currentGeo.BoneInfs[bi].Weights[vi]; var stride = nowVertexID * 4; switch (this._currentGeo.VertexSetedBoneCount[nowVertexID]) { case 0: this._currentGeo.GeometryData.skinIndices[stride] = boneIndex; this._currentGeo.GeometryData.skinWeights[stride] = nowVal; break; case 1: this._currentGeo.GeometryData.skinIndices[stride + 1] = boneIndex; this._currentGeo.GeometryData.skinWeights[stride + 1] = nowVal; break; case 2: this._currentGeo.GeometryData.skinIndices[stride + 2] = boneIndex; this._currentGeo.GeometryData.skinWeights[stride + 2] = nowVal; break; case 3: this._currentGeo.GeometryData.skinIndices[stride + 3] = boneIndex; this._currentGeo.GeometryData.skinWeights[stride + 3] = nowVal; break; } this._currentGeo.VertexSetedBoneCount[nowVertexID]++; if (this._currentGeo.VertexSetedBoneCount[nowVertexID] > 4) { console.log("warn! over 4 bone weight! :" + nowVertexID); } } } for (let sk = 0; sk < this._currentGeo.Materials.length; sk++) { this._currentGeo.Materials[sk].skinning = true; } var offsetList = []; for (let _bi = 0; _bi < putBones.length; _bi++) { if (putBones[_bi].OffsetMatrix) { offsetList.push(putBones[_bi].OffsetMatrix); } else { offsetList.push(new Matrix4()); } } var bufferGeometry = this._buildGeometry(); mesh = new SkinnedMesh( bufferGeometry, this._currentGeo.Materials.length === 1 ? this._currentGeo.Materials[0] : this._currentGeo.Materials ); this._initSkeleton(mesh, putBones, offsetList); } else { var _bufferGeometry = this._buildGeometry(); mesh = new Mesh( _bufferGeometry, this._currentGeo.Materials.length === 1 ? this._currentGeo.Materials[0] : this._currentGeo.Materials ); } mesh.name = this._currentGeo.name; var worldBaseMx = new Matrix4(); var currentMxFrame = this._currentGeo.baseFrame.putBone; if (currentMxFrame && currentMxFrame.parent) { while (true) { currentMxFrame = currentMxFrame.parent; if (currentMxFrame) { worldBaseMx.multiply(currentMxFrame.FrameTransformMatrix); } else { break; } } mesh.applyMatrix4(worldBaseMx); } this.Meshes.push(mesh); } }, { key: "_initSkeleton", value: function _initSkeleton(mesh, boneList, boneInverses) { var bones = [], bone, gbone; var i22, il; for (i22 = 0, il = boneList.length; i22 < il; i22++) { gbone = boneList[i22]; bone = new Bone(); bones.push(bone); bone.name = gbone.name; bone.position.fromArray(gbone.pos); bone.quaternion.fromArray(gbone.rotq); if (gbone.scl !== void 0) bone.scale.fromArray(gbone.scl); } for (i22 = 0, il = boneList.length; i22 < il; i22++) { gbone = boneList[i22]; if (gbone.parent !== -1 && gbone.parent !== null && bones[gbone.parent] !== void 0) { bones[gbone.parent].add(bones[i22]); } else { mesh.add(bones[i22]); } } mesh.updateMatrixWorld(true); var skeleton = new Skeleton(bones, boneInverses); mesh.bind(skeleton, mesh.matrixWorld); } }, { key: "_readAnimationKey", value: function _readAnimationKey() { var endRead = 0; var find = this._currentObject.data.indexOf(";", endRead); var line = this._currentObject.data.substr(endRead, find - endRead); endRead = find + 1; var nowKeyType = parseInt(this._readLine(line)); find = this._currentObject.data.indexOf(";", endRead); endRead = find + 1; line = this._currentObject.data.substr(endRead); var data = this._readLine(line.trim()).split(";;,"); for (let i22 = 0; i22 < data.length; i22++) { var data2 = data[i22].split(";"); var keyInfo = new XKeyFrameInfo(); keyInfo.type = nowKeyType; keyInfo.Frame = parseInt(data2[0]); keyInfo.index = this._currentAnimeFrames.keyFrames.length; keyInfo.time = keyInfo.Frame; if (nowKeyType != 4) { var frameFound = false; for (let mm = 0; mm < this._currentAnimeFrames.keyFrames.length; mm++) { if (this._currentAnimeFrames.keyFrames[mm].Frame === keyInfo.Frame) { keyInfo = this._currentAnimeFrames.keyFrames[mm]; frameFound = true; break; } } var frameValue = data2[2].split(","); switch (nowKeyType) { case 0: keyInfo.rot = new Quaternion( parseFloat(frameValue[1]), parseFloat(frameValue[2]), parseFloat(frameValue[3]), parseFloat(frameValue[0]) * -1 ); break; case 1: keyInfo.scl = new Vector3( parseFloat(frameValue[0]), parseFloat(frameValue[1]), parseFloat(frameValue[2]) ); break; case 2: keyInfo.pos = new Vector3( parseFloat(frameValue[0]), parseFloat(frameValue[1]), parseFloat(frameValue[2]) ); break; } if (!frameFound) { this._currentAnimeFrames.keyFrames.push(keyInfo); } } else { keyInfo.matrix = new Matrix4(); this._ParseMatrixData(keyInfo.matrix, data2[2].split(",")); this._currentAnimeFrames.keyFrames.push(keyInfo); } } } }, { key: "_makeOutputAnimation", value: function _makeOutputAnimation() { var animationObj = new XAnimationObj(this.options); animationObj.fps = this.animTicksPerSecond; animationObj.name = this._currentAnime.name; animationObj.make(this._currentAnime.AnimeFrames); this.animations.push(animationObj); } }, { key: "assignAnimation", value: function assignAnimation(_model, _animation) { var model = _model; var animation = _animation; if (!model) { model = this.Meshes[0]; } if (!animation) { animation = this.animations[0]; } if (!model || !animation) { return null; } var put = {}; put.fps = animation.fps; put.name = animation.name; put.length = animation.length; put.hierarchy = []; for (let b5 = 0; b5 < model.skeleton.bones.length; b5++) { var findAnimation = false; for (let i22 = 0; i22 < animation.hierarchy.length; i22++) { if (model.skeleton.bones[b5].name === animation.hierarchy[i22].name) { findAnimation = true; var c_key = animation.hierarchy[i22].copy(); c_key.parent = -1; if (model.skeleton.bones[b5].parent && model.skeleton.bones[b5].parent.type === "Bone") { for (let bb2 = 0; bb2 < put.hierarchy.length; bb2++) { if (put.hierarchy[bb2].name === model.skeleton.bones[b5].parent.name) { c_key.parent = bb2; c_key.parentName = model.skeleton.bones[b5].parent.name; } } } put.hierarchy.push(c_key); break; } } if (!findAnimation) { var _c_key = animation.hierarchy[0].copy(); _c_key.name = model.skeleton.bones[b5].name; _c_key.parent = -1; for (let k = 0; k < _c_key.keys.length; k++) { if (_c_key.keys[k].pos) { _c_key.keys[k].pos.set(0, 0, 0); } if (_c_key.keys[k].scl) { _c_key.keys[k].scl.set(1, 1, 1); } if (_c_key.keys[k].rot) { _c_key.keys[k].rot.set(0, 0, 0, 1); } } put.hierarchy.push(_c_key); } } if (!model.geometry.animations) { model.geometry.animations = []; } model.geometry.animations.push(AnimationClip.parseAnimation(put, model.skeleton.bones)); if (!model.animationMixer) { model.animationMixer = new AnimationMixer(model); } return put; } }, { key: "_ParseMatrixData", value: function _ParseMatrixData(targetMatrix, data) { targetMatrix.set( parseFloat(data[0]), parseFloat(data[4]), parseFloat(data[8]), parseFloat(data[12]), parseFloat(data[1]), parseFloat(data[5]), parseFloat(data[9]), parseFloat(data[13]), parseFloat(data[2]), parseFloat(data[6]), parseFloat(data[10]), parseFloat(data[14]), parseFloat(data[3]), parseFloat(data[7]), parseFloat(data[11]), parseFloat(data[15]) ); } } ]); return XLoader3; })(); return XLoader2; })(); // node_modules/three-stdlib/libs/chevrotain.js var { CstParser, Lexer, createToken } = (() => { var freeGlobal = typeof global == "object" && global && global.Object === Object && global; const freeGlobal$1 = freeGlobal; var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root = freeGlobal$1 || freeSelf || Function("return this")(); const root$1 = root; var Symbol$1 = root$1.Symbol; const Symbol$2 = Symbol$1; var objectProto$j = Object.prototype; var hasOwnProperty$g = objectProto$j.hasOwnProperty; var nativeObjectToString$1 = objectProto$j.toString; var symToStringTag$1 = Symbol$2 ? Symbol$2.toStringTag : void 0; function getRawTag(value) { var isOwn = hasOwnProperty$g.call(value, symToStringTag$1), tag = value[symToStringTag$1]; try { value[symToStringTag$1] = void 0; var unmasked = true; } catch (e2) { } var result = nativeObjectToString$1.call(value); if (unmasked) { if (isOwn) { value[symToStringTag$1] = tag; } else { delete value[symToStringTag$1]; } } return result; } var objectProto$i = Object.prototype; var nativeObjectToString = objectProto$i.toString; function objectToString(value) { return nativeObjectToString.call(value); } var nullTag = "[object Null]", undefinedTag = "[object Undefined]"; var symToStringTag = Symbol$2 ? Symbol$2.toStringTag : void 0; function baseGetTag(value) { if (value == null) { return value === void 0 ? undefinedTag : nullTag; } return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); } function isObjectLike(value) { return value != null && typeof value == "object"; } var symbolTag$3 = "[object Symbol]"; function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag$3; } function arrayMap(array, iteratee) { var index2 = -1, length3 = array == null ? 0 : array.length, result = Array(length3); while (++index2 < length3) { result[index2] = iteratee(array[index2], index2, array); } return result; } var isArray3 = Array.isArray; const isArray$1 = isArray3; var INFINITY$3 = 1 / 0; var symbolProto$2 = Symbol$2 ? Symbol$2.prototype : void 0, symbolToString = symbolProto$2 ? symbolProto$2.toString : void 0; function baseToString(value) { if (typeof value == "string") { return value; } if (isArray$1(value)) { return arrayMap(value, baseToString) + ""; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ""; } var result = value + ""; return result == "0" && 1 / value == -INFINITY$3 ? "-0" : result; } var reWhitespace = /\s/; function trimmedEndIndex(string) { var index2 = string.length; while (index2-- && reWhitespace.test(string.charAt(index2))) { } return index2; } var reTrimStart = /^\s+/; function baseTrim(string) { return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string; } function isObject(value) { var type = typeof value; return value != null && (type == "object" || type == "function"); } var NAN = 0 / 0; var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; var reIsBinary = /^0b[01]+$/i; var reIsOctal = /^0o[0-7]+$/i; var freeParseInt = parseInt; function toNumber(value) { if (typeof value == "number") { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == "function" ? value.valueOf() : value; value = isObject(other) ? other + "" : other; } if (typeof value != "string") { return value === 0 ? value : +value; } value = baseTrim(value); var isBinary = reIsBinary.test(value); return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; } var INFINITY$2 = 1 / 0, MAX_INTEGER = 17976931348623157e292; function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY$2 || value === -INFINITY$2) { var sign = value < 0 ? -1 : 1; return sign * MAX_INTEGER; } return value === value ? value : 0; } function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? remainder ? result - remainder : result : 0; } function identity3(value) { return value; } var asyncTag = "[object AsyncFunction]", funcTag$2 = "[object Function]", genTag$1 = "[object GeneratorFunction]", proxyTag = "[object Proxy]"; function isFunction3(value) { if (!isObject(value)) { return false; } var tag = baseGetTag(value); return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag; } var coreJsData = root$1["__core-js_shared__"]; const coreJsData$1 = coreJsData; var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData$1 && coreJsData$1.keys && coreJsData$1.keys.IE_PROTO || ""); return uid ? "Symbol(src)_1." + uid : ""; })(); function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } var funcProto$1 = Function.prototype; var funcToString$1 = funcProto$1.toString; function toSource(func) { if (func != null) { try { return funcToString$1.call(func); } catch (e2) { } try { return func + ""; } catch (e2) { } } return ""; } var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; var reIsHostCtor = /^\[object .+?Constructor\]$/; var funcProto = Function.prototype, objectProto$h = Object.prototype; var funcToString = funcProto.toString; var hasOwnProperty$f = objectProto$h.hasOwnProperty; var reIsNative = RegExp( "^" + funcToString.call(hasOwnProperty$f).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" ); function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction3(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } function getValue(object, key) { return object == null ? void 0 : object[key]; } function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : void 0; } var WeakMap2 = getNative(root$1, "WeakMap"); const WeakMap$1 = WeakMap2; var objectCreate = Object.create; var baseCreate = /* @__PURE__ */ (function() { function object() { } return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object(); object.prototype = void 0; return result; }; })(); const baseCreate$1 = baseCreate; function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } function noop2() { } function copyArray(source, array) { var index2 = -1, length3 = source.length; array || (array = Array(length3)); while (++index2 < length3) { array[index2] = source[index2]; } return array; } var HOT_COUNT = 800, HOT_SPAN = 16; var nativeNow = Date.now; function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(void 0, arguments); }; } function constant(value) { return function() { return value; }; } var defineProperty = (function() { try { var func = getNative(Object, "defineProperty"); func({}, "", {}); return func; } catch (e2) { } })(); const defineProperty$1 = defineProperty; var baseSetToString = !defineProperty$1 ? identity3 : function(func, string) { return defineProperty$1(func, "toString", { configurable: true, enumerable: false, value: constant(string), writable: true }); }; const baseSetToString$1 = baseSetToString; var setToString = shortOut(baseSetToString$1); const setToString$1 = setToString; function arrayEach(array, iteratee) { var index2 = -1, length3 = array == null ? 0 : array.length; while (++index2 < length3) { if (iteratee(array[index2], index2, array) === false) { break; } } return array; } function baseFindIndex(array, predicate, fromIndex, fromRight) { var length3 = array.length, index2 = fromIndex + (fromRight ? 1 : -1); while (fromRight ? index2-- : ++index2 < length3) { if (predicate(array[index2], index2, array)) { return index2; } } return -1; } function baseIsNaN(value) { return value !== value; } function strictIndexOf(array, value, fromIndex) { var index2 = fromIndex - 1, length3 = array.length; while (++index2 < length3) { if (array[index2] === value) { return index2; } } return -1; } function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } function arrayIncludes(array, value) { var length3 = array == null ? 0 : array.length; return !!length3 && baseIndexOf(array, value, 0) > -1; } var MAX_SAFE_INTEGER$1 = 9007199254740991; var reIsUint = /^(?:0|[1-9]\d*)$/; function isIndex(value, length3) { var type = typeof value; length3 = length3 == null ? MAX_SAFE_INTEGER$1 : length3; return !!length3 && (type == "number" || type != "symbol" && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length3; } function baseAssignValue(object, key, value) { if (key == "__proto__" && defineProperty$1) { defineProperty$1(object, key, { configurable: true, enumerable: true, value, writable: true }); } else { object[key] = value; } } function eq(value, other) { return value === other || value !== value && other !== other; } var objectProto$g = Object.prototype; var hasOwnProperty$e = objectProto$g.hasOwnProperty; function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty$e.call(object, key) && eq(objValue, value)) || value === void 0 && !(key in object)) { baseAssignValue(object, key, value); } } function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index2 = -1, length3 = props.length; while (++index2 < length3) { var key = props[index2]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0; if (newValue === void 0) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } var nativeMax$3 = Math.max; function overRest(func, start, transform) { start = nativeMax$3(start === void 0 ? func.length - 1 : start, 0); return function() { var args = arguments, index2 = -1, length3 = nativeMax$3(args.length - start, 0), array = Array(length3); while (++index2 < length3) { array[index2] = args[start + index2]; } index2 = -1; var otherArgs = Array(start + 1); while (++index2 < start) { otherArgs[index2] = args[index2]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } function baseRest(func, start) { return setToString$1(overRest(func, start, identity3), func + ""); } var MAX_SAFE_INTEGER = 9007199254740991; function isLength(value) { return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction3(value); } function isIterateeCall(value, index2, object) { if (!isObject(object)) { return false; } var type = typeof index2; if (type == "number" ? isArrayLike(object) && isIndex(index2, object.length) : type == "string" && index2 in object) { return eq(object[index2], value); } return false; } function createAssigner(assigner) { return baseRest(function(object, sources) { var index2 = -1, length3 = sources.length, customizer = length3 > 1 ? sources[length3 - 1] : void 0, guard = length3 > 2 ? sources[2] : void 0; customizer = assigner.length > 3 && typeof customizer == "function" ? (length3--, customizer) : void 0; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length3 < 3 ? void 0 : customizer; length3 = 1; } object = Object(object); while (++index2 < length3) { var source = sources[index2]; if (source) { assigner(object, source, index2, customizer); } } return object; }); } var objectProto$f = Object.prototype; function isPrototype(value) { var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto$f; return value === proto; } function baseTimes(n2, iteratee) { var index2 = -1, result = Array(n2); while (++index2 < n2) { result[index2] = iteratee(index2); } return result; } var argsTag$3 = "[object Arguments]"; function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag$3; } var objectProto$e = Object.prototype; var hasOwnProperty$d = objectProto$e.hasOwnProperty; var propertyIsEnumerable$1 = objectProto$e.propertyIsEnumerable; var isArguments = baseIsArguments( /* @__PURE__ */ (function() { return arguments; })() ) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty$d.call(value, "callee") && !propertyIsEnumerable$1.call(value, "callee"); }; const isArguments$1 = isArguments; function stubFalse() { return false; } var freeExports$2 = typeof exports == "object" && exports && !exports.nodeType && exports; var freeModule$2 = freeExports$2 && typeof module == "object" && module && !module.nodeType && module; var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; var Buffer$1 = moduleExports$2 ? root$1.Buffer : void 0; var nativeIsBuffer = Buffer$1 ? Buffer$1.isBuffer : void 0; var isBuffer = nativeIsBuffer || stubFalse; const isBuffer$1 = isBuffer; var argsTag$2 = "[object Arguments]", arrayTag$2 = "[object Array]", boolTag$3 = "[object Boolean]", dateTag$3 = "[object Date]", errorTag$2 = "[object Error]", funcTag$1 = "[object Function]", mapTag$6 = "[object Map]", numberTag$3 = "[object Number]", objectTag$3 = "[object Object]", regexpTag$4 = "[object RegExp]", setTag$6 = "[object Set]", stringTag$4 = "[object String]", weakMapTag$2 = "[object WeakMap]"; var arrayBufferTag$3 = "[object ArrayBuffer]", dataViewTag$4 = "[object DataView]", float32Tag$2 = "[object Float32Array]", float64Tag$2 = "[object Float64Array]", int8Tag$2 = "[object Int8Array]", int16Tag$2 = "[object Int16Array]", int32Tag$2 = "[object Int32Array]", uint8Tag$2 = "[object Uint8Array]", uint8ClampedTag$2 = "[object Uint8ClampedArray]", uint16Tag$2 = "[object Uint16Array]", uint32Tag$2 = "[object Uint32Array]"; var typedArrayTags = {}; typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] = typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] = typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] = typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] = typedArrayTags[uint32Tag$2] = true; typedArrayTags[argsTag$2] = typedArrayTags[arrayTag$2] = typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$3] = typedArrayTags[dataViewTag$4] = typedArrayTags[dateTag$3] = typedArrayTags[errorTag$2] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$6] = typedArrayTags[numberTag$3] = typedArrayTags[objectTag$3] = typedArrayTags[regexpTag$4] = typedArrayTags[setTag$6] = typedArrayTags[stringTag$4] = typedArrayTags[weakMapTag$2] = false; function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } function baseUnary(func) { return function(value) { return func(value); }; } var freeExports$1 = typeof exports == "object" && exports && !exports.nodeType && exports; var freeModule$1 = freeExports$1 && typeof module == "object" && module && !module.nodeType && module; var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; var freeProcess = moduleExports$1 && freeGlobal$1.process; var nodeUtil = (function() { try { var types2 = freeModule$1 && freeModule$1.require && freeModule$1.require("util").types; if (types2) { return types2; } return freeProcess && freeProcess.binding && freeProcess.binding("util"); } catch (e2) { } })(); const nodeUtil$1 = nodeUtil; var nodeIsTypedArray = nodeUtil$1 && nodeUtil$1.isTypedArray; var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; const isTypedArray$1 = isTypedArray; var objectProto$d = Object.prototype; var hasOwnProperty$c = objectProto$d.hasOwnProperty; function arrayLikeKeys(value, inherited) { var isArr = isArray$1(value), isArg = !isArr && isArguments$1(value), isBuff = !isArr && !isArg && isBuffer$1(value), isType = !isArr && !isArg && !isBuff && isTypedArray$1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length3 = result.length; for (var key in value) { if ((inherited || hasOwnProperty$c.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. isIndex(key, length3)))) { result.push(key); } } return result; } function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var nativeKeys = overArg(Object.keys, Object); const nativeKeys$1 = nativeKeys; var objectProto$c = Object.prototype; var hasOwnProperty$b = objectProto$c.hasOwnProperty; function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys$1(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$b.call(object, key) && key != "constructor") { result.push(key); } } return result; } function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } var objectProto$b = Object.prototype; var hasOwnProperty$a = objectProto$b.hasOwnProperty; var assign3 = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty$a.call(source, key)) { assignValue(object, key, source[key]); } } }); const assign$1 = assign3; function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var objectProto$a = Object.prototype; var hasOwnProperty$9 = objectProto$a.hasOwnProperty; function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == "constructor" && (isProto || !hasOwnProperty$9.call(object, key)))) { result.push(key); } } return result; } function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; function isKey(value, object) { if (isArray$1(value)) { return false; } var type = typeof value; if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); } var nativeCreate = getNative(Object, "create"); const nativeCreate$1 = nativeCreate; function hashClear() { this.__data__ = nativeCreate$1 ? nativeCreate$1(null) : {}; this.size = 0; } function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var HASH_UNDEFINED$2 = "__lodash_hash_undefined__"; var objectProto$9 = Object.prototype; var hasOwnProperty$8 = objectProto$9.hasOwnProperty; function hashGet(key) { var data = this.__data__; if (nativeCreate$1) { var result = data[key]; return result === HASH_UNDEFINED$2 ? void 0 : result; } return hasOwnProperty$8.call(data, key) ? data[key] : void 0; } var objectProto$8 = Object.prototype; var hasOwnProperty$7 = objectProto$8.hasOwnProperty; function hashHas(key) { var data = this.__data__; return nativeCreate$1 ? data[key] !== void 0 : hasOwnProperty$7.call(data, key); } var HASH_UNDEFINED$1 = "__lodash_hash_undefined__"; function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = nativeCreate$1 && value === void 0 ? HASH_UNDEFINED$1 : value; return this; } function Hash(entries) { var index2 = -1, length3 = entries == null ? 0 : entries.length; this.clear(); while (++index2 < length3) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } Hash.prototype.clear = hashClear; Hash.prototype["delete"] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; function listCacheClear() { this.__data__ = []; this.size = 0; } function assocIndexOf(array, key) { var length3 = array.length; while (length3--) { if (eq(array[length3][0], key)) { return length3; } } return -1; } var arrayProto = Array.prototype; var splice = arrayProto.splice; function listCacheDelete(key) { var data = this.__data__, index2 = assocIndexOf(data, key); if (index2 < 0) { return false; } var lastIndex = data.length - 1; if (index2 == lastIndex) { data.pop(); } else { splice.call(data, index2, 1); } --this.size; return true; } function listCacheGet(key) { var data = this.__data__, index2 = assocIndexOf(data, key); return index2 < 0 ? void 0 : data[index2][1]; } function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } function listCacheSet(key, value) { var data = this.__data__, index2 = assocIndexOf(data, key); if (index2 < 0) { ++this.size; data.push([key, value]); } else { data[index2][1] = value; } return this; } function ListCache(entries) { var index2 = -1, length3 = entries == null ? 0 : entries.length; this.clear(); while (++index2 < length3) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } ListCache.prototype.clear = listCacheClear; ListCache.prototype["delete"] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; var Map$1 = getNative(root$1, "Map"); const Map$2 = Map$1; function mapCacheClear() { this.size = 0; this.__data__ = { hash: new Hash(), map: new (Map$2 || ListCache)(), string: new Hash() }; } function isKeyable(value) { var type = typeof value; return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; } function getMapData(map22, key) { var data = map22.__data__; return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; } function mapCacheDelete(key) { var result = getMapData(this, key)["delete"](key); this.size -= result ? 1 : 0; return result; } function mapCacheGet(key) { return getMapData(this, key).get(key); } function mapCacheHas(key) { return getMapData(this, key).has(key); } function mapCacheSet(key, value) { var data = getMapData(this, key), size2 = data.size; data.set(key, value); this.size += data.size == size2 ? 0 : 1; return this; } function MapCache(entries) { var index2 = -1, length3 = entries == null ? 0 : entries.length; this.clear(); while (++index2 < length3) { var entry = entries[index2]; this.set(entry[0], entry[1]); } } MapCache.prototype.clear = mapCacheClear; MapCache.prototype["delete"] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; var FUNC_ERROR_TEXT$1 = "Expected a function"; function memoize(func, resolver) { if (typeof func != "function" || resolver != null && typeof resolver != "function") { throw new TypeError(FUNC_ERROR_TEXT$1); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache)(); return memoized; } memoize.Cache = MapCache; var MAX_MEMOIZE_SIZE = 500; function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; var reEscapeChar = /\\(\\)?/g; var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46) { result.push(""); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match); }); return result; }); const stringToPath$1 = stringToPath; function toString(value) { return value == null ? "" : baseToString(value); } function castPath(value, object) { if (isArray$1(value)) { return value; } return isKey(value, object) ? [value] : stringToPath$1(toString(value)); } var INFINITY$1 = 1 / 0; function toKey(value) { if (typeof value == "string" || isSymbol(value)) { return value; } var result = value + ""; return result == "0" && 1 / value == -INFINITY$1 ? "-0" : result; } function baseGet(object, path) { path = castPath(path, object); var index2 = 0, length3 = path.length; while (object != null && index2 < length3) { object = object[toKey(path[index2++])]; } return index2 && index2 == length3 ? object : void 0; } function get(object, path, defaultValue) { var result = object == null ? void 0 : baseGet(object, path); return result === void 0 ? defaultValue : result; } function arrayPush(array, values2) { var index2 = -1, length3 = values2.length, offset = array.length; while (++index2 < length3) { array[offset + index2] = values2[index2]; } return array; } var spreadableSymbol = Symbol$2 ? Symbol$2.isConcatSpreadable : void 0; function isFlattenable(value) { return isArray$1(value) || isArguments$1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } function baseFlatten(array, depth, predicate, isStrict, result) { var index2 = -1, length3 = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index2 < length3) { var value = array[index2]; if (depth > 0 && predicate(value)) { if (depth > 1) { baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } function flatten(array) { var length3 = array == null ? 0 : array.length; return length3 ? baseFlatten(array, 1) : []; } var getPrototype = overArg(Object.getPrototypeOf, Object); const getPrototype$1 = getPrototype; function baseSlice(array, start, end) { var index2 = -1, length3 = array.length; if (start < 0) { start = -start > length3 ? 0 : length3 + start; } end = end > length3 ? length3 : end; if (end < 0) { end += length3; } length3 = start > end ? 0 : end - start >>> 0; start >>>= 0; var result = Array(length3); while (++index2 < length3) { result[index2] = array[index2 + start]; } return result; } function arrayReduce(array, iteratee, accumulator, initAccum) { var index2 = -1, length3 = array == null ? 0 : array.length; if (initAccum && length3) { accumulator = array[++index2]; } while (++index2 < length3) { accumulator = iteratee(accumulator, array[index2], index2, array); } return accumulator; } function stackClear() { this.__data__ = new ListCache(); this.size = 0; } function stackDelete(key) { var data = this.__data__, result = data["delete"](key); this.size = data.size; return result; } function stackGet(key) { return this.__data__.get(key); } function stackHas(key) { return this.__data__.has(key); } var LARGE_ARRAY_SIZE$2 = 200; function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map$2 || pairs.length < LARGE_ARRAY_SIZE$2 - 1) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } Stack.prototype.clear = stackClear; Stack.prototype["delete"] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; var moduleExports = freeModule && freeModule.exports === freeExports; var Buffer2 = moduleExports ? root$1.Buffer : void 0, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : void 0; function cloneBuffer(buffer2, isDeep) { if (isDeep) { return buffer2.slice(); } var length3 = buffer2.length, result = allocUnsafe ? allocUnsafe(length3) : new buffer2.constructor(length3); buffer2.copy(result); return result; } function arrayFilter(array, predicate) { var index2 = -1, length3 = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index2 < length3) { var value = array[index2]; if (predicate(value, index2, array)) { result[resIndex++] = value; } } return result; } function stubArray() { return []; } var objectProto$7 = Object.prototype; var propertyIsEnumerable = objectProto$7.propertyIsEnumerable; var nativeGetSymbols$1 = Object.getOwnPropertySymbols; var getSymbols = !nativeGetSymbols$1 ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols$1(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; const getSymbols$1 = getSymbols; function copySymbols(source, object) { return copyObject(source, getSymbols$1(source), object); } var nativeGetSymbols = Object.getOwnPropertySymbols; var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols$1(object)); object = getPrototype$1(object); } return result; }; const getSymbolsIn$1 = getSymbolsIn; function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn$1(source), object); } function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray$1(object) ? result : arrayPush(result, symbolsFunc(object)); } function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols$1); } function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn$1); } var DataView2 = getNative(root$1, "DataView"); const DataView$1 = DataView2; var Promise$1 = getNative(root$1, "Promise"); const Promise$2 = Promise$1; var Set2 = getNative(root$1, "Set"); const Set$1 = Set2; var mapTag$5 = "[object Map]", objectTag$2 = "[object Object]", promiseTag = "[object Promise]", setTag$5 = "[object Set]", weakMapTag$1 = "[object WeakMap]"; var dataViewTag$3 = "[object DataView]"; var dataViewCtorString = toSource(DataView$1), mapCtorString = toSource(Map$2), promiseCtorString = toSource(Promise$2), setCtorString = toSource(Set$1), weakMapCtorString = toSource(WeakMap$1); var getTag = baseGetTag; if (DataView$1 && getTag(new DataView$1(new ArrayBuffer(1))) != dataViewTag$3 || Map$2 && getTag(new Map$2()) != mapTag$5 || Promise$2 && getTag(Promise$2.resolve()) != promiseTag || Set$1 && getTag(new Set$1()) != setTag$5 || WeakMap$1 && getTag(new WeakMap$1()) != weakMapTag$1) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag$2 ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : ""; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$3; case mapCtorString: return mapTag$5; case promiseCtorString: return promiseTag; case setCtorString: return setTag$5; case weakMapCtorString: return weakMapTag$1; } } return result; }; } const getTag$1 = getTag; var objectProto$6 = Object.prototype; var hasOwnProperty$6 = objectProto$6.hasOwnProperty; function initCloneArray(array) { var length3 = array.length, result = new array.constructor(length3); if (length3 && typeof array[0] == "string" && hasOwnProperty$6.call(array, "index")) { result.index = array.index; result.input = array.input; } return result; } var Uint8Array2 = root$1.Uint8Array; const Uint8Array$1 = Uint8Array2; function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array$1(result).set(new Uint8Array$1(arrayBuffer)); return result; } function cloneDataView(dataView, isDeep) { var buffer2 = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer2, dataView.byteOffset, dataView.byteLength); } var reFlags = /\w*$/; function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var symbolProto$1 = Symbol$2 ? Symbol$2.prototype : void 0, symbolValueOf$1 = symbolProto$1 ? symbolProto$1.valueOf : void 0; function cloneSymbol(symbol) { return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {}; } function cloneTypedArray(typedArray, isDeep) { var buffer2 = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer2, typedArray.byteOffset, typedArray.length); } var boolTag$2 = "[object Boolean]", dateTag$2 = "[object Date]", mapTag$4 = "[object Map]", numberTag$2 = "[object Number]", regexpTag$3 = "[object RegExp]", setTag$4 = "[object Set]", stringTag$3 = "[object String]", symbolTag$2 = "[object Symbol]"; var arrayBufferTag$2 = "[object ArrayBuffer]", dataViewTag$2 = "[object DataView]", float32Tag$1 = "[object Float32Array]", float64Tag$1 = "[object Float64Array]", int8Tag$1 = "[object Int8Array]", int16Tag$1 = "[object Int16Array]", int32Tag$1 = "[object Int32Array]", uint8Tag$1 = "[object Uint8Array]", uint8ClampedTag$1 = "[object Uint8ClampedArray]", uint16Tag$1 = "[object Uint16Array]", uint32Tag$1 = "[object Uint32Array]"; function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag$2: return cloneArrayBuffer(object); case boolTag$2: case dateTag$2: return new Ctor(+object); case dataViewTag$2: return cloneDataView(object, isDeep); case float32Tag$1: case float64Tag$1: case int8Tag$1: case int16Tag$1: case int32Tag$1: case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: return cloneTypedArray(object, isDeep); case mapTag$4: return new Ctor(); case numberTag$2: case stringTag$3: return new Ctor(object); case regexpTag$3: return cloneRegExp(object); case setTag$4: return new Ctor(); case symbolTag$2: return cloneSymbol(object); } } function initCloneObject(object) { return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate$1(getPrototype$1(object)) : {}; } var mapTag$3 = "[object Map]"; function baseIsMap(value) { return isObjectLike(value) && getTag$1(value) == mapTag$3; } var nodeIsMap = nodeUtil$1 && nodeUtil$1.isMap; var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; const isMap$1 = isMap; var setTag$3 = "[object Set]"; function baseIsSet(value) { return isObjectLike(value) && getTag$1(value) == setTag$3; } var nodeIsSet = nodeUtil$1 && nodeUtil$1.isSet; var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; const isSet$1 = isSet; var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG$1 = 4; var argsTag$1 = "[object Arguments]", arrayTag$1 = "[object Array]", boolTag$1 = "[object Boolean]", dateTag$1 = "[object Date]", errorTag$1 = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag$2 = "[object Map]", numberTag$1 = "[object Number]", objectTag$1 = "[object Object]", regexpTag$2 = "[object RegExp]", setTag$2 = "[object Set]", stringTag$2 = "[object String]", symbolTag$1 = "[object Symbol]", weakMapTag = "[object WeakMap]"; var arrayBufferTag$1 = "[object ArrayBuffer]", dataViewTag$1 = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; var cloneableTags = {}; cloneableTags[argsTag$1] = cloneableTags[arrayTag$1] = cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] = cloneableTags[boolTag$1] = cloneableTags[dateTag$1] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag$2] = cloneableTags[numberTag$1] = cloneableTags[objectTag$1] = cloneableTags[regexpTag$2] = cloneableTags[setTag$2] = cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag$1] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG$1; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== void 0) { return result; } if (!isObject(value)) { return value; } var isArr = isArray$1(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag$1(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer$1(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag$1 || tag == argsTag$1 || isFunc && !object) { result = isFlat || isFunc ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } stack || (stack = new Stack()); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet$1(value)) { value.forEach(function(subValue3) { result.add(baseClone(subValue3, bitmask, customizer, subValue3, value, stack)); }); } else if (isMap$1(value)) { value.forEach(function(subValue3, key2) { result.set(key2, baseClone(subValue3, bitmask, customizer, key2, value, stack)); }); } var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys; var props = isArr ? void 0 : keysFunc(value); arrayEach(props || value, function(subValue3, key2) { if (props) { key2 = subValue3; subValue3 = value[key2]; } assignValue(result, key2, baseClone(subValue3, bitmask, customizer, key2, value, stack)); }); return result; } var CLONE_SYMBOLS_FLAG = 4; function clone2(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } function compact(array) { var index2 = -1, length3 = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index2 < length3) { var value = array[index2]; if (value) { result[resIndex++] = value; } } return result; } var HASH_UNDEFINED = "__lodash_hash_undefined__"; function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } function setCacheHas(value) { return this.__data__.has(value); } function SetCache(values2) { var index2 = -1, length3 = values2 == null ? 0 : values2.length; this.__data__ = new MapCache(); while (++index2 < length3) { this.add(values2[index2]); } } SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; function arraySome(array, predicate) { var index2 = -1, length3 = array == null ? 0 : array.length; while (++index2 < length3) { if (predicate(array[index2], index2, array)) { return true; } } return false; } function cacheHas(cache, key) { return cache.has(key); } var COMPARE_PARTIAL_FLAG$5 = 1, COMPARE_UNORDERED_FLAG$3 = 2; function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index2 = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG$3 ? new SetCache() : void 0; stack.set(array, other); stack.set(other, array); while (++index2 < arrLength) { var arrValue = array[index2], othValue = other[index2]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index2, other, array, stack) : customizer(arrValue, othValue, index2, array, other, stack); } if (compared !== void 0) { if (compared) { continue; } result = false; break; } if (seen) { if (!arraySome(other, function(othValue2, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { result = false; break; } } stack["delete"](array); stack["delete"](other); return result; } function mapToArray(map22) { var index2 = -1, result = Array(map22.size); map22.forEach(function(value, key) { result[++index2] = [key, value]; }); return result; } function setToArray(set) { var index2 = -1, result = Array(set.size); set.forEach(function(value) { result[++index2] = value; }); return result; } var COMPARE_PARTIAL_FLAG$4 = 1, COMPARE_UNORDERED_FLAG$2 = 2; var boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", mapTag$1 = "[object Map]", numberTag = "[object Number]", regexpTag$1 = "[object RegExp]", setTag$1 = "[object Set]", stringTag$1 = "[object String]", symbolTag = "[object Symbol]"; var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]"; var symbolProto = Symbol$2 ? Symbol$2.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0; function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array$1(object), new Uint8Array$1(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag$1: case stringTag$1: return object == other + ""; case mapTag$1: var convert = mapToArray; case setTag$1: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$2; stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack["delete"](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } var COMPARE_PARTIAL_FLAG$3 = 1; var objectProto$5 = Object.prototype; var hasOwnProperty$5 = objectProto$5.hasOwnProperty; function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index2 = objLength; while (index2--) { var key = objProps[index2]; if (!(isPartial ? key in other : hasOwnProperty$5.call(other, key))) { return false; } } var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index2 < objLength) { key = objProps[index2]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { result = false; break; } skipCtor || (skipCtor = key == "constructor"); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; if (objCtor != othCtor && "constructor" in object && "constructor" in other && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { result = false; } } stack["delete"](object); stack["delete"](other); return result; } var COMPARE_PARTIAL_FLAG$2 = 1; var argsTag = "[object Arguments]", arrayTag = "[object Array]", objectTag = "[object Object]"; var objectProto$4 = Object.prototype; var hasOwnProperty$4 = objectProto$4.hasOwnProperty; function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray$1(object), othIsArr = isArray$1(other), objTag = objIsArr ? arrayTag : getTag$1(object), othTag = othIsArr ? arrayTag : getTag$1(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer$1(object)) { if (!isBuffer$1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack()); return objIsArr || isTypedArray$1(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) { var objIsWrapped = objIsObj && hasOwnProperty$4.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty$4.call(other, "__wrapped__"); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack()); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack()); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var COMPARE_PARTIAL_FLAG$1 = 1, COMPARE_UNORDERED_FLAG$1 = 2; function baseIsMatch(object, source, matchData, customizer) { var index2 = matchData.length, length3 = index2, noCustomizer = !customizer; if (object == null) { return !length3; } object = Object(object); while (index2--) { var data = matchData[index2]; if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { return false; } } while (++index2 < length3) { data = matchData[index2]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === void 0 && !(key in object)) { return false; } } else { var stack = new Stack(); if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === void 0 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack) : result)) { return false; } } } return true; } function isStrictComparable(value) { return value === value && !isObject(value); } function getMatchData(object) { var result = keys(object), length3 = result.length; while (length3--) { var key = result[length3], value = object[key]; result[length3] = [key, value, isStrictComparable(value)]; } return result; } function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== void 0 || key in Object(object)); }; } function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } function baseHasIn(object, key) { return object != null && key in Object(object); } function hasPath(object, path, hasFunc) { path = castPath(path, object); var index2 = -1, length3 = path.length, result = false; while (++index2 < length3) { var key = toKey(path[index2]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index2 != length3) { return result; } length3 = object == null ? 0 : object.length; return !!length3 && isLength(length3) && isIndex(key, length3) && (isArray$1(object) || isArguments$1(object)); } function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return objValue === void 0 && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } function baseProperty(key) { return function(object) { return object == null ? void 0 : object[key]; }; } function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } function baseIteratee(value) { if (typeof value == "function") { return value; } if (value == null) { return identity3; } if (typeof value == "object") { return isArray$1(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } function arrayAggregator(array, setter, iteratee, accumulator) { var index2 = -1, length3 = array == null ? 0 : array.length; while (++index2 < length3) { var value = array[index2]; setter(accumulator, value, iteratee(value), array); } return accumulator; } function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index2 = -1, iterable = Object(object), props = keysFunc(object), length3 = props.length; while (length3--) { var key = props[fromRight ? length3 : ++index2]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var baseFor = createBaseFor(); const baseFor$1 = baseFor; function baseForOwn(object, iteratee) { return object && baseFor$1(object, iteratee, keys); } function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length3 = collection.length, index2 = fromRight ? length3 : -1, iterable = Object(collection); while (fromRight ? index2-- : ++index2 < length3) { if (iteratee(iterable[index2], index2, iterable) === false) { break; } } return collection; }; } var baseEach = createBaseEach(baseForOwn); const baseEach$1 = baseEach; function baseAggregator(collection, setter, iteratee, accumulator) { baseEach$1(collection, function(value, key, collection2) { setter(accumulator, value, iteratee(value), collection2); }); return accumulator; } function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray$1(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, baseIteratee(iteratee), accumulator); }; } var objectProto$3 = Object.prototype; var hasOwnProperty$3 = objectProto$3.hasOwnProperty; var defaults2 = baseRest(function(object, sources) { object = Object(object); var index2 = -1; var length3 = sources.length; var guard = length3 > 2 ? sources[2] : void 0; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length3 = 1; } while (++index2 < length3) { var source = sources[index2]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === void 0 || eq(value, objectProto$3[key]) && !hasOwnProperty$3.call(object, key)) { object[key] = source[key]; } } } return object; }); const defaults$1 = defaults2; function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } function arrayIncludesWith(array, value, comparator) { var index2 = -1, length3 = array == null ? 0 : array.length; while (++index2 < length3) { if (comparator(value, array[index2])) { return true; } } return false; } var LARGE_ARRAY_SIZE$1 = 200; function baseDifference(array, values2, iteratee, comparator) { var index2 = -1, includes2 = arrayIncludes, isCommon = true, length3 = array.length, result = [], valuesLength = values2.length; if (!length3) { return result; } if (iteratee) { values2 = arrayMap(values2, baseUnary(iteratee)); } if (comparator) { includes2 = arrayIncludesWith; isCommon = false; } else if (values2.length >= LARGE_ARRAY_SIZE$1) { includes2 = cacheHas; isCommon = false; values2 = new SetCache(values2); } outer: while (++index2 < length3) { var value = array[index2], computed = iteratee == null ? value : iteratee(value); value = comparator || value !== 0 ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values2[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes2(values2, computed, comparator)) { result.push(value); } } return result; } var difference = baseRest(function(array, values2) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true)) : []; }); const difference$1 = difference; function last(array) { var length3 = array == null ? 0 : array.length; return length3 ? array[length3 - 1] : void 0; } function drop(array, n2, guard) { var length3 = array == null ? 0 : array.length; if (!length3) { return []; } n2 = guard || n2 === void 0 ? 1 : toInteger(n2); return baseSlice(array, n2 < 0 ? 0 : n2, length3); } function dropRight(array, n2, guard) { var length3 = array == null ? 0 : array.length; if (!length3) { return []; } n2 = guard || n2 === void 0 ? 1 : toInteger(n2); n2 = length3 - n2; return baseSlice(array, 0, n2 < 0 ? 0 : n2); } function castFunction(value) { return typeof value == "function" ? value : identity3; } function forEach(collection, iteratee) { var func = isArray$1(collection) ? arrayEach : baseEach$1; return func(collection, castFunction(iteratee)); } function arrayEvery(array, predicate) { var index2 = -1, length3 = array == null ? 0 : array.length; while (++index2 < length3) { if (!predicate(array[index2], index2, array)) { return false; } } return true; } function baseEvery(collection, predicate) { var result = true; baseEach$1(collection, function(value, index2, collection2) { result = !!predicate(value, index2, collection2); return result; }); return result; } function every(collection, predicate, guard) { var func = isArray$1(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = void 0; } return func(collection, baseIteratee(predicate)); } function baseFilter(collection, predicate) { var result = []; baseEach$1(collection, function(value, index2, collection2) { if (predicate(value, index2, collection2)) { result.push(value); } }); return result; } function filter(collection, predicate) { var func = isArray$1(collection) ? arrayFilter : baseFilter; return func(collection, baseIteratee(predicate)); } function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = baseIteratee(predicate); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index2 = findIndexFunc(collection, predicate, fromIndex); return index2 > -1 ? iterable[iteratee ? collection[index2] : index2] : void 0; }; } var nativeMax$2 = Math.max; function findIndex(array, predicate, fromIndex) { var length3 = array == null ? 0 : array.length; if (!length3) { return -1; } var index2 = fromIndex == null ? 0 : toInteger(fromIndex); if (index2 < 0) { index2 = nativeMax$2(length3 + index2, 0); } return baseFindIndex(array, baseIteratee(predicate), index2); } var find = createFind(findIndex); const find$1 = find; function head(array) { return array && array.length ? array[0] : void 0; } function baseMap(collection, iteratee) { var index2 = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach$1(collection, function(value, key, collection2) { result[++index2] = iteratee(value, key, collection2); }); return result; } function map2(collection, iteratee) { var func = isArray$1(collection) ? arrayMap : baseMap; return func(collection, baseIteratee(iteratee)); } function flatMap(collection, iteratee) { return baseFlatten(map2(collection, iteratee), 1); } var objectProto$2 = Object.prototype; var hasOwnProperty$2 = objectProto$2.hasOwnProperty; var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty$2.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); const groupBy$1 = groupBy; var objectProto$1 = Object.prototype; var hasOwnProperty$1 = objectProto$1.hasOwnProperty; function baseHas(object, key) { return object != null && hasOwnProperty$1.call(object, key); } function has(object, path) { return object != null && hasPath(object, path, baseHas); } var stringTag = "[object String]"; function isString(value) { return typeof value == "string" || !isArray$1(value) && isObjectLike(value) && baseGetTag(value) == stringTag; } function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } function values(object) { return object == null ? [] : baseValues(object, keys(object)); } var nativeMax$1 = Math.max; function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; var length3 = collection.length; if (fromIndex < 0) { fromIndex = nativeMax$1(length3 + fromIndex, 0); } return isString(collection) ? fromIndex <= length3 && collection.indexOf(value, fromIndex) > -1 : !!length3 && baseIndexOf(collection, value, fromIndex) > -1; } var nativeMax = Math.max; function indexOf(array, value, fromIndex) { var length3 = array == null ? 0 : array.length; if (!length3) { return -1; } var index2 = fromIndex == null ? 0 : toInteger(fromIndex); if (index2 < 0) { index2 = nativeMax(length3 + index2, 0); } return baseIndexOf(array, value, index2); } var mapTag = "[object Map]", setTag = "[object Set]"; var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray$1(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer$1(value) || isTypedArray$1(value) || isArguments$1(value))) { return !value.length; } var tag = getTag$1(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } var regexpTag = "[object RegExp]"; function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } var nodeIsRegExp = nodeUtil$1 && nodeUtil$1.isRegExp; var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; const isRegExp$1 = isRegExp; function isUndefined(value) { return value === void 0; } var FUNC_ERROR_TEXT = "Expected a function"; function negate(predicate) { if (typeof predicate != "function") { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index2 = -1, length3 = path.length, lastIndex = length3 - 1, nested = object; while (nested != null && ++index2 < length3) { var key = toKey(path[index2]), newValue = value; if (key === "__proto__" || key === "constructor" || key === "prototype") { return object; } if (index2 != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : void 0; if (newValue === void 0) { newValue = isObject(objValue) ? objValue : isIndex(path[index2 + 1]) ? [] : {}; } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } function basePickBy(object, paths, predicate) { var index2 = -1, length3 = paths.length, result = {}; while (++index2 < length3) { var path = paths[index2], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = baseIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index2, collection2) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index2, collection2); }); return accumulator; } function reduce2(collection, iteratee, accumulator) { var func = isArray$1(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, baseIteratee(iteratee), accumulator, initAccum, baseEach$1); } function reject(collection, predicate) { var func = isArray$1(collection) ? arrayFilter : baseFilter; return func(collection, negate(baseIteratee(predicate))); } function baseSome(collection, predicate) { var result; baseEach$1(collection, function(value, index2, collection2) { result = predicate(value, index2, collection2); return !result; }); return !!result; } function some(collection, predicate, guard) { var func = isArray$1(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = void 0; } return func(collection, baseIteratee(predicate)); } var INFINITY = 1 / 0; var createSet = !(Set$1 && 1 / setToArray(new Set$1([, -0]))[1] == INFINITY) ? noop2 : function(values2) { return new Set$1(values2); }; const createSet$1 = createSet; var LARGE_ARRAY_SIZE = 200; function baseUniq(array, iteratee, comparator) { var index2 = -1, includes2 = arrayIncludes, length3 = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes2 = arrayIncludesWith; } else if (length3 >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet$1(array); if (set) { return setToArray(set); } isCommon = false; includes2 = cacheHas; seen = new SetCache(); } else { seen = iteratee ? [] : result; } outer: while (++index2 < length3) { var value = array[index2], computed = iteratee ? iteratee(value) : value; value = comparator || value !== 0 ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes2(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } function uniq(array) { return array && array.length ? baseUniq(array) : []; } function PRINT_ERROR(msg) { if (console && console.error) { console.error(`Error: ${msg}`); } } function PRINT_WARNING(msg) { if (console && console.warn) { console.warn(`Warning: ${msg}`); } } function timer2(func) { const start = (/* @__PURE__ */ new Date()).getTime(); const val = func(); const end = (/* @__PURE__ */ new Date()).getTime(); const total = end - start; return { time: total, value: val }; } function toFastProperties(toBecomeFast) { function FakeConstructor() { } FakeConstructor.prototype = toBecomeFast; const fakeInstance = new FakeConstructor(); function fakeAccess() { return typeof fakeInstance.bar; } fakeAccess(); fakeAccess(); return toBecomeFast; } function tokenLabel$1(tokType) { if (hasTokenLabel$1(tokType)) { return tokType.LABEL; } else { return tokType.name; } } function hasTokenLabel$1(obj) { return isString(obj.LABEL) && obj.LABEL !== ""; } class AbstractProduction { get definition() { return this._definition; } set definition(value) { this._definition = value; } constructor(_definition) { this._definition = _definition; } accept(visitor) { visitor.visit(this); forEach(this.definition, (prod) => { prod.accept(visitor); }); } } class NonTerminal extends AbstractProduction { constructor(options) { super([]); this.idx = 1; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } set definition(definition) { } get definition() { if (this.referencedRule !== void 0) { return this.referencedRule.definition; } return []; } accept(visitor) { visitor.visit(this); } } class Rule extends AbstractProduction { constructor(options) { super(options.definition); this.orgText = ""; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } } class Alternative extends AbstractProduction { constructor(options) { super(options.definition); this.ignoreAmbiguities = false; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } } class Option extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } } class RepetitionMandatory extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } } class RepetitionMandatoryWithSeparator extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } } class Repetition extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } } class RepetitionWithSeparator extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } } class Alternation extends AbstractProduction { get definition() { return this._definition; } set definition(value) { this._definition = value; } constructor(options) { super(options.definition); this.idx = 1; this.ignoreAmbiguities = false; this.hasPredicates = false; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } } class Terminal { constructor(options) { this.idx = 1; assign$1( this, pickBy(options, (v5) => v5 !== void 0) ); } accept(visitor) { visitor.visit(this); } } function serializeGrammar(topRules) { return map2(topRules, serializeProduction); } function serializeProduction(node) { function convertDefinition(definition) { return map2(definition, serializeProduction); } if (node instanceof NonTerminal) { const serializedNonTerminal = { type: "NonTerminal", name: node.nonTerminalName, idx: node.idx }; if (isString(node.label)) { serializedNonTerminal.label = node.label; } return serializedNonTerminal; } else if (node instanceof Alternative) { return { type: "Alternative", definition: convertDefinition(node.definition) }; } else if (node instanceof Option) { return { type: "Option", idx: node.idx, definition: convertDefinition(node.definition) }; } else if (node instanceof RepetitionMandatory) { return { type: "RepetitionMandatory", idx: node.idx, definition: convertDefinition(node.definition) }; } else if (node instanceof RepetitionMandatoryWithSeparator) { return { type: "RepetitionMandatoryWithSeparator", idx: node.idx, separator: serializeProduction(new Terminal({ terminalType: node.separator })), definition: convertDefinition(node.definition) }; } else if (node instanceof RepetitionWithSeparator) { return { type: "RepetitionWithSeparator", idx: node.idx, separator: serializeProduction(new Terminal({ terminalType: node.separator })), definition: convertDefinition(node.definition) }; } else if (node instanceof Repetition) { return { type: "Repetition", idx: node.idx, definition: convertDefinition(node.definition) }; } else if (node instanceof Alternation) { return { type: "Alternation", idx: node.idx, definition: convertDefinition(node.definition) }; } else if (node instanceof Terminal) { const serializedTerminal = { type: "Terminal", name: node.terminalType.name, label: tokenLabel$1(node.terminalType), idx: node.idx }; if (isString(node.label)) { serializedTerminal.terminalLabel = node.label; } const pattern = node.terminalType.PATTERN; if (node.terminalType.PATTERN) { serializedTerminal.pattern = isRegExp$1(pattern) ? pattern.source : pattern; } return serializedTerminal; } else if (node instanceof Rule) { return { type: "Rule", name: node.name, orgText: node.orgText, definition: convertDefinition(node.definition) }; } else { throw Error("non exhaustive match"); } } class GAstVisitor { visit(node) { const nodeAny = node; switch (nodeAny.constructor) { case NonTerminal: return this.visitNonTerminal(nodeAny); case Alternative: return this.visitAlternative(nodeAny); case Option: return this.visitOption(nodeAny); case RepetitionMandatory: return this.visitRepetitionMandatory(nodeAny); case RepetitionMandatoryWithSeparator: return this.visitRepetitionMandatoryWithSeparator(nodeAny); case RepetitionWithSeparator: return this.visitRepetitionWithSeparator(nodeAny); case Repetition: return this.visitRepetition(nodeAny); case Alternation: return this.visitAlternation(nodeAny); case Terminal: return this.visitTerminal(nodeAny); case Rule: return this.visitRule(nodeAny); default: throw Error("non exhaustive match"); } } /* c8 ignore next */ visitNonTerminal(node) { } /* c8 ignore next */ visitAlternative(node) { } /* c8 ignore next */ visitOption(node) { } /* c8 ignore next */ visitRepetition(node) { } /* c8 ignore next */ visitRepetitionMandatory(node) { } /* c8 ignore next 3 */ visitRepetitionMandatoryWithSeparator(node) { } /* c8 ignore next */ visitRepetitionWithSeparator(node) { } /* c8 ignore next */ visitAlternation(node) { } /* c8 ignore next */ visitTerminal(node) { } /* c8 ignore next */ visitRule(node) { } } function isSequenceProd(prod) { return prod instanceof Alternative || prod instanceof Option || prod instanceof Repetition || prod instanceof RepetitionMandatory || prod instanceof RepetitionMandatoryWithSeparator || prod instanceof RepetitionWithSeparator || prod instanceof Terminal || prod instanceof Rule; } function isOptionalProd(prod, alreadyVisited = []) { const isDirectlyOptional = prod instanceof Option || prod instanceof Repetition || prod instanceof RepetitionWithSeparator; if (isDirectlyOptional) { return true; } if (prod instanceof Alternation) { return some(prod.definition, (subProd) => { return isOptionalProd(subProd, alreadyVisited); }); } else if (prod instanceof NonTerminal && includes(alreadyVisited, prod)) { return false; } else if (prod instanceof AbstractProduction) { if (prod instanceof NonTerminal) { alreadyVisited.push(prod); } return every(prod.definition, (subProd) => { return isOptionalProd(subProd, alreadyVisited); }); } else { return false; } } function isBranchingProd(prod) { return prod instanceof Alternation; } function getProductionDslName(prod) { if (prod instanceof NonTerminal) { return "SUBRULE"; } else if (prod instanceof Option) { return "OPTION"; } else if (prod instanceof Alternation) { return "OR"; } else if (prod instanceof RepetitionMandatory) { return "AT_LEAST_ONE"; } else if (prod instanceof RepetitionMandatoryWithSeparator) { return "AT_LEAST_ONE_SEP"; } else if (prod instanceof RepetitionWithSeparator) { return "MANY_SEP"; } else if (prod instanceof Repetition) { return "MANY"; } else if (prod instanceof Terminal) { return "CONSUME"; } else { throw Error("non exhaustive match"); } } class RestWalker { walk(prod, prevRest = []) { forEach(prod.definition, (subProd, index2) => { const currRest = drop(prod.definition, index2 + 1); if (subProd instanceof NonTerminal) { this.walkProdRef(subProd, currRest, prevRest); } else if (subProd instanceof Terminal) { this.walkTerminal(subProd, currRest, prevRest); } else if (subProd instanceof Alternative) { this.walkFlat(subProd, currRest, prevRest); } else if (subProd instanceof Option) { this.walkOption(subProd, currRest, prevRest); } else if (subProd instanceof RepetitionMandatory) { this.walkAtLeastOne(subProd, currRest, prevRest); } else if (subProd instanceof RepetitionMandatoryWithSeparator) { this.walkAtLeastOneSep(subProd, currRest, prevRest); } else if (subProd instanceof RepetitionWithSeparator) { this.walkManySep(subProd, currRest, prevRest); } else if (subProd instanceof Repetition) { this.walkMany(subProd, currRest, prevRest); } else if (subProd instanceof Alternation) { this.walkOr(subProd, currRest, prevRest); } else { throw Error("non exhaustive match"); } }); } walkTerminal(terminal, currRest, prevRest) { } walkProdRef(refProd, currRest, prevRest) { } walkFlat(flatProd, currRest, prevRest) { const fullOrRest = currRest.concat(prevRest); this.walk(flatProd, fullOrRest); } walkOption(optionProd, currRest, prevRest) { const fullOrRest = currRest.concat(prevRest); this.walk(optionProd, fullOrRest); } walkAtLeastOne(atLeastOneProd, currRest, prevRest) { const fullAtLeastOneRest = [new Option({ definition: atLeastOneProd.definition })].concat(currRest, prevRest); this.walk(atLeastOneProd, fullAtLeastOneRest); } walkAtLeastOneSep(atLeastOneSepProd, currRest, prevRest) { const fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest); this.walk(atLeastOneSepProd, fullAtLeastOneSepRest); } walkMany(manyProd, currRest, prevRest) { const fullManyRest = [new Option({ definition: manyProd.definition })].concat(currRest, prevRest); this.walk(manyProd, fullManyRest); } walkManySep(manySepProd, currRest, prevRest) { const fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest); this.walk(manySepProd, fullManySepRest); } walkOr(orProd, currRest, prevRest) { const fullOrRest = currRest.concat(prevRest); forEach(orProd.definition, (alt) => { const prodWrapper = new Alternative({ definition: [alt] }); this.walk(prodWrapper, fullOrRest); }); } } function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) { const repSepRest = [ new Option({ definition: [new Terminal({ terminalType: repSepProd.separator })].concat(repSepProd.definition) }) ]; const fullRepSepRest = repSepRest.concat(currRest, prevRest); return fullRepSepRest; } function first2(prod) { if (prod instanceof NonTerminal) { return first2(prod.referencedRule); } else if (prod instanceof Terminal) { return firstForTerminal(prod); } else if (isSequenceProd(prod)) { return firstForSequence(prod); } else if (isBranchingProd(prod)) { return firstForBranching(prod); } else { throw Error("non exhaustive match"); } } function firstForSequence(prod) { let firstSet = []; const seq = prod.definition; let nextSubProdIdx = 0; let hasInnerProdsRemaining = seq.length > nextSubProdIdx; let currSubProd; let isLastInnerProdOptional = true; while (hasInnerProdsRemaining && isLastInnerProdOptional) { currSubProd = seq[nextSubProdIdx]; isLastInnerProdOptional = isOptionalProd(currSubProd); firstSet = firstSet.concat(first2(currSubProd)); nextSubProdIdx = nextSubProdIdx + 1; hasInnerProdsRemaining = seq.length > nextSubProdIdx; } return uniq(firstSet); } function firstForBranching(prod) { const allAlternativesFirsts = map2(prod.definition, (innerProd) => { return first2(innerProd); }); return uniq(flatten(allAlternativesFirsts)); } function firstForTerminal(terminal) { return [terminal.terminalType]; } const IN = "_~IN~_"; class ResyncFollowsWalker extends RestWalker { constructor(topProd) { super(); this.topProd = topProd; this.follows = {}; } startWalking() { this.walk(this.topProd); return this.follows; } walkTerminal(terminal, currRest, prevRest) { } walkProdRef(refProd, currRest, prevRest) { const followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) + this.topProd.name; const fullRest = currRest.concat(prevRest); const restProd = new Alternative({ definition: fullRest }); const t_in_topProd_follows = first2(restProd); this.follows[followName] = t_in_topProd_follows; } } function computeAllProdsFollows(topProductions) { const reSyncFollows = {}; forEach(topProductions, (topProd) => { const currRefsFollow = new ResyncFollowsWalker(topProd).startWalking(); assign$1(reSyncFollows, currRefsFollow); }); return reSyncFollows; } function buildBetweenProdsFollowPrefix(inner, occurenceInParent) { return inner.name + occurenceInParent + IN; } function cc(char) { return char.charCodeAt(0); } function insertToSet(item, set) { if (Array.isArray(item)) { item.forEach(function(subItem) { set.push(subItem); }); } else { set.push(item); } } function addFlag(flagObj, flagKey) { if (flagObj[flagKey] === true) { throw "duplicate flag " + flagKey; } flagObj[flagKey]; flagObj[flagKey] = true; } function ASSERT_EXISTS(obj) { if (obj === void 0) { throw Error("Internal Error - Should never get here!"); } return true; } function ASSERT_NEVER_REACH_HERE() { throw Error("Internal Error - Should never get here!"); } function isCharacter(obj) { return obj["type"] === "Character"; } const digitsCharCodes = []; for (let i4 = cc("0"); i4 <= cc("9"); i4++) { digitsCharCodes.push(i4); } const wordCharCodes = [cc("_")].concat(digitsCharCodes); for (let i4 = cc("a"); i4 <= cc("z"); i4++) { wordCharCodes.push(i4); } for (let i4 = cc("A"); i4 <= cc("Z"); i4++) { wordCharCodes.push(i4); } const whitespaceCodes = [ cc(" "), cc("\f"), cc("\n"), cc("\r"), cc(" "), cc("\v"), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc("\u2028"), cc("\u2029"), cc(" "), cc(" "), cc(" "), cc("\uFEFF") ]; const hexDigitPattern = /[0-9a-fA-F]/; const decimalPattern = /[0-9]/; const decimalPatternNoZero = /[1-9]/; class RegExpParser { constructor() { this.idx = 0; this.input = ""; this.groupIdx = 0; } saveState() { return { idx: this.idx, input: this.input, groupIdx: this.groupIdx }; } restoreState(newState) { this.idx = newState.idx; this.input = newState.input; this.groupIdx = newState.groupIdx; } pattern(input) { this.idx = 0; this.input = input; this.groupIdx = 0; this.consumeChar("/"); const value = this.disjunction(); this.consumeChar("/"); const flags = { type: "Flags", loc: { begin: this.idx, end: input.length }, global: false, ignoreCase: false, multiLine: false, unicode: false, sticky: false }; while (this.isRegExpFlag()) { switch (this.popChar()) { case "g": addFlag(flags, "global"); break; case "i": addFlag(flags, "ignoreCase"); break; case "m": addFlag(flags, "multiLine"); break; case "u": addFlag(flags, "unicode"); break; case "y": addFlag(flags, "sticky"); break; } } if (this.idx !== this.input.length) { throw Error("Redundant input: " + this.input.substring(this.idx)); } return { type: "Pattern", flags, value, loc: this.loc(0) }; } disjunction() { const alts = []; const begin = this.idx; alts.push(this.alternative()); while (this.peekChar() === "|") { this.consumeChar("|"); alts.push(this.alternative()); } return { type: "Disjunction", value: alts, loc: this.loc(begin) }; } alternative() { const terms = []; const begin = this.idx; while (this.isTerm()) { terms.push(this.term()); } return { type: "Alternative", value: terms, loc: this.loc(begin) }; } term() { if (this.isAssertion()) { return this.assertion(); } else { return this.atom(); } } assertion() { const begin = this.idx; switch (this.popChar()) { case "^": return { type: "StartAnchor", loc: this.loc(begin) }; case "$": return { type: "EndAnchor", loc: this.loc(begin) }; case "\\": switch (this.popChar()) { case "b": return { type: "WordBoundary", loc: this.loc(begin) }; case "B": return { type: "NonWordBoundary", loc: this.loc(begin) }; } throw Error("Invalid Assertion Escape"); case "(": this.consumeChar("?"); let type; switch (this.popChar()) { case "=": type = "Lookahead"; break; case "!": type = "NegativeLookahead"; break; } ASSERT_EXISTS(type); const disjunction = this.disjunction(); this.consumeChar(")"); return { type, value: disjunction, loc: this.loc(begin) }; } return ASSERT_NEVER_REACH_HERE(); } quantifier(isBacktracking = false) { let range = void 0; const begin = this.idx; switch (this.popChar()) { case "*": range = { atLeast: 0, atMost: Infinity }; break; case "+": range = { atLeast: 1, atMost: Infinity }; break; case "?": range = { atLeast: 0, atMost: 1 }; break; case "{": const atLeast = this.integerIncludingZero(); switch (this.popChar()) { case "}": range = { atLeast, atMost: atLeast }; break; case ",": let atMost; if (this.isDigit()) { atMost = this.integerIncludingZero(); range = { atLeast, atMost }; } else { range = { atLeast, atMost: Infinity }; } this.consumeChar("}"); break; } if (isBacktracking === true && range === void 0) { return void 0; } ASSERT_EXISTS(range); break; } if (isBacktracking === true && range === void 0) { return void 0; } if (ASSERT_EXISTS(range)) { if (this.peekChar(0) === "?") { this.consumeChar("?"); range.greedy = false; } else { range.greedy = true; } range.type = "Quantifier"; range.loc = this.loc(begin); return range; } } atom() { let atom; const begin = this.idx; switch (this.peekChar()) { case ".": atom = this.dotAll(); break; case "\\": atom = this.atomEscape(); break; case "[": atom = this.characterClass(); break; case "(": atom = this.group(); break; } if (atom === void 0 && this.isPatternCharacter()) { atom = this.patternCharacter(); } if (ASSERT_EXISTS(atom)) { atom.loc = this.loc(begin); if (this.isQuantifier()) { atom.quantifier = this.quantifier(); } return atom; } } dotAll() { this.consumeChar("."); return { type: "Set", complement: true, value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")] }; } atomEscape() { this.consumeChar("\\"); switch (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(); } } decimalEscapeAtom() { const value = this.positiveInteger(); return { type: "GroupBackReference", value }; } characterClassEscape() { let set; let complement = false; switch (this.popChar()) { case "d": set = digitsCharCodes; break; case "D": set = digitsCharCodes; complement = true; break; case "s": set = whitespaceCodes; break; case "S": set = whitespaceCodes; complement = true; break; case "w": set = wordCharCodes; break; case "W": set = wordCharCodes; complement = true; break; } if (ASSERT_EXISTS(set)) { return { type: "Set", value: set, complement }; } } controlEscapeAtom() { let escapeCode; switch (this.popChar()) { case "f": escapeCode = cc("\f"); break; case "n": escapeCode = cc("\n"); break; case "r": escapeCode = cc("\r"); break; case "t": escapeCode = cc(" "); break; case "v": escapeCode = cc("\v"); break; } if (ASSERT_EXISTS(escapeCode)) { return { type: "Character", value: escapeCode }; } } controlLetterEscapeAtom() { this.consumeChar("c"); const letter = this.popChar(); if (/[a-zA-Z]/.test(letter) === false) { throw Error("Invalid "); } const letterCode = letter.toUpperCase().charCodeAt(0) - 64; return { type: "Character", value: letterCode }; } nulCharacterAtom() { this.consumeChar("0"); return { type: "Character", value: cc("\0") }; } hexEscapeSequenceAtom() { this.consumeChar("x"); return this.parseHexDigits(2); } regExpUnicodeEscapeSequenceAtom() { this.consumeChar("u"); return this.parseHexDigits(4); } identityEscapeAtom() { const escapedChar = this.popChar(); return { type: "Character", value: cc(escapedChar) }; } classPatternCharacterAtom() { switch (this.peekChar()) { case "\n": case "\r": case "\u2028": case "\u2029": case "\\": case "]": throw Error("TBD"); default: const nextChar = this.popChar(); return { type: "Character", value: cc(nextChar) }; } } characterClass() { const set = []; let complement = false; this.consumeChar("["); if (this.peekChar(0) === "^") { this.consumeChar("^"); complement = true; } while (this.isClassAtom()) { const from = this.classAtom(); from.type === "Character"; if (isCharacter(from) && this.isRangeDash()) { this.consumeChar("-"); const to = this.classAtom(); to.type === "Character"; if (isCharacter(to)) { if (to.value < from.value) { throw Error("Range out of order in character class"); } set.push({ from: from.value, to: to.value }); } else { insertToSet(from.value, set); set.push(cc("-")); insertToSet(to.value, set); } } else { insertToSet(from.value, set); } } this.consumeChar("]"); return { type: "Set", complement, value: set }; } classAtom() { switch (this.peekChar()) { case "]": case "\n": case "\r": case "\u2028": case "\u2029": throw Error("TBD"); case "\\": return this.classEscape(); default: return this.classPatternCharacterAtom(); } } classEscape() { this.consumeChar("\\"); switch (this.peekChar()) { case "b": this.consumeChar("b"); return { type: "Character", value: cc("\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(); } } group() { let capturing = true; this.consumeChar("("); switch (this.peekChar(0)) { case "?": this.consumeChar("?"); this.consumeChar(":"); capturing = false; break; default: this.groupIdx++; break; } const value = this.disjunction(); this.consumeChar(")"); const groupAst = { type: "Group", capturing, value }; if (capturing) { groupAst["idx"] = this.groupIdx; } return groupAst; } positiveInteger() { let number = this.popChar(); if (decimalPatternNoZero.test(number) === false) { throw Error("Expecting a positive integer"); } while (decimalPattern.test(this.peekChar(0))) { number += this.popChar(); } return parseInt(number, 10); } integerIncludingZero() { let number = this.popChar(); if (decimalPattern.test(number) === false) { throw Error("Expecting an integer"); } while (decimalPattern.test(this.peekChar(0))) { number += this.popChar(); } return parseInt(number, 10); } patternCharacter() { const nextChar = this.popChar(); switch (nextChar) { case "\n": 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: cc(nextChar) }; } } isRegExpFlag() { switch (this.peekChar(0)) { case "g": case "i": case "m": case "u": case "y": return true; default: return false; } } isRangeDash() { return this.peekChar() === "-" && this.isClassAtom(1); } isDigit() { return decimalPattern.test(this.peekChar(0)); } isClassAtom(howMuch = 0) { switch (this.peekChar(howMuch)) { case "]": case "\n": case "\r": case "\u2028": case "\u2029": return false; default: return true; } } isTerm() { return this.isAtom() || this.isAssertion(); } isAtom() { if (this.isPatternCharacter()) { return true; } switch (this.peekChar(0)) { case ".": case "\\": case "[": case "(": return true; default: return false; } } isAssertion() { 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; } } isQuantifier() { const prevState = this.saveState(); try { return this.quantifier(true) !== void 0; } catch (e2) { return false; } finally { this.restoreState(prevState); } } isPatternCharacter() { switch (this.peekChar()) { case "^": case "$": case "\\": case ".": case "*": case "+": case "?": case "(": case ")": case "[": case "|": case "/": case "\n": case "\r": case "\u2028": case "\u2029": return false; default: return true; } } parseHexDigits(howMany) { let hexString = ""; for (let i4 = 0; i4 < howMany; i4++) { const hexChar = this.popChar(); if (hexDigitPattern.test(hexChar) === false) { throw Error("Expecting a HexDecimal digits"); } hexString += hexChar; } const charCode = parseInt(hexString, 16); return { type: "Character", value: charCode }; } peekChar(howMuch = 0) { return this.input[this.idx + howMuch]; } popChar() { const nextChar = this.peekChar(0); this.consumeChar(void 0); return nextChar; } consumeChar(char) { if (char !== void 0 && this.input[this.idx] !== char) { throw Error("Expected: '" + char + "' but found: '" + this.input[this.idx] + "' at offset: " + this.idx); } if (this.idx >= this.input.length) { throw Error("Unexpected end of input"); } this.idx++; } loc(begin) { return { begin, end: this.idx }; } } class BaseRegExpVisitor { visitChildren(node) { for (const key in node) { const child = node[key]; if (node.hasOwnProperty(key)) { if (child.type !== void 0) { this.visit(child); } else if (Array.isArray(child)) { child.forEach((subChild) => { this.visit(subChild); }, this); } } } } visit(node) { switch (node.type) { case "Pattern": this.visitPattern(node); break; case "Flags": this.visitFlags(node); break; case "Disjunction": this.visitDisjunction(node); break; case "Alternative": this.visitAlternative(node); break; case "StartAnchor": this.visitStartAnchor(node); break; case "EndAnchor": this.visitEndAnchor(node); break; case "WordBoundary": this.visitWordBoundary(node); break; case "NonWordBoundary": this.visitNonWordBoundary(node); break; case "Lookahead": this.visitLookahead(node); break; case "NegativeLookahead": this.visitNegativeLookahead(node); break; case "Character": this.visitCharacter(node); break; case "Set": this.visitSet(node); break; case "Group": this.visitGroup(node); break; case "GroupBackReference": this.visitGroupBackReference(node); break; case "Quantifier": this.visitQuantifier(node); break; } this.visitChildren(node); } visitPattern(node) { } visitFlags(node) { } visitDisjunction(node) { } visitAlternative(node) { } // Assertion visitStartAnchor(node) { } visitEndAnchor(node) { } visitWordBoundary(node) { } visitNonWordBoundary(node) { } visitLookahead(node) { } visitNegativeLookahead(node) { } // atoms visitCharacter(node) { } visitSet(node) { } visitGroup(node) { } visitGroupBackReference(node) { } visitQuantifier(node) { } } let regExpAstCache = {}; const regExpParser = new RegExpParser(); function getRegExpAst(regExp) { const regExpStr = regExp.toString(); if (regExpAstCache.hasOwnProperty(regExpStr)) { return regExpAstCache[regExpStr]; } else { const regExpAst = regExpParser.pattern(regExpStr); regExpAstCache[regExpStr] = regExpAst; return regExpAst; } } function clearRegExpParserCache() { regExpAstCache = {}; } const complementErrorMessage = "Complement Sets are not supported for first char optimization"; const failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n'; function getOptimizedStartCodesIndices(regExp, ensureOptimizations = false) { try { const ast = getRegExpAst(regExp); const firstChars = firstCharOptimizedIndices(ast.value, {}, ast.flags.ignoreCase); return firstChars; } catch (e2) { if (e2.message === complementErrorMessage) { if (ensureOptimizations) { PRINT_WARNING( `${failedOptimizationPrefixMsg} Unable to optimize: < ${regExp.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 { let msgSuffix = ""; if (ensureOptimizations) { msgSuffix = "\n This will disable the lexer's first char optimizations.\n See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details."; } PRINT_ERROR( `${failedOptimizationPrefixMsg} Failed parsing: < ${regExp.toString()} > Using the @chevrotain/regexp-to-ast library Please open an issue at: https://github.com/chevrotain/chevrotain/issues` + msgSuffix ); } } return []; } function firstCharOptimizedIndices(ast, result, ignoreCase) { switch (ast.type) { case "Disjunction": for (let i4 = 0; i4 < ast.value.length; i4++) { firstCharOptimizedIndices(ast.value[i4], result, ignoreCase); } break; case "Alternative": const terms = ast.value; for (let i4 = 0; i4 < terms.length; i4++) { const term = terms[i4]; switch (term.type) { case "EndAnchor": case "GroupBackReference": case "Lookahead": case "NegativeLookahead": case "StartAnchor": case "WordBoundary": case "NonWordBoundary": continue; } const atom = term; switch (atom.type) { case "Character": addOptimizedIdxToResult(atom.value, result, ignoreCase); break; case "Set": if (atom.complement === true) { throw Error(complementErrorMessage); } forEach(atom.value, (code) => { if (typeof code === "number") { addOptimizedIdxToResult(code, result, ignoreCase); } else { const range = code; if (ignoreCase === true) { for (let rangeCode = range.from; rangeCode <= range.to; rangeCode++) { addOptimizedIdxToResult(rangeCode, result, ignoreCase); } } else { for (let rangeCode = range.from; rangeCode <= range.to && rangeCode < minOptimizationVal; rangeCode++) { addOptimizedIdxToResult(rangeCode, result, ignoreCase); } if (range.to >= minOptimizationVal) { const minUnOptVal = range.from >= minOptimizationVal ? range.from : minOptimizationVal; const maxUnOptVal = range.to; const minOptIdx = charCodeToOptimizedIndex(minUnOptVal); const maxOptIdx = charCodeToOptimizedIndex(maxUnOptVal); for (let currOptIdx = minOptIdx; currOptIdx <= maxOptIdx; currOptIdx++) { result[currOptIdx] = currOptIdx; } } } } }); break; case "Group": firstCharOptimizedIndices(atom.value, result, ignoreCase); break; default: throw Error("Non Exhaustive Match"); } const isOptionalQuantifier = atom.quantifier !== void 0 && atom.quantifier.atLeast === 0; if ( // A group may be optional due to empty contents /(?:)/ // or if everything inside it is optional /((a)?)/ atom.type === "Group" && isWholeOptional(atom) === false || // If this term is not a group it may only be optional if it has an optional quantifier atom.type !== "Group" && isOptionalQuantifier === false ) { break; } } break; default: throw Error("non exhaustive match!"); } return values(result); } function addOptimizedIdxToResult(code, result, ignoreCase) { const optimizedCharIdx = charCodeToOptimizedIndex(code); result[optimizedCharIdx] = optimizedCharIdx; if (ignoreCase === true) { handleIgnoreCase(code, result); } } function handleIgnoreCase(code, result) { const char = String.fromCharCode(code); const upperChar = char.toUpperCase(); if (upperChar !== char) { const optimizedCharIdx = charCodeToOptimizedIndex(upperChar.charCodeAt(0)); result[optimizedCharIdx] = optimizedCharIdx; } else { const lowerChar = char.toLowerCase(); if (lowerChar !== char) { const optimizedCharIdx = charCodeToOptimizedIndex(lowerChar.charCodeAt(0)); result[optimizedCharIdx] = optimizedCharIdx; } } } function findCode(setNode, targetCharCodes) { return find$1(setNode.value, (codeOrRange) => { if (typeof codeOrRange === "number") { return includes(targetCharCodes, codeOrRange); } else { const range = codeOrRange; return find$1(targetCharCodes, (targetCode) => range.from <= targetCode && targetCode <= range.to) !== void 0; } }); } function isWholeOptional(ast) { const quantifier = ast.quantifier; if (quantifier && quantifier.atLeast === 0) { return true; } if (!ast.value) { return false; } return isArray$1(ast.value) ? every(ast.value, isWholeOptional) : isWholeOptional(ast.value); } class CharCodeFinder extends BaseRegExpVisitor { constructor(targetCharCodes) { super(); this.targetCharCodes = targetCharCodes; this.found = false; } visitChildren(node) { if (this.found === true) { return; } switch (node.type) { case "Lookahead": this.visitLookahead(node); return; case "NegativeLookahead": this.visitNegativeLookahead(node); return; } super.visitChildren(node); } visitCharacter(node) { if (includes(this.targetCharCodes, node.value)) { this.found = true; } } visitSet(node) { if (node.complement) { if (findCode(node, this.targetCharCodes) === void 0) { this.found = true; } } else { if (findCode(node, this.targetCharCodes) !== void 0) { this.found = true; } } } } function canMatchCharCode(charCodes, pattern) { if (pattern instanceof RegExp) { const ast = getRegExpAst(pattern); const charCodeFinder = new CharCodeFinder(charCodes); charCodeFinder.visit(ast); return charCodeFinder.found; } else { return find$1(pattern, (char) => { return includes(charCodes, char.charCodeAt(0)); }) !== void 0; } } const PATTERN = "PATTERN"; const DEFAULT_MODE = "defaultMode"; const MODES = "modes"; let SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean"; function analyzeTokenTypes(tokenTypes, options) { options = defaults$1(options, { useSticky: SUPPORT_STICKY, debug: false, safeMode: false, positionTracking: "full", lineTerminatorCharacters: ["\r", "\n"], tracer: (msg, action) => action() }); const tracer = options.tracer; tracer("initCharCodeToOptimizedIndexMap", () => { initCharCodeToOptimizedIndexMap(); }); let onlyRelevantTypes; tracer("Reject Lexer.NA", () => { onlyRelevantTypes = reject(tokenTypes, (currType) => { return currType[PATTERN] === Lexer2.NA; }); }); let hasCustom = false; let allTransformedPatterns; tracer("Transform Patterns", () => { hasCustom = false; allTransformedPatterns = map2(onlyRelevantTypes, (currType) => { const currPattern = currType[PATTERN]; if (isRegExp$1(currPattern)) { const regExpSource = currPattern.source; if (regExpSource.length === 1 && // only these regExp meta characters which can appear in a length one regExp regExpSource !== "^" && regExpSource !== "$" && regExpSource !== "." && !currPattern.ignoreCase) { return regExpSource; } else if (regExpSource.length === 2 && regExpSource[0] === "\\" && // not a meta character !includes(["d", "D", "s", "S", "t", "r", "n", "t", "0", "c", "b", "B", "f", "v", "w", "W"], regExpSource[1])) { return regExpSource[1]; } else { return options.useSticky ? addStickyFlag(currPattern) : addStartOfInput(currPattern); } } else if (isFunction3(currPattern)) { hasCustom = true; return { exec: currPattern }; } else if (typeof currPattern === "object") { hasCustom = true; return currPattern; } else if (typeof currPattern === "string") { if (currPattern.length === 1) { return currPattern; } else { const escapedRegExpString = currPattern.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); const wrappedRegExp = new RegExp(escapedRegExpString); return options.useSticky ? addStickyFlag(wrappedRegExp) : addStartOfInput(wrappedRegExp); } } else { throw Error("non exhaustive match"); } }); }); let patternIdxToType; let patternIdxToGroup; let patternIdxToLongerAltIdxArr; let patternIdxToPushMode; let patternIdxToPopMode; tracer("misc mapping", () => { patternIdxToType = map2(onlyRelevantTypes, (currType) => currType.tokenTypeIdx); patternIdxToGroup = map2(onlyRelevantTypes, (clazz) => { const groupName = clazz.GROUP; if (groupName === Lexer2.SKIPPED) { return void 0; } else if (isString(groupName)) { return groupName; } else if (isUndefined(groupName)) { return false; } else { throw Error("non exhaustive match"); } }); patternIdxToLongerAltIdxArr = map2(onlyRelevantTypes, (clazz) => { const longerAltType = clazz.LONGER_ALT; if (longerAltType) { const longerAltIdxArr = isArray$1(longerAltType) ? map2(longerAltType, (type) => indexOf(onlyRelevantTypes, type)) : [indexOf(onlyRelevantTypes, longerAltType)]; return longerAltIdxArr; } }); patternIdxToPushMode = map2(onlyRelevantTypes, (clazz) => clazz.PUSH_MODE); patternIdxToPopMode = map2(onlyRelevantTypes, (clazz) => has(clazz, "POP_MODE")); }); let patternIdxToCanLineTerminator; tracer("Line Terminator Handling", () => { const lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters); patternIdxToCanLineTerminator = map2(onlyRelevantTypes, (tokType) => false); if (options.positionTracking !== "onlyOffset") { patternIdxToCanLineTerminator = map2(onlyRelevantTypes, (tokType) => { if (has(tokType, "LINE_BREAKS")) { return !!tokType.LINE_BREAKS; } else { return checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false && canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN); } }); } }); let patternIdxToIsCustom; let patternIdxToShort; let emptyGroups; let patternIdxToConfig; tracer("Misc Mapping #2", () => { patternIdxToIsCustom = map2(onlyRelevantTypes, isCustomPattern); patternIdxToShort = map2(allTransformedPatterns, isShortPattern); emptyGroups = reduce2( onlyRelevantTypes, (acc, clazz) => { const groupName = clazz.GROUP; if (isString(groupName) && !(groupName === Lexer2.SKIPPED)) { acc[groupName] = []; } return acc; }, {} ); patternIdxToConfig = map2(allTransformedPatterns, (x, idx) => { return { pattern: allTransformedPatterns[idx], longerAlt: patternIdxToLongerAltIdxArr[idx], canLineTerminator: patternIdxToCanLineTerminator[idx], isCustom: patternIdxToIsCustom[idx], short: patternIdxToShort[idx], group: patternIdxToGroup[idx], push: patternIdxToPushMode[idx], pop: patternIdxToPopMode[idx], tokenTypeIdx: patternIdxToType[idx], tokenType: onlyRelevantTypes[idx] }; }); }); let canBeOptimized = true; let charCodeToPatternIdxToConfig = []; if (!options.safeMode) { tracer("First Char Optimization", () => { charCodeToPatternIdxToConfig = reduce2( onlyRelevantTypes, (result, currTokType, idx) => { if (typeof currTokType.PATTERN === "string") { const charCode = currTokType.PATTERN.charCodeAt(0); const optimizedIdx = charCodeToOptimizedIndex(charCode); addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]); } else if (isArray$1(currTokType.START_CHARS_HINT)) { let lastOptimizedIdx; forEach(currTokType.START_CHARS_HINT, (charOrInt) => { const charCode = typeof charOrInt === "string" ? charOrInt.charCodeAt(0) : charOrInt; const currOptimizedIdx = charCodeToOptimizedIndex(charCode); if (lastOptimizedIdx !== currOptimizedIdx) { lastOptimizedIdx = currOptimizedIdx; addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]); } }); } else if (isRegExp$1(currTokType.PATTERN)) { if (currTokType.PATTERN.unicode) { canBeOptimized = false; if (options.ensureOptimizations) { PRINT_ERROR( `${failedOptimizationPrefixMsg} Unable to analyze < ${currTokType.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 { const optimizedCodes = getOptimizedStartCodesIndices(currTokType.PATTERN, options.ensureOptimizations); if (isEmpty(optimizedCodes)) { canBeOptimized = false; } forEach(optimizedCodes, (code) => { addToMapOfArrays(result, code, patternIdxToConfig[idx]); }); } } else { if (options.ensureOptimizations) { PRINT_ERROR( `${failedOptimizationPrefixMsg} TokenType: <${currTokType.name}> is using a custom token pattern without providing parameter. This will disable the lexer's first char optimizations. For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE` ); } canBeOptimized = false; } return result; }, [] ); }); } return { emptyGroups, patternIdxToConfig, charCodeToPatternIdxToConfig, hasCustom, canBeOptimized }; } function validatePatterns(tokenTypes, validModesNames) { let errors = []; const missingResult = findMissingPatterns(tokenTypes); errors = errors.concat(missingResult.errors); const invalidResult = findInvalidPatterns(missingResult.valid); const validTokenTypes = invalidResult.valid; errors = errors.concat(invalidResult.errors); errors = errors.concat(validateRegExpPattern(validTokenTypes)); errors = errors.concat(findInvalidGroupType(validTokenTypes)); errors = errors.concat(findModesThatDoNotExist(validTokenTypes, validModesNames)); errors = errors.concat(findUnreachablePatterns(validTokenTypes)); return errors; } function validateRegExpPattern(tokenTypes) { let errors = []; const withRegExpPatterns = filter(tokenTypes, (currTokType) => isRegExp$1(currTokType[PATTERN])); errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns)); errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns)); errors = errors.concat(findUnsupportedFlags(withRegExpPatterns)); errors = errors.concat(findDuplicatePatterns(withRegExpPatterns)); errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns)); return errors; } function findMissingPatterns(tokenTypes) { const tokenTypesWithMissingPattern = filter(tokenTypes, (currType) => { return !has(currType, PATTERN); }); const errors = map2(tokenTypesWithMissingPattern, (currType) => { return { message: "Token Type: ->" + currType.name + "<- missing static 'PATTERN' property", type: LexerDefinitionErrorType.MISSING_PATTERN, tokenTypes: [currType] }; }); const valid = difference$1(tokenTypes, tokenTypesWithMissingPattern); return { errors, valid }; } function findInvalidPatterns(tokenTypes) { const tokenTypesWithInvalidPattern = filter(tokenTypes, (currType) => { const pattern = currType[PATTERN]; return !isRegExp$1(pattern) && !isFunction3(pattern) && !has(pattern, "exec") && !isString(pattern); }); const errors = map2(tokenTypesWithInvalidPattern, (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", type: LexerDefinitionErrorType.INVALID_PATTERN, tokenTypes: [currType] }; }); const valid = difference$1(tokenTypes, tokenTypesWithInvalidPattern); return { errors, valid }; } const end_of_input = /[^\\][$]/; function findEndOfInputAnchor(tokenTypes) { class EndAnchorFinder extends BaseRegExpVisitor { constructor() { super(...arguments); this.found = false; } visitEndAnchor(node) { this.found = true; } } const invalidRegex = filter(tokenTypes, (currType) => { const pattern = currType.PATTERN; try { const regexpAst = getRegExpAst(pattern); const endAnchorVisitor = new EndAnchorFinder(); endAnchorVisitor.visit(regexpAst); return endAnchorVisitor.found; } catch (e2) { return end_of_input.test(pattern.source); } }); const errors = map2(invalidRegex, (currType) => { return { message: "Unexpected RegExp Anchor Error:\n Token Type: ->" + currType.name + "<- static 'PATTERN' cannot contain end of input anchor '$'\n See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.", type: LexerDefinitionErrorType.EOI_ANCHOR_FOUND, tokenTypes: [currType] }; }); return errors; } function findEmptyMatchRegExps(tokenTypes) { const matchesEmptyString = filter(tokenTypes, (currType) => { const pattern = currType.PATTERN; return pattern.test(""); }); const errors = map2(matchesEmptyString, (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' must not match an empty string", type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, tokenTypes: [currType] }; }); return errors; } const start_of_input = /[^\\[][\^]|^\^/; function findStartOfInputAnchor(tokenTypes) { class StartAnchorFinder extends BaseRegExpVisitor { constructor() { super(...arguments); this.found = false; } visitStartAnchor(node) { this.found = true; } } const invalidRegex = filter(tokenTypes, (currType) => { const pattern = currType.PATTERN; try { const regexpAst = getRegExpAst(pattern); const startAnchorVisitor = new StartAnchorFinder(); startAnchorVisitor.visit(regexpAst); return startAnchorVisitor.found; } catch (e2) { return start_of_input.test(pattern.source); } }); const errors = map2(invalidRegex, (currType) => { return { message: "Unexpected RegExp Anchor Error:\n Token Type: ->" + currType.name + "<- static 'PATTERN' cannot contain start of input anchor '^'\n See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.", type: LexerDefinitionErrorType.SOI_ANCHOR_FOUND, tokenTypes: [currType] }; }); return errors; } function findUnsupportedFlags(tokenTypes) { const invalidFlags = filter(tokenTypes, (currType) => { const pattern = currType[PATTERN]; return pattern instanceof RegExp && (pattern.multiline || pattern.global); }); const errors = map2(invalidFlags, (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", type: LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, tokenTypes: [currType] }; }); return errors; } function findDuplicatePatterns(tokenTypes) { const found = []; let identicalPatterns = map2(tokenTypes, (outerType) => { return reduce2( tokenTypes, (result, innerType) => { if (outerType.PATTERN.source === innerType.PATTERN.source && !includes(found, innerType) && innerType.PATTERN !== Lexer2.NA) { found.push(innerType); result.push(innerType); return result; } return result; }, [] ); }); identicalPatterns = compact(identicalPatterns); const duplicatePatterns = filter(identicalPatterns, (currIdenticalSet) => { return currIdenticalSet.length > 1; }); const errors = map2(duplicatePatterns, (setOfIdentical) => { const tokenTypeNames = map2(setOfIdentical, (currType) => { return currType.name; }); const dupPatternSrc = head(setOfIdentical).PATTERN; return { message: `The same RegExp pattern ->${dupPatternSrc}<-has been used in all of the following Token Types: ${tokenTypeNames.join(", ")} <-`, type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, tokenTypes: setOfIdentical }; }); return errors; } function findInvalidGroupType(tokenTypes) { const invalidTypes = filter(tokenTypes, (clazz) => { if (!has(clazz, "GROUP")) { return false; } const group = clazz.GROUP; return group !== Lexer2.SKIPPED && group !== Lexer2.NA && !isString(group); }); const errors = map2(invalidTypes, (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", type: LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, tokenTypes: [currType] }; }); return errors; } function findModesThatDoNotExist(tokenTypes, validModes) { const invalidModes = filter(tokenTypes, (clazz) => { return clazz.PUSH_MODE !== void 0 && !includes(validModes, clazz.PUSH_MODE); }); const errors = map2(invalidModes, (tokType) => { const msg = `Token Type: ->${tokType.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${tokType.PUSH_MODE}<-which does not exist`; return { message: msg, type: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, tokenTypes: [tokType] }; }); return errors; } function findUnreachablePatterns(tokenTypes) { const errors = []; const canBeTested = reduce2( tokenTypes, (result, tokType, idx) => { const pattern = tokType.PATTERN; if (pattern === Lexer2.NA) { return result; } if (isString(pattern)) { result.push({ str: pattern, idx, tokenType: tokType }); } else if (isRegExp$1(pattern) && noMetaChar(pattern)) { result.push({ str: pattern.source, idx, tokenType: tokType }); } return result; }, [] ); forEach(tokenTypes, (tokType, testIdx) => { forEach(canBeTested, ({ str, idx, tokenType }) => { if (testIdx < idx && testTokenType(str, tokType.PATTERN)) { const msg = `Token: ->${tokenType.name}<- can never be matched. Because it appears AFTER the Token Type ->${tokType.name}<-in the lexer's definition. See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`; errors.push({ message: msg, type: LexerDefinitionErrorType.UNREACHABLE_PATTERN, tokenTypes: [tokType, tokenType] }); } }); }); return errors; } function testTokenType(str, pattern) { if (isRegExp$1(pattern)) { const regExpArray = pattern.exec(str); return regExpArray !== null && regExpArray.index === 0; } else if (isFunction3(pattern)) { return pattern(str, 0, [], {}); } else if (has(pattern, "exec")) { return pattern.exec(str, 0, [], {}); } else if (typeof pattern === "string") { return pattern === str; } else { throw Error("non exhaustive match"); } } function noMetaChar(regExp) { const metaChars = [".", "\\", "[", "]", "|", "^", "$", "(", ")", "?", "*", "+", "{"]; return find$1(metaChars, (char) => regExp.source.indexOf(char) !== -1) === void 0; } function addStartOfInput(pattern) { const flags = pattern.ignoreCase ? "i" : ""; return new RegExp(`^(?:${pattern.source})`, flags); } function addStickyFlag(pattern) { const flags = pattern.ignoreCase ? "iy" : "y"; return new RegExp(`${pattern.source}`, flags); } function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { const errors = []; if (!has(lexerDefinition, DEFAULT_MODE)) { errors.push({ message: "A MultiMode Lexer cannot be initialized without a <" + DEFAULT_MODE + "> property in its definition\n", type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE }); } if (!has(lexerDefinition, MODES)) { errors.push({ message: "A MultiMode Lexer cannot be initialized without a <" + MODES + "> property in its definition\n", type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY }); } if (has(lexerDefinition, MODES) && has(lexerDefinition, DEFAULT_MODE) && !has(lexerDefinition.modes, lexerDefinition.defaultMode)) { errors.push({ message: `A MultiMode Lexer cannot be initialized with a ${DEFAULT_MODE}: <${lexerDefinition.defaultMode}>which does not exist `, type: LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST }); } if (has(lexerDefinition, MODES)) { forEach(lexerDefinition.modes, (currModeValue, currModeName) => { forEach(currModeValue, (currTokType, currIdx) => { if (isUndefined(currTokType)) { errors.push({ message: `A Lexer cannot be initialized using an undefined Token Type. Mode:<${currModeName}> at index: <${currIdx}> `, type: LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED }); } else if (has(currTokType, "LONGER_ALT")) { const longerAlt = isArray$1(currTokType.LONGER_ALT) ? currTokType.LONGER_ALT : [currTokType.LONGER_ALT]; forEach(longerAlt, (currLongerAlt) => { if (!isUndefined(currLongerAlt) && !includes(currModeValue, currLongerAlt)) { errors.push({ message: `A MultiMode Lexer cannot be initialized with a longer_alt <${currLongerAlt.name}> on token <${currTokType.name}> outside of mode <${currModeName}> `, type: LexerDefinitionErrorType.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE }); } }); } }); }); } return errors; } function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { const warnings = []; let hasAnyLineBreak = false; const allTokenTypes = compact(flatten(values(lexerDefinition.modes))); const concreteTokenTypes = reject(allTokenTypes, (currType) => currType[PATTERN] === Lexer2.NA); const terminatorCharCodes = getCharCodes(lineTerminatorCharacters); if (trackLines) { forEach(concreteTokenTypes, (tokType) => { const currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes); if (currIssue !== false) { const message = buildLineBreakIssueMessage(tokType, currIssue); const warningDescriptor = { message, type: currIssue.issue, tokenType: tokType }; warnings.push(warningDescriptor); } else { if (has(tokType, "LINE_BREAKS")) { if (tokType.LINE_BREAKS === true) { hasAnyLineBreak = true; } } else { if (canMatchCharCode(terminatorCharCodes, tokType.PATTERN)) { hasAnyLineBreak = true; } } } }); } if (trackLines && !hasAnyLineBreak) { warnings.push({ message: "Warning: No LINE_BREAKS Found.\n This Lexer has been defined to track line and column information,\n But none of the Token Types can be identified as matching a line terminator.\n See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n for details.", type: LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS }); } return warnings; } function cloneEmptyGroups(emptyGroups) { const clonedResult = {}; const groupKeys = keys(emptyGroups); forEach(groupKeys, (currKey) => { const currGroupValue = emptyGroups[currKey]; if (isArray$1(currGroupValue)) { clonedResult[currKey] = []; } else { throw Error("non exhaustive match"); } }); return clonedResult; } function isCustomPattern(tokenType) { const pattern = tokenType.PATTERN; if (isRegExp$1(pattern)) { return false; } else if (isFunction3(pattern)) { return true; } else if (has(pattern, "exec")) { return true; } else if (isString(pattern)) { return false; } else { throw Error("non exhaustive match"); } } function isShortPattern(pattern) { if (isString(pattern) && pattern.length === 1) { return pattern.charCodeAt(0); } else { return false; } } const LineTerminatorOptimizedTester = { // implements /\n|\r\n?/g.test test: function(text) { const len = text.length; for (let i4 = this.lastIndex; i4 < len; i4++) { const c2 = text.charCodeAt(i4); if (c2 === 10) { this.lastIndex = i4 + 1; return true; } else if (c2 === 13) { if (text.charCodeAt(i4 + 1) === 10) { this.lastIndex = i4 + 2; } else { this.lastIndex = i4 + 1; } return true; } } return false; }, lastIndex: 0 }; function checkLineBreaksIssues(tokType, lineTerminatorCharCodes) { if (has(tokType, "LINE_BREAKS")) { return false; } else { if (isRegExp$1(tokType.PATTERN)) { try { canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN); } catch (e2) { return { issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR, errMsg: e2.message }; } return false; } else if (isString(tokType.PATTERN)) { return false; } else if (isCustomPattern(tokType)) { return { issue: LexerDefinitionErrorType.CUSTOM_LINE_BREAK }; } else { throw Error("non exhaustive match"); } } } function buildLineBreakIssueMessage(tokType, details) { if (details.issue === LexerDefinitionErrorType.IDENTIFY_TERMINATOR) { return `Warning: unable to identify line terminator usage in pattern. The problem is in the <${tokType.name}> Token Type Root cause: ${details.errMsg}. For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`; } else if (details.issue === LexerDefinitionErrorType.CUSTOM_LINE_BREAK) { return `Warning: A Custom Token Pattern should specify the option. The problem is in the <${tokType.name}> Token Type For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`; } else { throw Error("non exhaustive match"); } } function getCharCodes(charsOrCodes) { const charCodes = map2(charsOrCodes, (numOrString) => { if (isString(numOrString)) { return numOrString.charCodeAt(0); } else { return numOrString; } }); return charCodes; } function addToMapOfArrays(map22, key, value) { if (map22[key] === void 0) { map22[key] = [value]; } else { map22[key].push(value); } } const minOptimizationVal = 256; let charCodeToOptimizedIdxMap = []; function charCodeToOptimizedIndex(charCode) { return charCode < minOptimizationVal ? charCode : charCodeToOptimizedIdxMap[charCode]; } function initCharCodeToOptimizedIndexMap() { if (isEmpty(charCodeToOptimizedIdxMap)) { charCodeToOptimizedIdxMap = new Array(65536); for (let i4 = 0; i4 < 65536; i4++) { charCodeToOptimizedIdxMap[i4] = i4 > 255 ? 255 + ~~(i4 / 255) : i4; } } } function tokenStructuredMatcher(tokInstance, tokConstructor) { const instanceType = tokInstance.tokenTypeIdx; if (instanceType === tokConstructor.tokenTypeIdx) { return true; } else { return tokConstructor.isParent === true && tokConstructor.categoryMatchesMap[instanceType] === true; } } function tokenStructuredMatcherNoCategories(token, tokType) { return token.tokenTypeIdx === tokType.tokenTypeIdx; } let tokenShortNameIdx = 1; const tokenIdxToClass = {}; function augmentTokenTypes(tokenTypes) { const tokenTypesAndParents = expandCategories(tokenTypes); assignTokenDefaultProps(tokenTypesAndParents); assignCategoriesMapProp(tokenTypesAndParents); assignCategoriesTokensProp(tokenTypesAndParents); forEach(tokenTypesAndParents, (tokType) => { tokType.isParent = tokType.categoryMatches.length > 0; }); } function expandCategories(tokenTypes) { let result = clone2(tokenTypes); let categories = tokenTypes; let searching = true; while (searching) { categories = compact(flatten(map2(categories, (currTokType) => currTokType.CATEGORIES))); const newCategories = difference$1(categories, result); result = result.concat(newCategories); if (isEmpty(newCategories)) { searching = false; } else { categories = newCategories; } } return result; } function assignTokenDefaultProps(tokenTypes) { forEach(tokenTypes, (currTokType) => { if (!hasShortKeyProperty(currTokType)) { tokenIdxToClass[tokenShortNameIdx] = currTokType; currTokType.tokenTypeIdx = tokenShortNameIdx++; } if (hasCategoriesProperty(currTokType) && !isArray$1(currTokType.CATEGORIES)) { currTokType.CATEGORIES = [currTokType.CATEGORIES]; } if (!hasCategoriesProperty(currTokType)) { currTokType.CATEGORIES = []; } if (!hasExtendingTokensTypesProperty(currTokType)) { currTokType.categoryMatches = []; } if (!hasExtendingTokensTypesMapProperty(currTokType)) { currTokType.categoryMatchesMap = {}; } }); } function assignCategoriesTokensProp(tokenTypes) { forEach(tokenTypes, (currTokType) => { currTokType.categoryMatches = []; forEach(currTokType.categoryMatchesMap, (val, key) => { currTokType.categoryMatches.push(tokenIdxToClass[key].tokenTypeIdx); }); }); } function assignCategoriesMapProp(tokenTypes) { forEach(tokenTypes, (currTokType) => { singleAssignCategoriesToksMap([], currTokType); }); } function singleAssignCategoriesToksMap(path, nextNode) { forEach(path, (pathNode) => { nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true; }); forEach(nextNode.CATEGORIES, (nextCategory) => { const newPath = path.concat(nextNode); if (!includes(newPath, nextCategory)) { singleAssignCategoriesToksMap(newPath, nextCategory); } }); } function hasShortKeyProperty(tokType) { return has(tokType, "tokenTypeIdx"); } function hasCategoriesProperty(tokType) { return has(tokType, "CATEGORIES"); } function hasExtendingTokensTypesProperty(tokType) { return has(tokType, "categoryMatches"); } function hasExtendingTokensTypesMapProperty(tokType) { return has(tokType, "categoryMatchesMap"); } function isTokenType(tokType) { return has(tokType, "tokenTypeIdx"); } const defaultLexerErrorProvider = { buildUnableToPopLexerModeMessage(token) { return `Unable to pop Lexer Mode after encountering Token ->${token.image}<- The Mode Stack is empty`; }, buildUnexpectedCharactersMessage(fullText, startOffset, length3, line, column) { return `unexpected character: ->${fullText.charAt(startOffset)}<- at offset: ${startOffset}, skipped ${length3} characters.`; } }; var LexerDefinitionErrorType; (function(LexerDefinitionErrorType2) { LexerDefinitionErrorType2[LexerDefinitionErrorType2["MISSING_PATTERN"] = 0] = "MISSING_PATTERN"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["INVALID_PATTERN"] = 1] = "INVALID_PATTERN"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["EOI_ANCHOR_FOUND"] = 2] = "EOI_ANCHOR_FOUND"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["UNSUPPORTED_FLAGS_FOUND"] = 3] = "UNSUPPORTED_FLAGS_FOUND"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["DUPLICATE_PATTERNS_FOUND"] = 4] = "DUPLICATE_PATTERNS_FOUND"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["INVALID_GROUP_TYPE_FOUND"] = 5] = "INVALID_GROUP_TYPE_FOUND"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["PUSH_MODE_DOES_NOT_EXIST"] = 6] = "PUSH_MODE_DOES_NOT_EXIST"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"] = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"] = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"] = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"] = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["SOI_ANCHOR_FOUND"] = 11] = "SOI_ANCHOR_FOUND"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["EMPTY_MATCH_PATTERN"] = 12] = "EMPTY_MATCH_PATTERN"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["NO_LINE_BREAKS_FLAGS"] = 13] = "NO_LINE_BREAKS_FLAGS"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["UNREACHABLE_PATTERN"] = 14] = "UNREACHABLE_PATTERN"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["IDENTIFY_TERMINATOR"] = 15] = "IDENTIFY_TERMINATOR"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["CUSTOM_LINE_BREAK"] = 16] = "CUSTOM_LINE_BREAK"; LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"] = 17] = "MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"; })(LexerDefinitionErrorType || (LexerDefinitionErrorType = {})); const DEFAULT_LEXER_CONFIG = { deferDefinitionErrorsHandling: false, positionTracking: "full", lineTerminatorsPattern: /\n|\r\n?/g, lineTerminatorCharacters: ["\n", "\r"], ensureOptimizations: false, safeMode: false, errorMessageProvider: defaultLexerErrorProvider, traceInitPerf: false, skipValidations: false, recoveryEnabled: true }; Object.freeze(DEFAULT_LEXER_CONFIG); class Lexer2 { constructor(lexerDefinition, config = DEFAULT_LEXER_CONFIG) { this.lexerDefinition = lexerDefinition; this.lexerDefinitionErrors = []; this.lexerDefinitionWarning = []; this.patternIdxToConfig = {}; this.charCodeToPatternIdxToConfig = {}; this.modes = []; this.emptyGroups = {}; this.trackStartLines = true; this.trackEndLines = true; this.hasCustom = false; this.canModeBeOptimized = {}; this.TRACE_INIT = (phaseDesc, phaseImpl) => { if (this.traceInitPerf === true) { this.traceInitIndent++; const indent = new Array(this.traceInitIndent + 1).join(" "); if (this.traceInitIndent < this.traceInitMaxIdent) { console.log(`${indent}--> <${phaseDesc}>`); } const { time, value } = timer2(phaseImpl); const traceMethod = time > 10 ? console.warn : console.log; if (this.traceInitIndent < this.traceInitMaxIdent) { traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`); } this.traceInitIndent--; return value; } else { return phaseImpl(); } }; if (typeof config === "boolean") { throw Error( "The second argument to the Lexer constructor is now an ILexerConfig Object.\na boolean 2nd argument is no longer supported" ); } this.config = assign$1({}, DEFAULT_LEXER_CONFIG, config); const traceInitVal = this.config.traceInitPerf; if (traceInitVal === true) { this.traceInitMaxIdent = Infinity; this.traceInitPerf = true; } else if (typeof traceInitVal === "number") { this.traceInitMaxIdent = traceInitVal; this.traceInitPerf = true; } this.traceInitIndent = -1; this.TRACE_INIT("Lexer Constructor", () => { let actualDefinition; let hasOnlySingleMode = true; this.TRACE_INIT("Lexer Config handling", () => { if (this.config.lineTerminatorsPattern === DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) { this.config.lineTerminatorsPattern = LineTerminatorOptimizedTester; } else { if (this.config.lineTerminatorCharacters === DEFAULT_LEXER_CONFIG.lineTerminatorCharacters) { throw Error( "Error: Missing property on the Lexer config.\n For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS" ); } } if (config.safeMode && config.ensureOptimizations) { throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.'); } this.trackStartLines = /full|onlyStart/i.test(this.config.positionTracking); this.trackEndLines = /full/i.test(this.config.positionTracking); if (isArray$1(lexerDefinition)) { actualDefinition = { modes: { defaultMode: clone2(lexerDefinition) }, defaultMode: DEFAULT_MODE }; } else { hasOnlySingleMode = false; actualDefinition = clone2(lexerDefinition); } }); if (this.config.skipValidations === false) { this.TRACE_INIT("performRuntimeChecks", () => { this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat( performRuntimeChecks(actualDefinition, this.trackStartLines, this.config.lineTerminatorCharacters) ); }); this.TRACE_INIT("performWarningRuntimeChecks", () => { this.lexerDefinitionWarning = this.lexerDefinitionWarning.concat( performWarningRuntimeChecks(actualDefinition, this.trackStartLines, this.config.lineTerminatorCharacters) ); }); } actualDefinition.modes = actualDefinition.modes ? actualDefinition.modes : {}; forEach(actualDefinition.modes, (currModeValue, currModeName) => { actualDefinition.modes[currModeName] = reject(currModeValue, (currTokType) => isUndefined(currTokType)); }); const allModeNames = keys(actualDefinition.modes); forEach(actualDefinition.modes, (currModDef, currModName) => { this.TRACE_INIT(`Mode: <${currModName}> processing`, () => { this.modes.push(currModName); if (this.config.skipValidations === false) { this.TRACE_INIT(`validatePatterns`, () => { this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat( validatePatterns(currModDef, allModeNames) ); }); } if (isEmpty(this.lexerDefinitionErrors)) { augmentTokenTypes(currModDef); let currAnalyzeResult; this.TRACE_INIT(`analyzeTokenTypes`, () => { currAnalyzeResult = analyzeTokenTypes(currModDef, { lineTerminatorCharacters: this.config.lineTerminatorCharacters, positionTracking: config.positionTracking, ensureOptimizations: config.ensureOptimizations, safeMode: config.safeMode, tracer: this.TRACE_INIT }); }); this.patternIdxToConfig[currModName] = currAnalyzeResult.patternIdxToConfig; this.charCodeToPatternIdxToConfig[currModName] = currAnalyzeResult.charCodeToPatternIdxToConfig; this.emptyGroups = assign$1({}, this.emptyGroups, currAnalyzeResult.emptyGroups); this.hasCustom = currAnalyzeResult.hasCustom || this.hasCustom; this.canModeBeOptimized[currModName] = currAnalyzeResult.canBeOptimized; } }); }); this.defaultMode = actualDefinition.defaultMode; if (!isEmpty(this.lexerDefinitionErrors) && !this.config.deferDefinitionErrorsHandling) { const allErrMessages = map2(this.lexerDefinitionErrors, (error) => { return error.message; }); const allErrMessagesString = allErrMessages.join("-----------------------\n"); throw new Error("Errors detected in definition of Lexer:\n" + allErrMessagesString); } forEach(this.lexerDefinitionWarning, (warningDescriptor) => { PRINT_WARNING(warningDescriptor.message); }); this.TRACE_INIT("Choosing sub-methods implementations", () => { if (SUPPORT_STICKY) { this.chopInput = identity3; this.match = this.matchWithTest; } else { this.updateLastIndex = noop2; this.match = this.matchWithExec; } if (hasOnlySingleMode) { this.handleModes = noop2; } if (this.trackStartLines === false) { this.computeNewColumn = identity3; } if (this.trackEndLines === false) { this.updateTokenEndLineColumnLocation = noop2; } if (/full/i.test(this.config.positionTracking)) { this.createTokenInstance = this.createFullToken; } else if (/onlyStart/i.test(this.config.positionTracking)) { this.createTokenInstance = this.createStartOnlyToken; } else if (/onlyOffset/i.test(this.config.positionTracking)) { this.createTokenInstance = this.createOffsetOnlyToken; } else { throw Error(`Invalid config option: "${this.config.positionTracking}"`); } if (this.hasCustom) { this.addToken = this.addTokenUsingPush; this.handlePayload = this.handlePayloadWithCustom; } else { this.addToken = this.addTokenUsingMemberAccess; this.handlePayload = this.handlePayloadNoCustom; } }); this.TRACE_INIT("Failed Optimization Warnings", () => { const unOptimizedModes = reduce2( this.canModeBeOptimized, (cannotBeOptimized, canBeOptimized, modeName) => { if (canBeOptimized === false) { cannotBeOptimized.push(modeName); } return cannotBeOptimized; }, [] ); if (config.ensureOptimizations && !isEmpty(unOptimizedModes)) { throw Error( `Lexer Modes: < ${unOptimizedModes.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.` ); } }); this.TRACE_INIT("clearRegExpParserCache", () => { clearRegExpParserCache(); }); this.TRACE_INIT("toFastProperties", () => { toFastProperties(this); }); }); } tokenize(text, initialMode = this.defaultMode) { if (!isEmpty(this.lexerDefinitionErrors)) { const allErrMessages = map2(this.lexerDefinitionErrors, (error) => { return error.message; }); const allErrMessagesString = allErrMessages.join("-----------------------\n"); throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" + allErrMessagesString); } return this.tokenizeInternal(text, initialMode); } // There is quite a bit of duplication between this and "tokenizeInternalLazy" // This is intentional due to performance considerations. // this method also used quite a bit of `!` none null assertions because it is too optimized // for `tsc` to always understand it is "safe" tokenizeInternal(text, initialMode) { let i4, j, k, matchAltImage, longerAlt, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, msg, match; const orgText = text; const orgLength = orgText.length; let offset = 0; let matchedTokensIndex = 0; const guessedNumberOfTokens = this.hasCustom ? 0 : Math.floor(text.length / 10); const matchedTokens = new Array(guessedNumberOfTokens); const errors = []; let line = this.trackStartLines ? 1 : void 0; let column = this.trackStartLines ? 1 : void 0; const groups = cloneEmptyGroups(this.emptyGroups); const trackLines = this.trackStartLines; const lineTerminatorPattern = this.config.lineTerminatorsPattern; let currModePatternsLength = 0; let patternIdxToConfig = []; let currCharCodeToPatternIdxToConfig = []; const modeStack = []; const emptyArray = []; Object.freeze(emptyArray); let getPossiblePatterns; function getPossiblePatternsSlow() { return patternIdxToConfig; } function getPossiblePatternsOptimized(charCode) { const optimizedCharIdx = charCodeToOptimizedIndex(charCode); const possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx]; if (possiblePatterns === void 0) { return emptyArray; } else { return possiblePatterns; } } const pop_mode = (popToken) => { if (modeStack.length === 1 && // if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition" // So no error should occur. popToken.tokenType.PUSH_MODE === void 0) { const msg2 = this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken); errors.push({ offset: popToken.startOffset, line: popToken.startLine, column: popToken.startColumn, length: popToken.image.length, message: msg2 }); } else { modeStack.pop(); const newMode = last(modeStack); patternIdxToConfig = this.patternIdxToConfig[newMode]; currCharCodeToPatternIdxToConfig = this.charCodeToPatternIdxToConfig[newMode]; currModePatternsLength = patternIdxToConfig.length; const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false; if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { getPossiblePatterns = getPossiblePatternsOptimized; } else { getPossiblePatterns = getPossiblePatternsSlow; } } }; function push_mode(newMode) { modeStack.push(newMode); currCharCodeToPatternIdxToConfig = this.charCodeToPatternIdxToConfig[newMode]; patternIdxToConfig = this.patternIdxToConfig[newMode]; currModePatternsLength = patternIdxToConfig.length; currModePatternsLength = patternIdxToConfig.length; const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false; if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { getPossiblePatterns = getPossiblePatternsOptimized; } else { getPossiblePatterns = getPossiblePatternsSlow; } } push_mode.call(this, initialMode); let currConfig; const recoveryEnabled = this.config.recoveryEnabled; while (offset < orgLength) { matchedImage = null; const nextCharCode = orgText.charCodeAt(offset); const chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode); const chosenPatternsLength = chosenPatternIdxToConfig.length; for (i4 = 0; i4 < chosenPatternsLength; i4++) { currConfig = chosenPatternIdxToConfig[i4]; const currPattern = currConfig.pattern; payload = null; const singleCharCode = currConfig.short; if (singleCharCode !== false) { if (nextCharCode === singleCharCode) { matchedImage = currPattern; } } else if (currConfig.isCustom === true) { match = currPattern.exec(orgText, offset, matchedTokens, groups); if (match !== null) { matchedImage = match[0]; if (match.payload !== void 0) { payload = match.payload; } } else { matchedImage = null; } } else { this.updateLastIndex(currPattern, offset); matchedImage = this.match(currPattern, text, offset); } if (matchedImage !== null) { longerAlt = currConfig.longerAlt; if (longerAlt !== void 0) { const longerAltLength = longerAlt.length; for (k = 0; k < longerAltLength; k++) { const longerAltConfig = patternIdxToConfig[longerAlt[k]]; const longerAltPattern = longerAltConfig.pattern; altPayload = null; if (longerAltConfig.isCustom === true) { match = longerAltPattern.exec(orgText, offset, matchedTokens, groups); if (match !== null) { matchAltImage = match[0]; if (match.payload !== void 0) { altPayload = match.payload; } } else { matchAltImage = null; } } else { this.updateLastIndex(longerAltPattern, offset); matchAltImage = this.match(longerAltPattern, text, offset); } if (matchAltImage && matchAltImage.length > matchedImage.length) { matchedImage = matchAltImage; payload = altPayload; currConfig = longerAltConfig; break; } } } break; } } if (matchedImage !== null) { imageLength = matchedImage.length; group = currConfig.group; if (group !== void 0) { tokType = currConfig.tokenTypeIdx; newToken = this.createTokenInstance( matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength ); this.handlePayload(newToken, payload); if (group === false) { matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken); } else { groups[group].push(newToken); } } text = this.chopInput(text, imageLength); offset = offset + imageLength; column = this.computeNewColumn(column, imageLength); if (trackLines === true && currConfig.canLineTerminator === true) { let numOfLTsInMatch = 0; let foundTerminator; let lastLTEndOffset; lineTerminatorPattern.lastIndex = 0; do { foundTerminator = lineTerminatorPattern.test(matchedImage); if (foundTerminator === true) { lastLTEndOffset = lineTerminatorPattern.lastIndex - 1; numOfLTsInMatch++; } } while (foundTerminator === true); if (numOfLTsInMatch !== 0) { line = line + numOfLTsInMatch; column = imageLength - lastLTEndOffset; this.updateTokenEndLineColumnLocation( newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength ); } } this.handleModes(currConfig, pop_mode, push_mode, newToken); } else { const errorStartOffset = offset; const errorLine = line; const errorColumn = column; let foundResyncPoint = recoveryEnabled === false; while (foundResyncPoint === false && offset < orgLength) { text = this.chopInput(text, 1); offset++; for (j = 0; j < currModePatternsLength; j++) { const currConfig2 = patternIdxToConfig[j]; const currPattern = currConfig2.pattern; const singleCharCode = currConfig2.short; if (singleCharCode !== false) { if (orgText.charCodeAt(offset) === singleCharCode) { foundResyncPoint = true; } } else if (currConfig2.isCustom === true) { foundResyncPoint = currPattern.exec(orgText, offset, matchedTokens, groups) !== null; } else { this.updateLastIndex(currPattern, offset); foundResyncPoint = currPattern.exec(text) !== null; } if (foundResyncPoint === true) { break; } } } errLength = offset - errorStartOffset; column = this.computeNewColumn(column, errLength); msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage( orgText, errorStartOffset, errLength, errorLine, errorColumn ); errors.push({ offset: errorStartOffset, line: errorLine, column: errorColumn, length: errLength, message: msg }); if (recoveryEnabled === false) { break; } } } if (!this.hasCustom) { matchedTokens.length = matchedTokensIndex; } return { tokens: matchedTokens, groups, errors }; } handleModes(config, pop_mode, push_mode, newToken) { if (config.pop === true) { const pushMode = config.push; pop_mode(newToken); if (pushMode !== void 0) { push_mode.call(this, pushMode); } } else if (config.push !== void 0) { push_mode.call(this, config.push); } } chopInput(text, length3) { return text.substring(length3); } updateLastIndex(regExp, newLastIndex) { regExp.lastIndex = newLastIndex; } // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler updateTokenEndLineColumnLocation(newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) { let lastCharIsLT, fixForEndingInLT; if (group !== void 0) { lastCharIsLT = lastLTIdx === imageLength - 1; fixForEndingInLT = lastCharIsLT ? -1 : 0; if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) { newToken.endLine = line + fixForEndingInLT; newToken.endColumn = column - 1 + -fixForEndingInLT; } } } computeNewColumn(oldColumn, imageLength) { return oldColumn + imageLength; } createOffsetOnlyToken(image, startOffset, tokenTypeIdx, tokenType) { return { image, startOffset, tokenTypeIdx, tokenType }; } createStartOnlyToken(image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) { return { image, startOffset, startLine, startColumn, tokenTypeIdx, tokenType }; } createFullToken(image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) { return { image, startOffset, endOffset: startOffset + imageLength - 1, startLine, endLine: startLine, startColumn, endColumn: startColumn + imageLength - 1, tokenTypeIdx, tokenType }; } addTokenUsingPush(tokenVector, index2, tokenToAdd) { tokenVector.push(tokenToAdd); return index2; } addTokenUsingMemberAccess(tokenVector, index2, tokenToAdd) { tokenVector[index2] = tokenToAdd; index2++; return index2; } handlePayloadNoCustom(token, payload) { } handlePayloadWithCustom(token, payload) { if (payload !== null) { token.payload = payload; } } matchWithTest(pattern, text, offset) { const found = pattern.test(text); if (found === true) { return text.substring(offset, pattern.lastIndex); } return null; } matchWithExec(pattern, text) { const regExpArray = pattern.exec(text); return regExpArray !== null ? regExpArray[0] : null; } } Lexer2.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."; Lexer2.NA = /NOT_APPLICABLE/; function tokenLabel(tokType) { if (hasTokenLabel(tokType)) { return tokType.LABEL; } else { return tokType.name; } } function hasTokenLabel(obj) { return isString(obj.LABEL) && obj.LABEL !== ""; } const PARENT = "parent"; const CATEGORIES = "categories"; const LABEL = "label"; const GROUP = "group"; const PUSH_MODE = "push_mode"; const POP_MODE = "pop_mode"; const LONGER_ALT = "longer_alt"; const LINE_BREAKS = "line_breaks"; const START_CHARS_HINT = "start_chars_hint"; function createToken2(config) { return createTokenInternal(config); } function createTokenInternal(config) { const pattern = config.pattern; const tokenType = {}; tokenType.name = config.name; if (!isUndefined(pattern)) { tokenType.PATTERN = pattern; } if (has(config, PARENT)) { throw "The parent property is no longer supported.\nSee: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details."; } if (has(config, CATEGORIES)) { tokenType.CATEGORIES = config[CATEGORIES]; } augmentTokenTypes([tokenType]); if (has(config, LABEL)) { tokenType.LABEL = config[LABEL]; } if (has(config, GROUP)) { tokenType.GROUP = config[GROUP]; } if (has(config, POP_MODE)) { tokenType.POP_MODE = config[POP_MODE]; } if (has(config, PUSH_MODE)) { tokenType.PUSH_MODE = config[PUSH_MODE]; } if (has(config, LONGER_ALT)) { tokenType.LONGER_ALT = config[LONGER_ALT]; } if (has(config, LINE_BREAKS)) { tokenType.LINE_BREAKS = config[LINE_BREAKS]; } if (has(config, START_CHARS_HINT)) { tokenType.START_CHARS_HINT = config[START_CHARS_HINT]; } return tokenType; } const EOF = createToken2({ name: "EOF", pattern: Lexer2.NA }); augmentTokenTypes([EOF]); function createTokenInstance(tokType, image, startOffset, endOffset, startLine, endLine, startColumn, endColumn) { return { image, startOffset, endOffset, startLine, endLine, startColumn, endColumn, tokenTypeIdx: tokType.tokenTypeIdx, tokenType: tokType }; } function tokenMatcher(token, tokType) { return tokenStructuredMatcher(token, tokType); } const defaultParserErrorProvider = { buildMismatchTokenMessage({ expected, actual, previous, ruleName }) { const hasLabel = hasTokenLabel(expected); const expectedMsg = hasLabel ? `--> ${tokenLabel(expected)} <--` : `token of type --> ${expected.name} <--`; const msg = `Expecting ${expectedMsg} but found --> '${actual.image}' <--`; return msg; }, buildNotAllInputParsedMessage({ firstRedundant, ruleName }) { return "Redundant input, expecting EOF but found: " + firstRedundant.image; }, buildNoViableAltMessage({ expectedPathsPerAlt, actual, previous, customUserDescription, ruleName }) { const errPrefix = "Expecting: "; const actualText = head(actual).image; const errSuffix = "\nbut found: '" + actualText + "'"; if (customUserDescription) { return errPrefix + customUserDescription + errSuffix; } else { const allLookAheadPaths = reduce2(expectedPathsPerAlt, (result, currAltPaths) => result.concat(currAltPaths), []); const nextValidTokenSequences = map2( allLookAheadPaths, (currPath) => `[${map2(currPath, (currTokenType) => tokenLabel(currTokenType)).join(", ")}]` ); const nextValidSequenceItems = map2(nextValidTokenSequences, (itemMsg, idx) => ` ${idx + 1}. ${itemMsg}`); const calculatedDescription = `one of these possible Token sequences: ${nextValidSequenceItems.join("\n")}`; return errPrefix + calculatedDescription + errSuffix; } }, buildEarlyExitMessage({ expectedIterationPaths, actual, customUserDescription, ruleName }) { const errPrefix = "Expecting: "; const actualText = head(actual).image; const errSuffix = "\nbut found: '" + actualText + "'"; if (customUserDescription) { return errPrefix + customUserDescription + errSuffix; } else { const nextValidTokenSequences = map2( expectedIterationPaths, (currPath) => `[${map2(currPath, (currTokenType) => tokenLabel(currTokenType)).join(",")}]` ); const calculatedDescription = `expecting at least one iteration which starts with one of these possible Token sequences:: <${nextValidTokenSequences.join(" ,")}>`; return errPrefix + calculatedDescription + errSuffix; } } }; Object.freeze(defaultParserErrorProvider); const defaultGrammarResolverErrorProvider = { buildRuleNotFoundError(topLevelRule, undefinedRule) { const msg = "Invalid grammar, reference to a rule which is not defined: ->" + undefinedRule.nonTerminalName + "<-\ninside top level rule: ->" + topLevelRule.name + "<-"; return msg; } }; const defaultGrammarValidatorErrorProvider = { buildDuplicateFoundError(topLevelRule, duplicateProds) { function getExtraProductionArgument2(prod) { if (prod instanceof Terminal) { return prod.terminalType.name; } else if (prod instanceof NonTerminal) { return prod.nonTerminalName; } else { return ""; } } const topLevelName = topLevelRule.name; const duplicateProd = head(duplicateProds); const index2 = duplicateProd.idx; const dslName = getProductionDslName(duplicateProd); const extraArgument = getExtraProductionArgument2(duplicateProd); const hasExplicitIndex = index2 > 0; let msg = `->${dslName}${hasExplicitIndex ? index2 : ""}<- ${extraArgument ? `with argument: ->${extraArgument}<-` : ""} appears more than once (${duplicateProds.length} times) in the top level rule: ->${topLevelName}<-. For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES `; msg = msg.replace(/[ \t]+/g, " "); msg = msg.replace(/\s\s+/g, "\n"); return msg; }, buildNamespaceConflictError(rule) { const errMsg = `Namespace conflict found in grammar. The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${rule.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 errMsg; }, buildAlternationPrefixAmbiguityError(options) { const pathMsg = map2(options.prefixPath, (currTok) => tokenLabel(currTok)).join(", "); const occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; const errMsg = `Ambiguous alternatives: <${options.ambiguityIndices.join(" ,")}> due to common lookahead prefix in inside <${options.topLevelRule.name}> Rule, <${pathMsg}> 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 errMsg; }, buildAlternationAmbiguityError(options) { const pathMsg = map2(options.prefixPath, (currtok) => tokenLabel(currtok)).join(", "); const occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; let currMessage = `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(" ,")}> in inside <${options.topLevelRule.name}> Rule, <${pathMsg}> may appears as a prefix path in all these alternatives. `; currMessage = currMessage + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES For Further details.`; return currMessage; }, buildEmptyRepetitionError(options) { let dslName = getProductionDslName(options.repetition); if (options.repetition.idx !== 0) { dslName += options.repetition.idx; } const errMsg = `The repetition <${dslName}> within Rule <${options.topLevelRule.name}> can never consume any tokens. This could lead to an infinite loop.`; return errMsg; }, // TODO: remove - `errors_public` from nyc.config.js exclude // once this method is fully removed from this file buildTokenNameError(options) { return "deprecated"; }, buildEmptyAlternationError(options) { const errMsg = `Ambiguous empty alternative: <${options.emptyChoiceIdx + 1}> in inside <${options.topLevelRule.name}> Rule. Only the last alternative may be an empty alternative.`; return errMsg; }, buildTooManyAlternativesError(options) { const errMsg = `An Alternation cannot have more than 256 alternatives: inside <${options.topLevelRule.name}> Rule. has ${options.alternation.definition.length + 1} alternatives.`; return errMsg; }, buildLeftRecursionError(options) { const ruleName = options.topLevelRule.name; const pathNames = map2(options.leftRecursionPath, (currRule) => currRule.name); const leftRecursivePath = `${ruleName} --> ${pathNames.concat([ruleName]).join(" --> ")}`; const errMsg = `Left Recursion found in grammar. rule: <${ruleName}> can be invoked from itself (directly or indirectly) without consuming any Tokens. The grammar path that causes this is: ${leftRecursivePath} To fix this refactor your grammar to remove the left recursion. see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`; return errMsg; }, // TODO: remove - `errors_public` from nyc.config.js exclude // once this method is fully removed from this file buildInvalidRuleNameError(options) { return "deprecated"; }, buildDuplicateRuleNameError(options) { let ruleName; if (options.topLevelRule instanceof Rule) { ruleName = options.topLevelRule.name; } else { ruleName = options.topLevelRule; } const errMsg = `Duplicate definition, rule: ->${ruleName}<- is already defined in the grammar: ->${options.grammarName}<-`; return errMsg; } }; function resolveGrammar$1(topLevels, errMsgProvider) { const refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider); refResolver.resolveRefs(); return refResolver.errors; } class GastRefResolverVisitor extends GAstVisitor { constructor(nameToTopRule, errMsgProvider) { super(); this.nameToTopRule = nameToTopRule; this.errMsgProvider = errMsgProvider; this.errors = []; } resolveRefs() { forEach(values(this.nameToTopRule), (prod) => { this.currTopLevel = prod; prod.accept(this); }); } visitNonTerminal(node) { const ref = this.nameToTopRule[node.nonTerminalName]; if (!ref) { const msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node); this.errors.push({ message: msg, type: ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, ruleName: this.currTopLevel.name, unresolvedRefName: node.nonTerminalName }); } else { node.referencedRule = ref; } } } class AbstractNextPossibleTokensWalker extends RestWalker { constructor(topProd, path) { super(); this.topProd = topProd; this.path = path; this.possibleTokTypes = []; this.nextProductionName = ""; this.nextProductionOccurrence = 0; this.found = false; this.isAtEndOfPath = false; } startWalking() { this.found = false; if (this.path.ruleStack[0] !== this.topProd.name) { throw Error("The path does not start with the walker's top Rule!"); } this.ruleStack = clone2(this.path.ruleStack).reverse(); this.occurrenceStack = clone2(this.path.occurrenceStack).reverse(); this.ruleStack.pop(); this.occurrenceStack.pop(); this.updateExpectedNext(); this.walk(this.topProd); return this.possibleTokTypes; } walk(prod, prevRest = []) { if (!this.found) { super.walk(prod, prevRest); } } walkProdRef(refProd, currRest, prevRest) { if (refProd.referencedRule.name === this.nextProductionName && refProd.idx === this.nextProductionOccurrence) { const fullRest = currRest.concat(prevRest); this.updateExpectedNext(); this.walk(refProd.referencedRule, fullRest); } } updateExpectedNext() { if (isEmpty(this.ruleStack)) { this.nextProductionName = ""; this.nextProductionOccurrence = 0; this.isAtEndOfPath = true; } else { this.nextProductionName = this.ruleStack.pop(); this.nextProductionOccurrence = this.occurrenceStack.pop(); } } } class NextAfterTokenWalker extends AbstractNextPossibleTokensWalker { constructor(topProd, path) { super(topProd, path); this.path = path; this.nextTerminalName = ""; this.nextTerminalOccurrence = 0; this.nextTerminalName = this.path.lastTok.name; this.nextTerminalOccurrence = this.path.lastTokOccurrence; } walkTerminal(terminal, currRest, prevRest) { if (this.isAtEndOfPath && terminal.terminalType.name === this.nextTerminalName && terminal.idx === this.nextTerminalOccurrence && !this.found) { const fullRest = currRest.concat(prevRest); const restProd = new Alternative({ definition: fullRest }); this.possibleTokTypes = first2(restProd); this.found = true; } } } class AbstractNextTerminalAfterProductionWalker extends RestWalker { constructor(topRule, occurrence) { super(); this.topRule = topRule; this.occurrence = occurrence; this.result = { token: void 0, occurrence: void 0, isEndOfRule: void 0 }; } startWalking() { this.walk(this.topRule); return this.result; } } class NextTerminalAfterManyWalker extends AbstractNextTerminalAfterProductionWalker { walkMany(manyProd, currRest, prevRest) { if (manyProd.idx === this.occurrence) { const firstAfterMany = head(currRest.concat(prevRest)); this.result.isEndOfRule = firstAfterMany === void 0; if (firstAfterMany instanceof Terminal) { this.result.token = firstAfterMany.terminalType; this.result.occurrence = firstAfterMany.idx; } } else { super.walkMany(manyProd, currRest, prevRest); } } } class NextTerminalAfterManySepWalker extends AbstractNextTerminalAfterProductionWalker { walkManySep(manySepProd, currRest, prevRest) { if (manySepProd.idx === this.occurrence) { const firstAfterManySep = head(currRest.concat(prevRest)); this.result.isEndOfRule = firstAfterManySep === void 0; if (firstAfterManySep instanceof Terminal) { this.result.token = firstAfterManySep.terminalType; this.result.occurrence = firstAfterManySep.idx; } } else { super.walkManySep(manySepProd, currRest, prevRest); } } } class NextTerminalAfterAtLeastOneWalker extends AbstractNextTerminalAfterProductionWalker { walkAtLeastOne(atLeastOneProd, currRest, prevRest) { if (atLeastOneProd.idx === this.occurrence) { const firstAfterAtLeastOne = head(currRest.concat(prevRest)); this.result.isEndOfRule = firstAfterAtLeastOne === void 0; if (firstAfterAtLeastOne instanceof Terminal) { this.result.token = firstAfterAtLeastOne.terminalType; this.result.occurrence = firstAfterAtLeastOne.idx; } } else { super.walkAtLeastOne(atLeastOneProd, currRest, prevRest); } } } class NextTerminalAfterAtLeastOneSepWalker extends AbstractNextTerminalAfterProductionWalker { walkAtLeastOneSep(atleastOneSepProd, currRest, prevRest) { if (atleastOneSepProd.idx === this.occurrence) { const firstAfterfirstAfterAtLeastOneSep = head(currRest.concat(prevRest)); this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === void 0; if (firstAfterfirstAfterAtLeastOneSep instanceof Terminal) { this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType; this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx; } } else { super.walkAtLeastOneSep(atleastOneSepProd, currRest, prevRest); } } } function possiblePathsFrom(targetDef, maxLength, currPath = []) { currPath = clone2(currPath); let result = []; let i4 = 0; function remainingPathWith(nextDef) { return nextDef.concat(drop(targetDef, i4 + 1)); } function getAlternativesForProd(definition) { const alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath); return result.concat(alternatives); } while (currPath.length < maxLength && i4 < targetDef.length) { const prod = targetDef[i4]; if (prod instanceof Alternative) { return getAlternativesForProd(prod.definition); } else if (prod instanceof NonTerminal) { return getAlternativesForProd(prod.definition); } else if (prod instanceof Option) { result = getAlternativesForProd(prod.definition); } else if (prod instanceof RepetitionMandatory) { const newDef = prod.definition.concat([ new Repetition({ definition: prod.definition }) ]); return getAlternativesForProd(newDef); } else if (prod instanceof RepetitionMandatoryWithSeparator) { const newDef = [ new Alternative({ definition: prod.definition }), new Repetition({ definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition) }) ]; return getAlternativesForProd(newDef); } else if (prod instanceof RepetitionWithSeparator) { const newDef = prod.definition.concat([ new Repetition({ definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition) }) ]); result = getAlternativesForProd(newDef); } else if (prod instanceof Repetition) { const newDef = prod.definition.concat([ new Repetition({ definition: prod.definition }) ]); result = getAlternativesForProd(newDef); } else if (prod instanceof Alternation) { forEach(prod.definition, (currAlt) => { if (isEmpty(currAlt.definition) === false) { result = getAlternativesForProd(currAlt.definition); } }); return result; } else if (prod instanceof Terminal) { currPath.push(prod.terminalType); } else { throw Error("non exhaustive match"); } i4++; } result.push({ partialPath: currPath, suffixDef: drop(targetDef, i4) }); return result; } function nextPossibleTokensAfter(initialDef, tokenVector, tokMatcher, maxLookAhead) { const EXIT_NON_TERMINAL = "EXIT_NONE_TERMINAL"; const EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL]; const EXIT_ALTERNATIVE = "EXIT_ALTERNATIVE"; let foundCompletePath = false; const tokenVectorLength = tokenVector.length; const minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1; const result = []; const possiblePaths = []; possiblePaths.push({ idx: -1, def: initialDef, ruleStack: [], occurrenceStack: [] }); while (!isEmpty(possiblePaths)) { const currPath = possiblePaths.pop(); if (currPath === EXIT_ALTERNATIVE) { if (foundCompletePath && last(possiblePaths).idx <= minimalAlternativesIndex) { possiblePaths.pop(); } continue; } const currDef = currPath.def; const currIdx = currPath.idx; const currRuleStack = currPath.ruleStack; const currOccurrenceStack = currPath.occurrenceStack; if (isEmpty(currDef)) { continue; } const prod = currDef[0]; if (prod === EXIT_NON_TERMINAL) { const nextPath = { idx: currIdx, def: drop(currDef), ruleStack: dropRight(currRuleStack), occurrenceStack: dropRight(currOccurrenceStack) }; possiblePaths.push(nextPath); } else if (prod instanceof Terminal) { if (currIdx < tokenVectorLength - 1) { const nextIdx = currIdx + 1; const actualToken = tokenVector[nextIdx]; if (tokMatcher(actualToken, prod.terminalType)) { const nextPath = { idx: nextIdx, def: drop(currDef), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPath); } } else if (currIdx === tokenVectorLength - 1) { result.push({ nextTokenType: prod.terminalType, nextTokenOccurrence: prod.idx, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }); foundCompletePath = true; } else { throw Error("non exhaustive match"); } } else if (prod instanceof NonTerminal) { const newRuleStack = clone2(currRuleStack); newRuleStack.push(prod.nonTerminalName); const newOccurrenceStack = clone2(currOccurrenceStack); newOccurrenceStack.push(prod.idx); const nextPath = { idx: currIdx, def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, drop(currDef)), ruleStack: newRuleStack, occurrenceStack: newOccurrenceStack }; possiblePaths.push(nextPath); } else if (prod instanceof Option) { const nextPathWithout = { idx: currIdx, def: drop(currDef), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWithout); possiblePaths.push(EXIT_ALTERNATIVE); const nextPathWith = { idx: currIdx, def: prod.definition.concat(drop(currDef)), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWith); } else if (prod instanceof RepetitionMandatory) { const secondIteration = new Repetition({ definition: prod.definition, idx: prod.idx }); const nextDef = prod.definition.concat([secondIteration], drop(currDef)); const nextPath = { idx: currIdx, def: nextDef, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPath); } else if (prod instanceof RepetitionMandatoryWithSeparator) { const separatorGast = new Terminal({ terminalType: prod.separator }); const secondIteration = new Repetition({ definition: [separatorGast].concat(prod.definition), idx: prod.idx }); const nextDef = prod.definition.concat([secondIteration], drop(currDef)); const nextPath = { idx: currIdx, def: nextDef, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPath); } else if (prod instanceof RepetitionWithSeparator) { const nextPathWithout = { idx: currIdx, def: drop(currDef), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWithout); possiblePaths.push(EXIT_ALTERNATIVE); const separatorGast = new Terminal({ terminalType: prod.separator }); const nthRepetition = new Repetition({ definition: [separatorGast].concat(prod.definition), idx: prod.idx }); const nextDef = prod.definition.concat([nthRepetition], drop(currDef)); const nextPathWith = { idx: currIdx, def: nextDef, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWith); } else if (prod instanceof Repetition) { const nextPathWithout = { idx: currIdx, def: drop(currDef), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWithout); possiblePaths.push(EXIT_ALTERNATIVE); const nthRepetition = new Repetition({ definition: prod.definition, idx: prod.idx }); const nextDef = prod.definition.concat([nthRepetition], drop(currDef)); const nextPathWith = { idx: currIdx, def: nextDef, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWith); } else if (prod instanceof Alternation) { for (let i4 = prod.definition.length - 1; i4 >= 0; i4--) { const currAlt = prod.definition[i4]; const currAltPath = { idx: currIdx, def: currAlt.definition.concat(drop(currDef)), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(currAltPath); possiblePaths.push(EXIT_ALTERNATIVE); } } else if (prod instanceof Alternative) { possiblePaths.push({ idx: currIdx, def: prod.definition.concat(drop(currDef)), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }); } else if (prod instanceof Rule) { possiblePaths.push(expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack)); } else { throw Error("non exhaustive match"); } } return result; } function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) { const newRuleStack = clone2(currRuleStack); newRuleStack.push(topRule.name); const newCurrOccurrenceStack = clone2(currOccurrenceStack); newCurrOccurrenceStack.push(1); return { idx: currIdx, def: topRule.definition, ruleStack: newRuleStack, occurrenceStack: newCurrOccurrenceStack }; } var PROD_TYPE; (function(PROD_TYPE2) { PROD_TYPE2[PROD_TYPE2["OPTION"] = 0] = "OPTION"; PROD_TYPE2[PROD_TYPE2["REPETITION"] = 1] = "REPETITION"; PROD_TYPE2[PROD_TYPE2["REPETITION_MANDATORY"] = 2] = "REPETITION_MANDATORY"; PROD_TYPE2[PROD_TYPE2["REPETITION_MANDATORY_WITH_SEPARATOR"] = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR"; PROD_TYPE2[PROD_TYPE2["REPETITION_WITH_SEPARATOR"] = 4] = "REPETITION_WITH_SEPARATOR"; PROD_TYPE2[PROD_TYPE2["ALTERNATION"] = 5] = "ALTERNATION"; })(PROD_TYPE || (PROD_TYPE = {})); function getProdType(prod) { if (prod instanceof Option || prod === "Option") { return PROD_TYPE.OPTION; } else if (prod instanceof Repetition || prod === "Repetition") { return PROD_TYPE.REPETITION; } else if (prod instanceof RepetitionMandatory || prod === "RepetitionMandatory") { return PROD_TYPE.REPETITION_MANDATORY; } else if (prod instanceof RepetitionMandatoryWithSeparator || prod === "RepetitionMandatoryWithSeparator") { return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR; } else if (prod instanceof RepetitionWithSeparator || prod === "RepetitionWithSeparator") { return PROD_TYPE.REPETITION_WITH_SEPARATOR; } else if (prod instanceof Alternation || prod === "Alternation") { return PROD_TYPE.ALTERNATION; } else { throw Error("non exhaustive match"); } } function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) { const lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead); const tokenMatcher2 = areTokenCategoriesNotUsed(lookAheadPaths) ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher; return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher2, dynamicTokensEnabled); } function buildLookaheadFuncForOptionalProd(occurrence, ruleGrammar, k, dynamicTokensEnabled, prodType, lookaheadBuilder) { const lookAheadPaths = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k); const tokenMatcher2 = areTokenCategoriesNotUsed(lookAheadPaths) ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher; return lookaheadBuilder(lookAheadPaths[0], tokenMatcher2, dynamicTokensEnabled); } function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher2, dynamicTokensEnabled) { const numOfAlts = alts.length; const areAllOneTokenLookahead = every(alts, (currAlt) => { return every(currAlt, (currPath) => { return currPath.length === 1; }); }); if (hasPredicates) { return function(orAlts) { const predicates = map2(orAlts, (currAlt) => currAlt.GATE); for (let t3 = 0; t3 < numOfAlts; t3++) { const currAlt = alts[t3]; const currNumOfPaths = currAlt.length; const currPredicate = predicates[t3]; if (currPredicate !== void 0 && currPredicate.call(this) === false) { continue; } nextPath: for (let j = 0; j < currNumOfPaths; j++) { const currPath = currAlt[j]; const currPathLength = currPath.length; for (let i4 = 0; i4 < currPathLength; i4++) { const nextToken = this.LA(i4 + 1); if (tokenMatcher2(nextToken, currPath[i4]) === false) { continue nextPath; } } return t3; } } return void 0; }; } else if (areAllOneTokenLookahead && !dynamicTokensEnabled) { const singleTokenAlts = map2(alts, (currAlt) => { return flatten(currAlt); }); const choiceToAlt = reduce2( singleTokenAlts, (result, currAlt, idx) => { forEach(currAlt, (currTokType) => { if (!has(result, currTokType.tokenTypeIdx)) { result[currTokType.tokenTypeIdx] = idx; } forEach(currTokType.categoryMatches, (currExtendingType) => { if (!has(result, currExtendingType)) { result[currExtendingType] = idx; } }); }); return result; }, {} ); return function() { const nextToken = this.LA(1); return choiceToAlt[nextToken.tokenTypeIdx]; }; } else { return function() { for (let t3 = 0; t3 < numOfAlts; t3++) { const currAlt = alts[t3]; const currNumOfPaths = currAlt.length; nextPath: for (let j = 0; j < currNumOfPaths; j++) { const currPath = currAlt[j]; const currPathLength = currPath.length; for (let i4 = 0; i4 < currPathLength; i4++) { const nextToken = this.LA(i4 + 1); if (tokenMatcher2(nextToken, currPath[i4]) === false) { continue nextPath; } } return t3; } } return void 0; }; } } function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher2, dynamicTokensEnabled) { const areAllOneTokenLookahead = every(alt, (currPath) => { return currPath.length === 1; }); const numOfPaths = alt.length; if (areAllOneTokenLookahead && !dynamicTokensEnabled) { const singleTokensTypes = flatten(alt); if (singleTokensTypes.length === 1 && isEmpty(singleTokensTypes[0].categoryMatches)) { const expectedTokenType = singleTokensTypes[0]; const expectedTokenUniqueKey = expectedTokenType.tokenTypeIdx; return function() { return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey; }; } else { const choiceToAlt = reduce2( singleTokensTypes, (result, currTokType, idx) => { result[currTokType.tokenTypeIdx] = true; forEach(currTokType.categoryMatches, (currExtendingType) => { result[currExtendingType] = true; }); return result; }, [] ); return function() { const nextToken = this.LA(1); return choiceToAlt[nextToken.tokenTypeIdx] === true; }; } } else { return function() { nextPath: for (let j = 0; j < numOfPaths; j++) { const currPath = alt[j]; const currPathLength = currPath.length; for (let i4 = 0; i4 < currPathLength; i4++) { const nextToken = this.LA(i4 + 1); if (tokenMatcher2(nextToken, currPath[i4]) === false) { continue nextPath; } } return true; } return false; }; } } class RestDefinitionFinderWalker extends RestWalker { constructor(topProd, targetOccurrence, targetProdType) { super(); this.topProd = topProd; this.targetOccurrence = targetOccurrence; this.targetProdType = targetProdType; } startWalking() { this.walk(this.topProd); return this.restDef; } checkIsTarget(node, expectedProdType, currRest, prevRest) { if (node.idx === this.targetOccurrence && this.targetProdType === expectedProdType) { this.restDef = currRest.concat(prevRest); return true; } return false; } walkOption(optionProd, currRest, prevRest) { if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) { super.walkOption(optionProd, currRest, prevRest); } } walkAtLeastOne(atLeastOneProd, currRest, prevRest) { if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) { super.walkOption(atLeastOneProd, currRest, prevRest); } } walkAtLeastOneSep(atLeastOneSepProd, currRest, prevRest) { if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) { super.walkOption(atLeastOneSepProd, currRest, prevRest); } } walkMany(manyProd, currRest, prevRest) { if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) { super.walkOption(manyProd, currRest, prevRest); } } walkManySep(manySepProd, currRest, prevRest) { if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) { super.walkOption(manySepProd, currRest, prevRest); } } } class InsideDefinitionFinderVisitor extends GAstVisitor { constructor(targetOccurrence, targetProdType, targetRef) { super(); this.targetOccurrence = targetOccurrence; this.targetProdType = targetProdType; this.targetRef = targetRef; this.result = []; } checkIsTarget(node, expectedProdName) { if (node.idx === this.targetOccurrence && this.targetProdType === expectedProdName && (this.targetRef === void 0 || node === this.targetRef)) { this.result = node.definition; } } visitOption(node) { this.checkIsTarget(node, PROD_TYPE.OPTION); } visitRepetition(node) { this.checkIsTarget(node, PROD_TYPE.REPETITION); } visitRepetitionMandatory(node) { this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY); } visitRepetitionMandatoryWithSeparator(node) { this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR); } visitRepetitionWithSeparator(node) { this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR); } visitAlternation(node) { this.checkIsTarget(node, PROD_TYPE.ALTERNATION); } } function initializeArrayOfArrays(size2) { const result = new Array(size2); for (let i4 = 0; i4 < size2; i4++) { result[i4] = []; } return result; } function pathToHashKeys(path) { let keys2 = [""]; for (let i4 = 0; i4 < path.length; i4++) { const tokType = path[i4]; const longerKeys = []; for (let j = 0; j < keys2.length; j++) { const currShorterKey = keys2[j]; longerKeys.push(currShorterKey + "_" + tokType.tokenTypeIdx); for (let t3 = 0; t3 < tokType.categoryMatches.length; t3++) { const categoriesKeySuffix = "_" + tokType.categoryMatches[t3]; longerKeys.push(currShorterKey + categoriesKeySuffix); } } keys2 = longerKeys; } return keys2; } function isUniquePrefixHash(altKnownPathsKeys, searchPathKeys, idx) { for (let currAltIdx = 0; currAltIdx < altKnownPathsKeys.length; currAltIdx++) { if (currAltIdx === idx) { continue; } const otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx]; for (let searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) { const searchKey = searchPathKeys[searchIdx]; if (otherAltKnownPathsKeys[searchKey] === true) { return false; } } } return true; } function lookAheadSequenceFromAlternatives(altsDefs, k) { const partialAlts = map2(altsDefs, (currAlt) => possiblePathsFrom([currAlt], 1)); const finalResult = initializeArrayOfArrays(partialAlts.length); const altsHashes = map2(partialAlts, (currAltPaths) => { const dict = {}; forEach(currAltPaths, (item) => { const keys2 = pathToHashKeys(item.partialPath); forEach(keys2, (currKey) => { dict[currKey] = true; }); }); return dict; }); let newData = partialAlts; for (let pathLength = 1; pathLength <= k; pathLength++) { const currDataset = newData; newData = initializeArrayOfArrays(currDataset.length); for (let altIdx = 0; altIdx < currDataset.length; altIdx++) { const currAltPathsAndSuffixes = currDataset[altIdx]; for (let currPathIdx = 0; currPathIdx < currAltPathsAndSuffixes.length; currPathIdx++) { const currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath; const suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef; const prefixKeys = pathToHashKeys(currPathPrefix); const isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx); if (isUnique || isEmpty(suffixDef) || currPathPrefix.length === k) { const currAltResult = finalResult[altIdx]; if (containsPath(currAltResult, currPathPrefix) === false) { currAltResult.push(currPathPrefix); for (let j = 0; j < prefixKeys.length; j++) { const currKey = prefixKeys[j]; altsHashes[altIdx][currKey] = true; } } } else { const newPartialPathsAndSuffixes = possiblePathsFrom(suffixDef, pathLength + 1, currPathPrefix); newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes); forEach(newPartialPathsAndSuffixes, (item) => { const prefixKeys2 = pathToHashKeys(item.partialPath); forEach(prefixKeys2, (key) => { altsHashes[altIdx][key] = true; }); }); } } } } return finalResult; } function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) { const visitor = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd); ruleGrammar.accept(visitor); return lookAheadSequenceFromAlternatives(visitor.result, k); } function getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k) { const insideDefVisitor = new InsideDefinitionFinderVisitor(occurrence, prodType); ruleGrammar.accept(insideDefVisitor); const insideDef = insideDefVisitor.result; const afterDefWalker = new RestDefinitionFinderWalker(ruleGrammar, occurrence, prodType); const afterDef = afterDefWalker.startWalking(); const insideFlat = new Alternative({ definition: insideDef }); const afterFlat = new Alternative({ definition: afterDef }); return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k); } function containsPath(alternative, searchPath) { compareOtherPath: for (let i4 = 0; i4 < alternative.length; i4++) { const otherPath = alternative[i4]; if (otherPath.length !== searchPath.length) { continue; } for (let j = 0; j < otherPath.length; j++) { const searchTok = searchPath[j]; const otherTok = otherPath[j]; const matchingTokens = searchTok === otherTok || otherTok.categoryMatchesMap[searchTok.tokenTypeIdx] !== void 0; if (matchingTokens === false) { continue compareOtherPath; } } return true; } return false; } function isStrictPrefixOfPath(prefix, other) { return prefix.length < other.length && every(prefix, (tokType, idx) => { const otherTokType = other[idx]; return tokType === otherTokType || otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]; }); } function areTokenCategoriesNotUsed(lookAheadPaths) { return every( lookAheadPaths, (singleAltPaths) => every(singleAltPaths, (singlePath) => every(singlePath, (token) => isEmpty(token.categoryMatches))) ); } function validateLookahead(options) { const lookaheadValidationErrorMessages = options.lookaheadStrategy.validate({ rules: options.rules, tokenTypes: options.tokenTypes, grammarName: options.grammarName }); return map2( lookaheadValidationErrorMessages, (errorMessage) => Object.assign({ type: ParserDefinitionErrorType.CUSTOM_LOOKAHEAD_VALIDATION }, errorMessage) ); } function validateGrammar$1(topLevels, tokenTypes, errMsgProvider, grammarName) { const duplicateErrors = flatMap( topLevels, (currTopLevel) => validateDuplicateProductions(currTopLevel, errMsgProvider) ); const termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider); const tooManyAltsErrors = flatMap(topLevels, (curRule) => validateTooManyAlts(curRule, errMsgProvider)); const duplicateRulesError = flatMap( topLevels, (curRule) => validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider) ); return duplicateErrors.concat(termsNamespaceConflictErrors, tooManyAltsErrors, duplicateRulesError); } function validateDuplicateProductions(topLevelRule, errMsgProvider) { const collectorVisitor2 = new OccurrenceValidationCollector(); topLevelRule.accept(collectorVisitor2); const allRuleProductions = collectorVisitor2.allProductions; const productionGroups = groupBy$1(allRuleProductions, identifyProductionForDuplicates); const duplicates = pickBy(productionGroups, (currGroup) => { return currGroup.length > 1; }); const errors = map2(values(duplicates), (currDuplicates) => { const firstProd = head(currDuplicates); const msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates); const dslName = getProductionDslName(firstProd); const defError = { message: msg, type: ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, ruleName: topLevelRule.name, dslName, occurrence: firstProd.idx }; const param = getExtraProductionArgument(firstProd); if (param) { defError.parameter = param; } return defError; }); return errors; } function identifyProductionForDuplicates(prod) { return `${getProductionDslName(prod)}_#_${prod.idx}_#_${getExtraProductionArgument(prod)}`; } function getExtraProductionArgument(prod) { if (prod instanceof Terminal) { return prod.terminalType.name; } else if (prod instanceof NonTerminal) { return prod.nonTerminalName; } else { return ""; } } class OccurrenceValidationCollector extends GAstVisitor { constructor() { super(...arguments); this.allProductions = []; } visitNonTerminal(subrule) { this.allProductions.push(subrule); } visitOption(option) { this.allProductions.push(option); } visitRepetitionWithSeparator(manySep) { this.allProductions.push(manySep); } visitRepetitionMandatory(atLeastOne) { this.allProductions.push(atLeastOne); } visitRepetitionMandatoryWithSeparator(atLeastOneSep) { this.allProductions.push(atLeastOneSep); } visitRepetition(many) { this.allProductions.push(many); } visitAlternation(or) { this.allProductions.push(or); } visitTerminal(terminal) { this.allProductions.push(terminal); } } function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) { const errors = []; const occurrences = reduce2( allRules, (result, curRule) => { if (curRule.name === rule.name) { return result + 1; } return result; }, 0 ); if (occurrences > 1) { const errMsg = errMsgProvider.buildDuplicateRuleNameError({ topLevelRule: rule, grammarName: className }); errors.push({ message: errMsg, type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: rule.name }); } return errors; } function validateRuleIsOverridden(ruleName, definedRulesNames, className) { const errors = []; let errMsg; if (!includes(definedRulesNames, ruleName)) { errMsg = `Invalid rule override, rule: ->${ruleName}<- cannot be overridden in the grammar: ->${className}<-as it is not defined in any of the super grammars `; errors.push({ message: errMsg, type: ParserDefinitionErrorType.INVALID_RULE_OVERRIDE, ruleName }); } return errors; } function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path = []) { const errors = []; const nextNonTerminals = getFirstNoneTerminal(currRule.definition); if (isEmpty(nextNonTerminals)) { return []; } else { const ruleName = topRule.name; const foundLeftRecursion = includes(nextNonTerminals, topRule); if (foundLeftRecursion) { errors.push({ message: errMsgProvider.buildLeftRecursionError({ topLevelRule: topRule, leftRecursionPath: path }), type: ParserDefinitionErrorType.LEFT_RECURSION, ruleName }); } const validNextSteps = difference$1(nextNonTerminals, path.concat([topRule])); const errorsFromNextSteps = flatMap(validNextSteps, (currRefRule) => { const newPath = clone2(path); newPath.push(currRefRule); return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath); }); return errors.concat(errorsFromNextSteps); } } function getFirstNoneTerminal(definition) { let result = []; if (isEmpty(definition)) { return result; } const firstProd = head(definition); if (firstProd instanceof NonTerminal) { result.push(firstProd.referencedRule); } else if (firstProd instanceof Alternative || firstProd instanceof Option || firstProd instanceof RepetitionMandatory || firstProd instanceof RepetitionMandatoryWithSeparator || firstProd instanceof RepetitionWithSeparator || firstProd instanceof Repetition) { result = result.concat(getFirstNoneTerminal(firstProd.definition)); } else if (firstProd instanceof Alternation) { result = flatten(map2(firstProd.definition, (currSubDef) => getFirstNoneTerminal(currSubDef.definition))); } else if (firstProd instanceof Terminal) ; else { throw Error("non exhaustive match"); } const isFirstOptional = isOptionalProd(firstProd); const hasMore = definition.length > 1; if (isFirstOptional && hasMore) { const rest = drop(definition); return result.concat(getFirstNoneTerminal(rest)); } else { return result; } } class OrCollector extends GAstVisitor { constructor() { super(...arguments); this.alternations = []; } visitAlternation(node) { this.alternations.push(node); } } function validateEmptyOrAlternative(topLevelRule, errMsgProvider) { const orCollector = new OrCollector(); topLevelRule.accept(orCollector); const ors = orCollector.alternations; const errors = flatMap(ors, (currOr) => { const exceptLast = dropRight(currOr.definition); return flatMap(exceptLast, (currAlternative, currAltIdx) => { const possibleFirstInAlt = nextPossibleTokensAfter([currAlternative], [], tokenStructuredMatcher, 1); if (isEmpty(possibleFirstInAlt)) { return [ { message: errMsgProvider.buildEmptyAlternationError({ topLevelRule, alternation: currOr, emptyChoiceIdx: currAltIdx }), type: ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, ruleName: topLevelRule.name, occurrence: currOr.idx, alternative: currAltIdx + 1 } ]; } else { return []; } }); }); return errors; } function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, errMsgProvider) { const orCollector = new OrCollector(); topLevelRule.accept(orCollector); let ors = orCollector.alternations; ors = reject(ors, (currOr) => currOr.ignoreAmbiguities === true); const errors = flatMap(ors, (currOr) => { const currOccurrence = currOr.idx; const actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead; const alternatives = getLookaheadPathsForOr(currOccurrence, topLevelRule, actualMaxLookahead, currOr); const altsAmbiguityErrors = checkAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); const altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities( alternatives, currOr, topLevelRule, errMsgProvider ); return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors); }); return errors; } class RepetitionCollector extends GAstVisitor { constructor() { super(...arguments); this.allProductions = []; } visitRepetitionWithSeparator(manySep) { this.allProductions.push(manySep); } visitRepetitionMandatory(atLeastOne) { this.allProductions.push(atLeastOne); } visitRepetitionMandatoryWithSeparator(atLeastOneSep) { this.allProductions.push(atLeastOneSep); } visitRepetition(many) { this.allProductions.push(many); } } function validateTooManyAlts(topLevelRule, errMsgProvider) { const orCollector = new OrCollector(); topLevelRule.accept(orCollector); const ors = orCollector.alternations; const errors = flatMap(ors, (currOr) => { if (currOr.definition.length > 255) { return [ { message: errMsgProvider.buildTooManyAlternativesError({ topLevelRule, alternation: currOr }), type: ParserDefinitionErrorType.TOO_MANY_ALTS, ruleName: topLevelRule.name, occurrence: currOr.idx } ]; } else { return []; } }); return errors; } function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) { const errors = []; forEach(topLevelRules, (currTopRule) => { const collectorVisitor2 = new RepetitionCollector(); currTopRule.accept(collectorVisitor2); const allRuleProductions = collectorVisitor2.allProductions; forEach(allRuleProductions, (currProd) => { const prodType = getProdType(currProd); const actualMaxLookahead = currProd.maxLookahead || maxLookahead; const currOccurrence = currProd.idx; const paths = getLookaheadPathsForOptionalProd(currOccurrence, currTopRule, prodType, actualMaxLookahead); const pathsInsideProduction = paths[0]; if (isEmpty(flatten(pathsInsideProduction))) { const errMsg = errMsgProvider.buildEmptyRepetitionError({ topLevelRule: currTopRule, repetition: currProd }); errors.push({ message: errMsg, type: ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, ruleName: currTopRule.name }); } }); }); return errors; } function checkAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { const foundAmbiguousPaths = []; const identicalAmbiguities = reduce2( alternatives, (result, currAlt, currAltIdx) => { if (alternation.definition[currAltIdx].ignoreAmbiguities === true) { return result; } forEach(currAlt, (currPath) => { const altsCurrPathAppearsIn = [currAltIdx]; forEach(alternatives, (currOtherAlt, currOtherAltIdx) => { if (currAltIdx !== currOtherAltIdx && containsPath(currOtherAlt, currPath) && // ignore (skip) ambiguities with this "other" alternative alternation.definition[currOtherAltIdx].ignoreAmbiguities !== true) { altsCurrPathAppearsIn.push(currOtherAltIdx); } }); if (altsCurrPathAppearsIn.length > 1 && !containsPath(foundAmbiguousPaths, currPath)) { foundAmbiguousPaths.push(currPath); result.push({ alts: altsCurrPathAppearsIn, path: currPath }); } }); return result; }, [] ); const currErrors = map2(identicalAmbiguities, (currAmbDescriptor) => { const ambgIndices = map2(currAmbDescriptor.alts, (currAltIdx) => currAltIdx + 1); const currMessage = errMsgProvider.buildAlternationAmbiguityError({ topLevelRule: rule, alternation, ambiguityIndices: ambgIndices, prefixPath: currAmbDescriptor.path }); return { message: currMessage, type: ParserDefinitionErrorType.AMBIGUOUS_ALTS, ruleName: rule.name, occurrence: alternation.idx, alternatives: currAmbDescriptor.alts }; }); return currErrors; } function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { const pathsAndIndices = reduce2( alternatives, (result, currAlt, idx) => { const currPathsAndIdx = map2(currAlt, (currPath) => { return { idx, path: currPath }; }); return result.concat(currPathsAndIdx); }, [] ); const errors = compact( flatMap(pathsAndIndices, (currPathAndIdx) => { const alternativeGast = alternation.definition[currPathAndIdx.idx]; if (alternativeGast.ignoreAmbiguities === true) { return []; } const targetIdx = currPathAndIdx.idx; const targetPath = currPathAndIdx.path; const prefixAmbiguitiesPathsAndIndices = filter(pathsAndIndices, (searchPathAndIdx) => { return ( // ignore (skip) ambiguities with this "other" alternative alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities !== true && searchPathAndIdx.idx < targetIdx && // checking for strict prefix because identical lookaheads // will be be detected using a different validation. isStrictPrefixOfPath(searchPathAndIdx.path, targetPath) ); }); const currPathPrefixErrors = map2(prefixAmbiguitiesPathsAndIndices, (currAmbPathAndIdx) => { const ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1]; const occurrence = alternation.idx === 0 ? "" : alternation.idx; const message = errMsgProvider.buildAlternationPrefixAmbiguityError({ topLevelRule: rule, alternation, ambiguityIndices: ambgIndices, prefixPath: currAmbPathAndIdx.path }); return { message, type: ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, ruleName: rule.name, occurrence, alternatives: ambgIndices }; }); return currPathPrefixErrors; }) ); return errors; } function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) { const errors = []; const tokenNames = map2(tokenTypes, (currToken) => currToken.name); forEach(topLevels, (currRule) => { const currRuleName = currRule.name; if (includes(tokenNames, currRuleName)) { const errMsg = errMsgProvider.buildNamespaceConflictError(currRule); errors.push({ message: errMsg, type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, ruleName: currRuleName }); } }); return errors; } function resolveGrammar(options) { const actualOptions = defaults$1(options, { errMsgProvider: defaultGrammarResolverErrorProvider }); const topRulesTable = {}; forEach(options.rules, (rule) => { topRulesTable[rule.name] = rule; }); return resolveGrammar$1(topRulesTable, actualOptions.errMsgProvider); } function validateGrammar(options) { options = defaults$1(options, { errMsgProvider: defaultGrammarValidatorErrorProvider }); return validateGrammar$1(options.rules, options.tokenTypes, options.errMsgProvider, options.grammarName); } const MISMATCHED_TOKEN_EXCEPTION = "MismatchedTokenException"; const NO_VIABLE_ALT_EXCEPTION = "NoViableAltException"; const EARLY_EXIT_EXCEPTION = "EarlyExitException"; const NOT_ALL_INPUT_PARSED_EXCEPTION = "NotAllInputParsedException"; const RECOGNITION_EXCEPTION_NAMES = [ MISMATCHED_TOKEN_EXCEPTION, NO_VIABLE_ALT_EXCEPTION, EARLY_EXIT_EXCEPTION, NOT_ALL_INPUT_PARSED_EXCEPTION ]; Object.freeze(RECOGNITION_EXCEPTION_NAMES); function isRecognitionException(error) { return includes(RECOGNITION_EXCEPTION_NAMES, error.name); } class RecognitionException extends Error { constructor(message, token) { super(message); this.token = token; this.resyncedTokens = []; Object.setPrototypeOf(this, new.target.prototype); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } } class MismatchedTokenException extends RecognitionException { constructor(message, token, previousToken) { super(message, token); this.previousToken = previousToken; this.name = MISMATCHED_TOKEN_EXCEPTION; } } class NoViableAltException extends RecognitionException { constructor(message, token, previousToken) { super(message, token); this.previousToken = previousToken; this.name = NO_VIABLE_ALT_EXCEPTION; } } class NotAllInputParsedException extends RecognitionException { constructor(message, token) { super(message, token); this.name = NOT_ALL_INPUT_PARSED_EXCEPTION; } } class EarlyExitException extends RecognitionException { constructor(message, token, previousToken) { super(message, token); this.previousToken = previousToken; this.name = EARLY_EXIT_EXCEPTION; } } const EOF_FOLLOW_KEY = {}; const IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException"; class InRuleRecoveryException extends Error { constructor(message) { super(message); this.name = IN_RULE_RECOVERY_EXCEPTION; } } class Recoverable { initRecoverable(config) { this.firstAfterRepMap = {}; this.resyncFollows = {}; this.recoveryEnabled = has(config, "recoveryEnabled") ? config.recoveryEnabled : DEFAULT_PARSER_CONFIG.recoveryEnabled; if (this.recoveryEnabled) { this.attemptInRepetitionRecovery = attemptInRepetitionRecovery; } } getTokenToInsert(tokType) { const tokToInsert = createTokenInstance(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN); tokToInsert.isInsertedInRecovery = true; return tokToInsert; } canTokenTypeBeInsertedInRecovery(tokType) { return true; } canTokenTypeBeDeletedInRecovery(tokType) { return true; } tryInRepetitionRecovery(grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) { const reSyncTokType = this.findReSyncTokenType(); const savedLexerState = this.exportLexerState(); const resyncedTokens = []; let passedResyncPoint = false; const nextTokenWithoutResync = this.LA(1); let currToken = this.LA(1); const generateErrorMessage = () => { const previousToken = this.LA(0); const msg = this.errorMessageProvider.buildMismatchTokenMessage({ expected: expectedTokType, actual: nextTokenWithoutResync, previous: previousToken, ruleName: this.getCurrRuleFullName() }); const error = new MismatchedTokenException(msg, nextTokenWithoutResync, this.LA(0)); error.resyncedTokens = dropRight(resyncedTokens); this.SAVE_ERROR(error); }; while (!passedResyncPoint) { if (this.tokenMatcher(currToken, expectedTokType)) { generateErrorMessage(); return; } else if (lookAheadFunc.call(this)) { generateErrorMessage(); grammarRule.apply(this, grammarRuleArgs); return; } else if (this.tokenMatcher(currToken, reSyncTokType)) { passedResyncPoint = true; } else { currToken = this.SKIP_TOKEN(); this.addToResyncTokens(currToken, resyncedTokens); } } this.importLexerState(savedLexerState); } shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck) { if (notStuck === false) { return false; } if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) { return false; } if (this.isBackTracking()) { return false; } if (this.canPerformInRuleRecovery( expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx) )) { return false; } return true; } // Error Recovery functionality getFollowsForInRuleRecovery(tokType, tokIdxInRule) { const grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule); const follows = this.getNextPossibleTokenTypes(grammarPath); return follows; } tryInRuleRecovery(expectedTokType, follows) { if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) { const tokToInsert = this.getTokenToInsert(expectedTokType); return tokToInsert; } if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) { const nextTok = this.SKIP_TOKEN(); this.consumeToken(); return nextTok; } throw new InRuleRecoveryException("sad sad panda"); } canPerformInRuleRecovery(expectedToken, follows) { return this.canRecoverWithSingleTokenInsertion(expectedToken, follows) || this.canRecoverWithSingleTokenDeletion(expectedToken); } canRecoverWithSingleTokenInsertion(expectedTokType, follows) { if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) { return false; } if (isEmpty(follows)) { return false; } const mismatchedTok = this.LA(1); const isMisMatchedTokInFollows = find$1(follows, (possibleFollowsTokType) => { return this.tokenMatcher(mismatchedTok, possibleFollowsTokType); }) !== void 0; return isMisMatchedTokInFollows; } canRecoverWithSingleTokenDeletion(expectedTokType) { if (!this.canTokenTypeBeDeletedInRecovery(expectedTokType)) { return false; } const isNextTokenWhatIsExpected = this.tokenMatcher(this.LA(2), expectedTokType); return isNextTokenWhatIsExpected; } isInCurrentRuleReSyncSet(tokenTypeIdx) { const followKey = this.getCurrFollowKey(); const currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey); return includes(currentRuleReSyncSet, tokenTypeIdx); } findReSyncTokenType() { const allPossibleReSyncTokTypes = this.flattenFollowSet(); let nextToken = this.LA(1); let k = 2; while (true) { const foundMatch = find$1(allPossibleReSyncTokTypes, (resyncTokType) => { const canMatch = tokenMatcher(nextToken, resyncTokType); return canMatch; }); if (foundMatch !== void 0) { return foundMatch; } nextToken = this.LA(k); k++; } } getCurrFollowKey() { if (this.RULE_STACK.length === 1) { return EOF_FOLLOW_KEY; } const currRuleShortName = this.getLastExplicitRuleShortName(); const currRuleIdx = this.getLastExplicitRuleOccurrenceIndex(); const prevRuleShortName = this.getPreviousExplicitRuleShortName(); return { ruleName: this.shortRuleNameToFullName(currRuleShortName), idxInCallingRule: currRuleIdx, inRule: this.shortRuleNameToFullName(prevRuleShortName) }; } buildFullFollowKeyStack() { const explicitRuleStack = this.RULE_STACK; const explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK; return map2(explicitRuleStack, (ruleName, idx) => { if (idx === 0) { return EOF_FOLLOW_KEY; } return { ruleName: this.shortRuleNameToFullName(ruleName), idxInCallingRule: explicitOccurrenceStack[idx], inRule: this.shortRuleNameToFullName(explicitRuleStack[idx - 1]) }; }); } flattenFollowSet() { const followStack = map2(this.buildFullFollowKeyStack(), (currKey) => { return this.getFollowSetFromFollowKey(currKey); }); return flatten(followStack); } getFollowSetFromFollowKey(followKey) { if (followKey === EOF_FOLLOW_KEY) { return [EOF]; } const followName = followKey.ruleName + followKey.idxInCallingRule + IN + followKey.inRule; return this.resyncFollows[followName]; } // It does not make any sense to include a virtual EOF token in the list of resynced tokens // as EOF does not really exist and thus does not contain any useful information (line/column numbers) addToResyncTokens(token, resyncTokens) { if (!this.tokenMatcher(token, EOF)) { resyncTokens.push(token); } return resyncTokens; } reSyncTo(tokType) { const resyncedTokens = []; let nextTok = this.LA(1); while (this.tokenMatcher(nextTok, tokType) === false) { nextTok = this.SKIP_TOKEN(); this.addToResyncTokens(nextTok, resyncedTokens); } return dropRight(resyncedTokens); } attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { } getCurrentGrammarPath(tokType, tokIdxInRule) { const pathRuleStack = this.getHumanReadableRuleStack(); const pathOccurrenceStack = clone2(this.RULE_OCCURRENCE_STACK); const grammarPath = { ruleStack: pathRuleStack, occurrenceStack: pathOccurrenceStack, lastTok: tokType, lastTokOccurrence: tokIdxInRule }; return grammarPath; } getHumanReadableRuleStack() { return map2(this.RULE_STACK, (currShortName) => this.shortRuleNameToFullName(currShortName)); } } function attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { const key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence); let firstAfterRepInfo = this.firstAfterRepMap[key]; if (firstAfterRepInfo === void 0) { const currRuleName = this.getCurrRuleFullName(); const ruleGrammar = this.getGAstProductions()[currRuleName]; const walker = new nextToksWalker(ruleGrammar, prodOccurrence); firstAfterRepInfo = walker.startWalking(); this.firstAfterRepMap[key] = firstAfterRepInfo; } let expectTokAfterLastMatch = firstAfterRepInfo.token; let nextTokIdx = firstAfterRepInfo.occurrence; const isEndOfRule = firstAfterRepInfo.isEndOfRule; if (this.RULE_STACK.length === 1 && isEndOfRule && expectTokAfterLastMatch === void 0) { expectTokAfterLastMatch = EOF; nextTokIdx = 1; } if (expectTokAfterLastMatch === void 0 || nextTokIdx === void 0) { return; } if (this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck)) { this.tryInRepetitionRecovery(prodFunc, args, lookaheadFunc, expectTokAfterLastMatch); } } const BITS_FOR_METHOD_TYPE = 4; const BITS_FOR_OCCURRENCE_IDX = 8; const OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX; const OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX; const MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX; const AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX; const MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX; const AT_LEAST_ONE_SEP_IDX = 6 << BITS_FOR_OCCURRENCE_IDX; function getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) { return occurrence | dslMethodIdx | ruleIdx; } class LLkLookaheadStrategy { constructor(options) { var _a3; this.maxLookahead = (_a3 = options === null || options === void 0 ? void 0 : options.maxLookahead) !== null && _a3 !== void 0 ? _a3 : DEFAULT_PARSER_CONFIG.maxLookahead; } validate(options) { const leftRecursionErrors = this.validateNoLeftRecursion(options.rules); if (isEmpty(leftRecursionErrors)) { const emptyAltErrors = this.validateEmptyOrAlternatives(options.rules); const ambiguousAltsErrors = this.validateAmbiguousAlternationAlternatives(options.rules, this.maxLookahead); const emptyRepetitionErrors = this.validateSomeNonEmptyLookaheadPath(options.rules, this.maxLookahead); const allErrors = [...leftRecursionErrors, ...emptyAltErrors, ...ambiguousAltsErrors, ...emptyRepetitionErrors]; return allErrors; } return leftRecursionErrors; } validateNoLeftRecursion(rules) { return flatMap( rules, (currTopRule) => validateNoLeftRecursion(currTopRule, currTopRule, defaultGrammarValidatorErrorProvider) ); } validateEmptyOrAlternatives(rules) { return flatMap( rules, (currTopRule) => validateEmptyOrAlternative(currTopRule, defaultGrammarValidatorErrorProvider) ); } validateAmbiguousAlternationAlternatives(rules, maxLookahead) { return flatMap( rules, (currTopRule) => validateAmbiguousAlternationAlternatives(currTopRule, maxLookahead, defaultGrammarValidatorErrorProvider) ); } validateSomeNonEmptyLookaheadPath(rules, maxLookahead) { return validateSomeNonEmptyLookaheadPath(rules, maxLookahead, defaultGrammarValidatorErrorProvider); } buildLookaheadForAlternation(options) { return buildLookaheadFuncForOr( options.prodOccurrence, options.rule, options.maxLookahead, options.hasPredicates, options.dynamicTokensEnabled, buildAlternativesLookAheadFunc ); } buildLookaheadForOptional(options) { return buildLookaheadFuncForOptionalProd( options.prodOccurrence, options.rule, options.maxLookahead, options.dynamicTokensEnabled, getProdType(options.prodType), buildSingleAlternativeLookaheadFunction ); } } class LooksAhead { initLooksAhead(config) { this.dynamicTokensEnabled = has(config, "dynamicTokensEnabled") ? config.dynamicTokensEnabled : DEFAULT_PARSER_CONFIG.dynamicTokensEnabled; this.maxLookahead = has(config, "maxLookahead") ? config.maxLookahead : DEFAULT_PARSER_CONFIG.maxLookahead; this.lookaheadStrategy = has(config, "lookaheadStrategy") ? config.lookaheadStrategy : new LLkLookaheadStrategy({ maxLookahead: this.maxLookahead }); this.lookAheadFuncsCache = /* @__PURE__ */ new Map(); } preComputeLookaheadFunctions(rules) { forEach(rules, (currRule) => { this.TRACE_INIT(`${currRule.name} Rule Lookahead`, () => { const { alternation, repetition, option, repetitionMandatory, repetitionMandatoryWithSeparator, repetitionWithSeparator } = collectMethods(currRule); forEach(alternation, (currProd) => { const prodIdx = currProd.idx === 0 ? "" : currProd.idx; this.TRACE_INIT(`${getProductionDslName(currProd)}${prodIdx}`, () => { const laFunc = this.lookaheadStrategy.buildLookaheadForAlternation({ prodOccurrence: currProd.idx, rule: currRule, maxLookahead: currProd.maxLookahead || this.maxLookahead, hasPredicates: currProd.hasPredicates, dynamicTokensEnabled: this.dynamicTokensEnabled }); const key = getKeyForAutomaticLookahead(this.fullRuleNameToShort[currRule.name], OR_IDX, currProd.idx); this.setLaFuncCache(key, laFunc); }); }); forEach(repetition, (currProd) => { this.computeLookaheadFunc( currRule, currProd.idx, MANY_IDX, "Repetition", currProd.maxLookahead, getProductionDslName(currProd) ); }); forEach(option, (currProd) => { this.computeLookaheadFunc( currRule, currProd.idx, OPTION_IDX, "Option", currProd.maxLookahead, getProductionDslName(currProd) ); }); forEach(repetitionMandatory, (currProd) => { this.computeLookaheadFunc( currRule, currProd.idx, AT_LEAST_ONE_IDX, "RepetitionMandatory", currProd.maxLookahead, getProductionDslName(currProd) ); }); forEach(repetitionMandatoryWithSeparator, (currProd) => { this.computeLookaheadFunc( currRule, currProd.idx, AT_LEAST_ONE_SEP_IDX, "RepetitionMandatoryWithSeparator", currProd.maxLookahead, getProductionDslName(currProd) ); }); forEach(repetitionWithSeparator, (currProd) => { this.computeLookaheadFunc( currRule, currProd.idx, MANY_SEP_IDX, "RepetitionWithSeparator", currProd.maxLookahead, getProductionDslName(currProd) ); }); }); }); } computeLookaheadFunc(rule, prodOccurrence, prodKey, prodType, prodMaxLookahead, dslMethodName) { this.TRACE_INIT(`${dslMethodName}${prodOccurrence === 0 ? "" : prodOccurrence}`, () => { const laFunc = this.lookaheadStrategy.buildLookaheadForOptional({ prodOccurrence, rule, maxLookahead: prodMaxLookahead || this.maxLookahead, dynamicTokensEnabled: this.dynamicTokensEnabled, prodType }); const key = getKeyForAutomaticLookahead(this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence); this.setLaFuncCache(key, laFunc); }); } // this actually returns a number, but it is always used as a string (object prop key) getKeyForAutomaticLookahead(dslMethodIdx, occurrence) { const currRuleShortName = this.getLastExplicitRuleShortName(); return getKeyForAutomaticLookahead(currRuleShortName, dslMethodIdx, occurrence); } getLaFuncFromCache(key) { return this.lookAheadFuncsCache.get(key); } /* istanbul ignore next */ setLaFuncCache(key, value) { this.lookAheadFuncsCache.set(key, value); } } class DslMethodsCollectorVisitor extends GAstVisitor { constructor() { super(...arguments); this.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }; } reset() { this.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }; } visitOption(option) { this.dslMethods.option.push(option); } visitRepetitionWithSeparator(manySep) { this.dslMethods.repetitionWithSeparator.push(manySep); } visitRepetitionMandatory(atLeastOne) { this.dslMethods.repetitionMandatory.push(atLeastOne); } visitRepetitionMandatoryWithSeparator(atLeastOneSep) { this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep); } visitRepetition(many) { this.dslMethods.repetition.push(many); } visitAlternation(or) { this.dslMethods.alternation.push(or); } } const collectorVisitor = new DslMethodsCollectorVisitor(); function collectMethods(rule) { collectorVisitor.reset(); rule.accept(collectorVisitor); const dslMethods = collectorVisitor.dslMethods; collectorVisitor.reset(); return dslMethods; } function setNodeLocationOnlyOffset(currNodeLocation, newLocationInfo) { if (isNaN(currNodeLocation.startOffset) === true) { currNodeLocation.startOffset = newLocationInfo.startOffset; currNodeLocation.endOffset = newLocationInfo.endOffset; } else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { currNodeLocation.endOffset = newLocationInfo.endOffset; } } function setNodeLocationFull(currNodeLocation, newLocationInfo) { if (isNaN(currNodeLocation.startOffset) === true) { currNodeLocation.startOffset = newLocationInfo.startOffset; currNodeLocation.startColumn = newLocationInfo.startColumn; currNodeLocation.startLine = newLocationInfo.startLine; currNodeLocation.endOffset = newLocationInfo.endOffset; currNodeLocation.endColumn = newLocationInfo.endColumn; currNodeLocation.endLine = newLocationInfo.endLine; } else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { currNodeLocation.endOffset = newLocationInfo.endOffset; currNodeLocation.endColumn = newLocationInfo.endColumn; currNodeLocation.endLine = newLocationInfo.endLine; } } function addTerminalToCst(node, token, tokenTypeName) { if (node.children[tokenTypeName] === void 0) { node.children[tokenTypeName] = [token]; } else { node.children[tokenTypeName].push(token); } } function addNoneTerminalToCst(node, ruleName, ruleResult) { if (node.children[ruleName] === void 0) { node.children[ruleName] = [ruleResult]; } else { node.children[ruleName].push(ruleResult); } } const NAME = "name"; function defineNameProp(obj, nameValue) { Object.defineProperty(obj, NAME, { enumerable: false, configurable: true, writable: false, value: nameValue }); } function defaultVisit(ctx, param) { const childrenNames = keys(ctx); const childrenNamesLength = childrenNames.length; for (let i4 = 0; i4 < childrenNamesLength; i4++) { const currChildName = childrenNames[i4]; const currChildArray = ctx[currChildName]; const currChildArrayLength = currChildArray.length; for (let j = 0; j < currChildArrayLength; j++) { const currChild = currChildArray[j]; if (currChild.tokenTypeIdx === void 0) { this[currChild.name](currChild.children, param); } } } } function createBaseSemanticVisitorConstructor(grammarName, ruleNames) { const derivedConstructor = function() { }; defineNameProp(derivedConstructor, grammarName + "BaseSemantics"); const semanticProto = { visit: function(cstNode, param) { if (isArray$1(cstNode)) { cstNode = cstNode[0]; } if (isUndefined(cstNode)) { return void 0; } return this[cstNode.name](cstNode.children, param); }, validateVisitor: function() { const semanticDefinitionErrors = validateVisitor(this, ruleNames); if (!isEmpty(semanticDefinitionErrors)) { const errorMessages = map2(semanticDefinitionErrors, (currDefError) => currDefError.msg); throw Error( `Errors Detected in CST Visitor <${this.constructor.name}>: ${errorMessages.join("\n\n").replace(/\n/g, "\n ")}` ); } } }; derivedConstructor.prototype = semanticProto; derivedConstructor.prototype.constructor = derivedConstructor; derivedConstructor._RULE_NAMES = ruleNames; return derivedConstructor; } function createBaseVisitorConstructorWithDefaults(grammarName, ruleNames, baseConstructor) { const derivedConstructor = function() { }; defineNameProp(derivedConstructor, grammarName + "BaseSemanticsWithDefaults"); const withDefaultsProto = Object.create(baseConstructor.prototype); forEach(ruleNames, (ruleName) => { withDefaultsProto[ruleName] = defaultVisit; }); derivedConstructor.prototype = withDefaultsProto; derivedConstructor.prototype.constructor = derivedConstructor; return derivedConstructor; } var CstVisitorDefinitionError; (function(CstVisitorDefinitionError2) { CstVisitorDefinitionError2[CstVisitorDefinitionError2["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD"; CstVisitorDefinitionError2[CstVisitorDefinitionError2["MISSING_METHOD"] = 1] = "MISSING_METHOD"; })(CstVisitorDefinitionError || (CstVisitorDefinitionError = {})); function validateVisitor(visitorInstance, ruleNames) { const missingErrors = validateMissingCstMethods(visitorInstance, ruleNames); return missingErrors; } function validateMissingCstMethods(visitorInstance, ruleNames) { const missingRuleNames = filter(ruleNames, (currRuleName) => { return isFunction3(visitorInstance[currRuleName]) === false; }); const errors = map2(missingRuleNames, (currRuleName) => { return { msg: `Missing visitor method: <${currRuleName}> on ${visitorInstance.constructor.name} CST Visitor.`, type: CstVisitorDefinitionError.MISSING_METHOD, methodName: currRuleName }; }); return compact(errors); } class TreeBuilder { initTreeBuilder(config) { this.CST_STACK = []; this.outputCst = config.outputCst; this.nodeLocationTracking = has(config, "nodeLocationTracking") ? config.nodeLocationTracking : DEFAULT_PARSER_CONFIG.nodeLocationTracking; if (!this.outputCst) { this.cstInvocationStateUpdate = noop2; this.cstFinallyStateUpdate = noop2; this.cstPostTerminal = noop2; this.cstPostNonTerminal = noop2; this.cstPostRule = noop2; } else { if (/full/i.test(this.nodeLocationTracking)) { if (this.recoveryEnabled) { this.setNodeLocationFromToken = setNodeLocationFull; this.setNodeLocationFromNode = setNodeLocationFull; this.cstPostRule = noop2; this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery; } else { this.setNodeLocationFromToken = noop2; this.setNodeLocationFromNode = noop2; this.cstPostRule = this.cstPostRuleFull; this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular; } } else if (/onlyOffset/i.test(this.nodeLocationTracking)) { if (this.recoveryEnabled) { this.setNodeLocationFromToken = setNodeLocationOnlyOffset; this.setNodeLocationFromNode = setNodeLocationOnlyOffset; this.cstPostRule = noop2; this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery; } else { this.setNodeLocationFromToken = noop2; this.setNodeLocationFromNode = noop2; this.cstPostRule = this.cstPostRuleOnlyOffset; this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular; } } else if (/none/i.test(this.nodeLocationTracking)) { this.setNodeLocationFromToken = noop2; this.setNodeLocationFromNode = noop2; this.cstPostRule = noop2; this.setInitialNodeLocation = noop2; } else { throw Error(`Invalid config option: "${config.nodeLocationTracking}"`); } } } setInitialNodeLocationOnlyOffsetRecovery(cstNode) { cstNode.location = { startOffset: NaN, endOffset: NaN }; } setInitialNodeLocationOnlyOffsetRegular(cstNode) { cstNode.location = { // without error recovery the starting Location of a new CstNode is guaranteed // To be the next Token's startOffset (for valid inputs). // For invalid inputs there won't be any CSTOutput so this potential // inaccuracy does not matter startOffset: this.LA(1).startOffset, endOffset: NaN }; } setInitialNodeLocationFullRecovery(cstNode) { cstNode.location = { startOffset: NaN, startLine: NaN, startColumn: NaN, endOffset: NaN, endLine: NaN, endColumn: NaN }; } /** * @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work * @param cstNode */ setInitialNodeLocationFullRegular(cstNode) { const nextToken = this.LA(1); cstNode.location = { startOffset: nextToken.startOffset, startLine: nextToken.startLine, startColumn: nextToken.startColumn, endOffset: NaN, endLine: NaN, endColumn: NaN }; } cstInvocationStateUpdate(fullRuleName) { const cstNode = { name: fullRuleName, children: /* @__PURE__ */ Object.create(null) }; this.setInitialNodeLocation(cstNode); this.CST_STACK.push(cstNode); } cstFinallyStateUpdate() { this.CST_STACK.pop(); } cstPostRuleFull(ruleCstNode) { const prevToken = this.LA(0); const loc = ruleCstNode.location; if (loc.startOffset <= prevToken.startOffset === true) { loc.endOffset = prevToken.endOffset; loc.endLine = prevToken.endLine; loc.endColumn = prevToken.endColumn; } else { loc.startOffset = NaN; loc.startLine = NaN; loc.startColumn = NaN; } } cstPostRuleOnlyOffset(ruleCstNode) { const prevToken = this.LA(0); const loc = ruleCstNode.location; if (loc.startOffset <= prevToken.startOffset === true) { loc.endOffset = prevToken.endOffset; } else { loc.startOffset = NaN; } } cstPostTerminal(key, consumedToken) { const rootCst = this.CST_STACK[this.CST_STACK.length - 1]; addTerminalToCst(rootCst, consumedToken, key); this.setNodeLocationFromToken(rootCst.location, consumedToken); } cstPostNonTerminal(ruleCstResult, ruleName) { const preCstNode = this.CST_STACK[this.CST_STACK.length - 1]; addNoneTerminalToCst(preCstNode, ruleName, ruleCstResult); this.setNodeLocationFromNode(preCstNode.location, ruleCstResult.location); } getBaseCstVisitorConstructor() { if (isUndefined(this.baseCstVisitorConstructor)) { const newBaseCstVisitorConstructor = createBaseSemanticVisitorConstructor( this.className, keys(this.gastProductionsCache) ); this.baseCstVisitorConstructor = newBaseCstVisitorConstructor; return newBaseCstVisitorConstructor; } return this.baseCstVisitorConstructor; } getBaseCstVisitorConstructorWithDefaults() { if (isUndefined(this.baseCstVisitorWithDefaultsConstructor)) { const newConstructor = createBaseVisitorConstructorWithDefaults( this.className, keys(this.gastProductionsCache), this.getBaseCstVisitorConstructor() ); this.baseCstVisitorWithDefaultsConstructor = newConstructor; return newConstructor; } return this.baseCstVisitorWithDefaultsConstructor; } getLastExplicitRuleShortName() { const ruleStack = this.RULE_STACK; return ruleStack[ruleStack.length - 1]; } getPreviousExplicitRuleShortName() { const ruleStack = this.RULE_STACK; return ruleStack[ruleStack.length - 2]; } getLastExplicitRuleOccurrenceIndex() { const occurrenceStack = this.RULE_OCCURRENCE_STACK; return occurrenceStack[occurrenceStack.length - 1]; } } class LexerAdapter { initLexerAdapter() { this.tokVector = []; this.tokVectorLength = 0; this.currIdx = -1; } set input(newInput) { if (this.selfAnalysisDone !== true) { throw Error(`Missing invocation at the end of the Parser's constructor.`); } this.reset(); this.tokVector = newInput; this.tokVectorLength = newInput.length; } get input() { return this.tokVector; } // skips a token and returns the next token SKIP_TOKEN() { if (this.currIdx <= this.tokVector.length - 2) { this.consumeToken(); return this.LA(1); } else { return END_OF_FILE; } } // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers // or lexers dependent on parser context. LA(howMuch) { const soughtIdx = this.currIdx + howMuch; if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) { return END_OF_FILE; } else { return this.tokVector[soughtIdx]; } } consumeToken() { this.currIdx++; } exportLexerState() { return this.currIdx; } importLexerState(newState) { this.currIdx = newState; } resetLexerState() { this.currIdx = -1; } moveToTerminatedState() { this.currIdx = this.tokVector.length - 1; } getLexerPosition() { return this.exportLexerState(); } } class RecognizerApi { ACTION(impl) { return impl.call(this); } consume(idx, tokType, options) { return this.consumeInternal(tokType, idx, options); } subrule(idx, ruleToCall, options) { return this.subruleInternal(ruleToCall, idx, options); } option(idx, actionORMethodDef) { return this.optionInternal(actionORMethodDef, idx); } or(idx, altsOrOpts) { return this.orInternal(altsOrOpts, idx); } many(idx, actionORMethodDef) { return this.manyInternal(idx, actionORMethodDef); } atLeastOne(idx, actionORMethodDef) { return this.atLeastOneInternal(idx, actionORMethodDef); } CONSUME(tokType, options) { return this.consumeInternal(tokType, 0, options); } CONSUME1(tokType, options) { return this.consumeInternal(tokType, 1, options); } CONSUME2(tokType, options) { return this.consumeInternal(tokType, 2, options); } CONSUME3(tokType, options) { return this.consumeInternal(tokType, 3, options); } CONSUME4(tokType, options) { return this.consumeInternal(tokType, 4, options); } CONSUME5(tokType, options) { return this.consumeInternal(tokType, 5, options); } CONSUME6(tokType, options) { return this.consumeInternal(tokType, 6, options); } CONSUME7(tokType, options) { return this.consumeInternal(tokType, 7, options); } CONSUME8(tokType, options) { return this.consumeInternal(tokType, 8, options); } CONSUME9(tokType, options) { return this.consumeInternal(tokType, 9, options); } SUBRULE(ruleToCall, options) { return this.subruleInternal(ruleToCall, 0, options); } SUBRULE1(ruleToCall, options) { return this.subruleInternal(ruleToCall, 1, options); } SUBRULE2(ruleToCall, options) { return this.subruleInternal(ruleToCall, 2, options); } SUBRULE3(ruleToCall, options) { return this.subruleInternal(ruleToCall, 3, options); } SUBRULE4(ruleToCall, options) { return this.subruleInternal(ruleToCall, 4, options); } SUBRULE5(ruleToCall, options) { return this.subruleInternal(ruleToCall, 5, options); } SUBRULE6(ruleToCall, options) { return this.subruleInternal(ruleToCall, 6, options); } SUBRULE7(ruleToCall, options) { return this.subruleInternal(ruleToCall, 7, options); } SUBRULE8(ruleToCall, options) { return this.subruleInternal(ruleToCall, 8, options); } SUBRULE9(ruleToCall, options) { return this.subruleInternal(ruleToCall, 9, options); } OPTION(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 0); } OPTION1(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 1); } OPTION2(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 2); } OPTION3(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 3); } OPTION4(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 4); } OPTION5(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 5); } OPTION6(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 6); } OPTION7(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 7); } OPTION8(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 8); } OPTION9(actionORMethodDef) { return this.optionInternal(actionORMethodDef, 9); } OR(altsOrOpts) { return this.orInternal(altsOrOpts, 0); } OR1(altsOrOpts) { return this.orInternal(altsOrOpts, 1); } OR2(altsOrOpts) { return this.orInternal(altsOrOpts, 2); } OR3(altsOrOpts) { return this.orInternal(altsOrOpts, 3); } OR4(altsOrOpts) { return this.orInternal(altsOrOpts, 4); } OR5(altsOrOpts) { return this.orInternal(altsOrOpts, 5); } OR6(altsOrOpts) { return this.orInternal(altsOrOpts, 6); } OR7(altsOrOpts) { return this.orInternal(altsOrOpts, 7); } OR8(altsOrOpts) { return this.orInternal(altsOrOpts, 8); } OR9(altsOrOpts) { return this.orInternal(altsOrOpts, 9); } MANY(actionORMethodDef) { this.manyInternal(0, actionORMethodDef); } MANY1(actionORMethodDef) { this.manyInternal(1, actionORMethodDef); } MANY2(actionORMethodDef) { this.manyInternal(2, actionORMethodDef); } MANY3(actionORMethodDef) { this.manyInternal(3, actionORMethodDef); } MANY4(actionORMethodDef) { this.manyInternal(4, actionORMethodDef); } MANY5(actionORMethodDef) { this.manyInternal(5, actionORMethodDef); } MANY6(actionORMethodDef) { this.manyInternal(6, actionORMethodDef); } MANY7(actionORMethodDef) { this.manyInternal(7, actionORMethodDef); } MANY8(actionORMethodDef) { this.manyInternal(8, actionORMethodDef); } MANY9(actionORMethodDef) { this.manyInternal(9, actionORMethodDef); } MANY_SEP(options) { this.manySepFirstInternal(0, options); } MANY_SEP1(options) { this.manySepFirstInternal(1, options); } MANY_SEP2(options) { this.manySepFirstInternal(2, options); } MANY_SEP3(options) { this.manySepFirstInternal(3, options); } MANY_SEP4(options) { this.manySepFirstInternal(4, options); } MANY_SEP5(options) { this.manySepFirstInternal(5, options); } MANY_SEP6(options) { this.manySepFirstInternal(6, options); } MANY_SEP7(options) { this.manySepFirstInternal(7, options); } MANY_SEP8(options) { this.manySepFirstInternal(8, options); } MANY_SEP9(options) { this.manySepFirstInternal(9, options); } AT_LEAST_ONE(actionORMethodDef) { this.atLeastOneInternal(0, actionORMethodDef); } AT_LEAST_ONE1(actionORMethodDef) { return this.atLeastOneInternal(1, actionORMethodDef); } AT_LEAST_ONE2(actionORMethodDef) { this.atLeastOneInternal(2, actionORMethodDef); } AT_LEAST_ONE3(actionORMethodDef) { this.atLeastOneInternal(3, actionORMethodDef); } AT_LEAST_ONE4(actionORMethodDef) { this.atLeastOneInternal(4, actionORMethodDef); } AT_LEAST_ONE5(actionORMethodDef) { this.atLeastOneInternal(5, actionORMethodDef); } AT_LEAST_ONE6(actionORMethodDef) { this.atLeastOneInternal(6, actionORMethodDef); } AT_LEAST_ONE7(actionORMethodDef) { this.atLeastOneInternal(7, actionORMethodDef); } AT_LEAST_ONE8(actionORMethodDef) { this.atLeastOneInternal(8, actionORMethodDef); } AT_LEAST_ONE9(actionORMethodDef) { this.atLeastOneInternal(9, actionORMethodDef); } AT_LEAST_ONE_SEP(options) { this.atLeastOneSepFirstInternal(0, options); } AT_LEAST_ONE_SEP1(options) { this.atLeastOneSepFirstInternal(1, options); } AT_LEAST_ONE_SEP2(options) { this.atLeastOneSepFirstInternal(2, options); } AT_LEAST_ONE_SEP3(options) { this.atLeastOneSepFirstInternal(3, options); } AT_LEAST_ONE_SEP4(options) { this.atLeastOneSepFirstInternal(4, options); } AT_LEAST_ONE_SEP5(options) { this.atLeastOneSepFirstInternal(5, options); } AT_LEAST_ONE_SEP6(options) { this.atLeastOneSepFirstInternal(6, options); } AT_LEAST_ONE_SEP7(options) { this.atLeastOneSepFirstInternal(7, options); } AT_LEAST_ONE_SEP8(options) { this.atLeastOneSepFirstInternal(8, options); } AT_LEAST_ONE_SEP9(options) { this.atLeastOneSepFirstInternal(9, options); } RULE(name, implementation, config = DEFAULT_RULE_CONFIG) { if (includes(this.definedRulesNames, name)) { const errMsg = defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ topLevelRule: name, grammarName: this.className }); const error = { message: errMsg, type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: name }; this.definitionErrors.push(error); } this.definedRulesNames.push(name); const ruleImplementation = this.defineRule(name, implementation, config); this[name] = ruleImplementation; return ruleImplementation; } OVERRIDE_RULE(name, impl, config = DEFAULT_RULE_CONFIG) { const ruleErrors = validateRuleIsOverridden(name, this.definedRulesNames, this.className); this.definitionErrors = this.definitionErrors.concat(ruleErrors); const ruleImplementation = this.defineRule(name, impl, config); this[name] = ruleImplementation; return ruleImplementation; } BACKTRACK(grammarRule, args) { return function() { this.isBackTrackingStack.push(1); const orgState = this.saveRecogState(); try { grammarRule.apply(this, args); return true; } catch (e2) { if (isRecognitionException(e2)) { return false; } else { throw e2; } } finally { this.reloadRecogState(orgState); this.isBackTrackingStack.pop(); } }; } // GAST export APIs getGAstProductions() { return this.gastProductionsCache; } getSerializedGastProductions() { return serializeGrammar(values(this.gastProductionsCache)); } } class RecognizerEngine { initRecognizerEngine(tokenVocabulary, config) { this.className = this.constructor.name; this.shortRuleNameToFull = {}; this.fullRuleNameToShort = {}; this.ruleShortNameIdx = 256; this.tokenMatcher = tokenStructuredMatcherNoCategories; this.subruleIdx = 0; this.definedRulesNames = []; this.tokensMap = {}; this.isBackTrackingStack = []; this.RULE_STACK = []; this.RULE_OCCURRENCE_STACK = []; this.gastProductionsCache = {}; if (has(config, "serializedGrammar")) { throw Error( "The Parser's configuration can no longer contain a property.\n See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\n For Further details." ); } if (isArray$1(tokenVocabulary)) { if (isEmpty(tokenVocabulary)) { throw Error( "A Token Vocabulary cannot be empty.\n Note that the first argument for the parser constructor\n is no longer a Token vector (since v4.0)." ); } if (typeof tokenVocabulary[0].startOffset === "number") { throw Error( "The Parser constructor no longer accepts a token vector as the first argument.\n See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0\n For Further details." ); } } if (isArray$1(tokenVocabulary)) { this.tokensMap = reduce2( tokenVocabulary, (acc, tokType) => { acc[tokType.name] = tokType; return acc; }, {} ); } else if (has(tokenVocabulary, "modes") && every(flatten(values(tokenVocabulary.modes)), isTokenType)) { const allTokenTypes2 = flatten(values(tokenVocabulary.modes)); const uniqueTokens = uniq(allTokenTypes2); this.tokensMap = reduce2( uniqueTokens, (acc, tokType) => { acc[tokType.name] = tokType; return acc; }, {} ); } else if (isObject(tokenVocabulary)) { this.tokensMap = clone2(tokenVocabulary); } else { throw new Error( " argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition" ); } this.tokensMap["EOF"] = EOF; const allTokenTypes = has(tokenVocabulary, "modes") ? flatten(values(tokenVocabulary.modes)) : values(tokenVocabulary); const noTokenCategoriesUsed = every( allTokenTypes, (tokenConstructor) => isEmpty(tokenConstructor.categoryMatches) ); this.tokenMatcher = noTokenCategoriesUsed ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher; augmentTokenTypes(values(this.tokensMap)); } defineRule(ruleName, impl, config) { if (this.selfAnalysisDone) { throw Error( `Grammar rule <${ruleName}> may not be defined after the 'performSelfAnalysis' method has been called' Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.` ); } const resyncEnabled = has(config, "resyncEnabled") ? config.resyncEnabled : DEFAULT_RULE_CONFIG.resyncEnabled; const recoveryValueFunc = has(config, "recoveryValueFunc") ? config.recoveryValueFunc : DEFAULT_RULE_CONFIG.recoveryValueFunc; const shortName = this.ruleShortNameIdx << BITS_FOR_METHOD_TYPE + BITS_FOR_OCCURRENCE_IDX; this.ruleShortNameIdx++; this.shortRuleNameToFull[shortName] = ruleName; this.fullRuleNameToShort[ruleName] = shortName; let invokeRuleWithTry; if (this.outputCst === true) { invokeRuleWithTry = function invokeRuleWithTry2(...args) { try { this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx); impl.apply(this, args); const cst = this.CST_STACK[this.CST_STACK.length - 1]; this.cstPostRule(cst); return cst; } catch (e2) { return this.invokeRuleCatch(e2, resyncEnabled, recoveryValueFunc); } finally { this.ruleFinallyStateUpdate(); } }; } else { invokeRuleWithTry = function invokeRuleWithTryCst(...args) { try { this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx); return impl.apply(this, args); } catch (e2) { return this.invokeRuleCatch(e2, resyncEnabled, recoveryValueFunc); } finally { this.ruleFinallyStateUpdate(); } }; } const wrappedGrammarRule = Object.assign(invokeRuleWithTry, { ruleName, originalGrammarAction: impl }); return wrappedGrammarRule; } invokeRuleCatch(e2, resyncEnabledConfig, recoveryValueFunc) { const isFirstInvokedRule = this.RULE_STACK.length === 1; const reSyncEnabled = resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled; if (isRecognitionException(e2)) { const recogError = e2; if (reSyncEnabled) { const reSyncTokType = this.findReSyncTokenType(); if (this.isInCurrentRuleReSyncSet(reSyncTokType)) { recogError.resyncedTokens = this.reSyncTo(reSyncTokType); if (this.outputCst) { const partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; partialCstResult.recoveredNode = true; return partialCstResult; } else { return recoveryValueFunc(e2); } } else { if (this.outputCst) { const partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; partialCstResult.recoveredNode = true; recogError.partialCstResult = partialCstResult; } throw recogError; } } else if (isFirstInvokedRule) { this.moveToTerminatedState(); return recoveryValueFunc(e2); } else { throw recogError; } } else { throw e2; } } // Implementation of parsing DSL optionInternal(actionORMethodDef, occurrence) { const key = this.getKeyForAutomaticLookahead(OPTION_IDX, occurrence); return this.optionInternalLogic(actionORMethodDef, occurrence, key); } optionInternalLogic(actionORMethodDef, occurrence, key) { let lookAheadFunc = this.getLaFuncFromCache(key); let action; if (typeof actionORMethodDef !== "function") { action = actionORMethodDef.DEF; const predicate = actionORMethodDef.GATE; if (predicate !== void 0) { const orgLookaheadFunction = lookAheadFunc; lookAheadFunc = () => { return predicate.call(this) && orgLookaheadFunction.call(this); }; } } else { action = actionORMethodDef; } if (lookAheadFunc.call(this) === true) { return action.call(this); } return void 0; } atLeastOneInternal(prodOccurrence, actionORMethodDef) { const laKey = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_IDX, prodOccurrence); return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey); } atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, key) { let lookAheadFunc = this.getLaFuncFromCache(key); let action; if (typeof actionORMethodDef !== "function") { action = actionORMethodDef.DEF; const predicate = actionORMethodDef.GATE; if (predicate !== void 0) { const orgLookaheadFunction = lookAheadFunc; lookAheadFunc = () => { return predicate.call(this) && orgLookaheadFunction.call(this); }; } } else { action = actionORMethodDef; } if (lookAheadFunc.call(this) === true) { let notStuck = this.doSingleRepetition(action); while (lookAheadFunc.call(this) === true && notStuck === true) { notStuck = this.doSingleRepetition(action); } } else { throw this.raiseEarlyExitException(prodOccurrence, PROD_TYPE.REPETITION_MANDATORY, actionORMethodDef.ERR_MSG); } this.attemptInRepetitionRecovery( this.atLeastOneInternal, [prodOccurrence, actionORMethodDef], lookAheadFunc, AT_LEAST_ONE_IDX, prodOccurrence, NextTerminalAfterAtLeastOneWalker ); } atLeastOneSepFirstInternal(prodOccurrence, options) { const laKey = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_SEP_IDX, prodOccurrence); this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey); } atLeastOneSepFirstInternalLogic(prodOccurrence, options, key) { const action = options.DEF; const separator = options.SEP; const firstIterationLookaheadFunc = this.getLaFuncFromCache(key); if (firstIterationLookaheadFunc.call(this) === true) { action.call(this); const separatorLookAheadFunc = () => { return this.tokenMatcher(this.LA(1), separator); }; while (this.tokenMatcher(this.LA(1), separator) === true) { this.CONSUME(separator); action.call(this); } this.attemptInRepetitionRecovery( this.repetitionSepSecondInternal, [prodOccurrence, separator, separatorLookAheadFunc, action, NextTerminalAfterAtLeastOneSepWalker], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, NextTerminalAfterAtLeastOneSepWalker ); } else { throw this.raiseEarlyExitException( prodOccurrence, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG ); } } manyInternal(prodOccurrence, actionORMethodDef) { const laKey = this.getKeyForAutomaticLookahead(MANY_IDX, prodOccurrence); return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey); } manyInternalLogic(prodOccurrence, actionORMethodDef, key) { let lookaheadFunction = this.getLaFuncFromCache(key); let action; if (typeof actionORMethodDef !== "function") { action = actionORMethodDef.DEF; const predicate = actionORMethodDef.GATE; if (predicate !== void 0) { const orgLookaheadFunction = lookaheadFunction; lookaheadFunction = () => { return predicate.call(this) && orgLookaheadFunction.call(this); }; } } else { action = actionORMethodDef; } let notStuck = true; while (lookaheadFunction.call(this) === true && notStuck === true) { notStuck = this.doSingleRepetition(action); } this.attemptInRepetitionRecovery( this.manyInternal, [prodOccurrence, actionORMethodDef], lookaheadFunction, MANY_IDX, prodOccurrence, NextTerminalAfterManyWalker, // The notStuck parameter is only relevant when "attemptInRepetitionRecovery" // is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP] // An infinite loop cannot occur as: // - Either the lookahead is guaranteed to consume something (Single Token Separator) // - AT_LEAST_ONE by definition is guaranteed to consume something (or error out). notStuck ); } manySepFirstInternal(prodOccurrence, options) { const laKey = this.getKeyForAutomaticLookahead(MANY_SEP_IDX, prodOccurrence); this.manySepFirstInternalLogic(prodOccurrence, options, laKey); } manySepFirstInternalLogic(prodOccurrence, options, key) { const action = options.DEF; const separator = options.SEP; const firstIterationLaFunc = this.getLaFuncFromCache(key); if (firstIterationLaFunc.call(this) === true) { action.call(this); const separatorLookAheadFunc = () => { return this.tokenMatcher(this.LA(1), separator); }; while (this.tokenMatcher(this.LA(1), separator) === true) { this.CONSUME(separator); action.call(this); } this.attemptInRepetitionRecovery( this.repetitionSepSecondInternal, [prodOccurrence, separator, separatorLookAheadFunc, action, NextTerminalAfterManySepWalker], separatorLookAheadFunc, MANY_SEP_IDX, prodOccurrence, NextTerminalAfterManySepWalker ); } } repetitionSepSecondInternal(prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker) { while (separatorLookAheadFunc()) { this.CONSUME(separator); action.call(this); } this.attemptInRepetitionRecovery( this.repetitionSepSecondInternal, [prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker ); } doSingleRepetition(action) { const beforeIteration = this.getLexerPosition(); action.call(this); const afterIteration = this.getLexerPosition(); return afterIteration > beforeIteration; } orInternal(altsOrOpts, occurrence) { const laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence); const alts = isArray$1(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF; const laFunc = this.getLaFuncFromCache(laKey); const altIdxToTake = laFunc.call(this, alts); if (altIdxToTake !== void 0) { const chosenAlternative = alts[altIdxToTake]; return chosenAlternative.ALT.call(this); } this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG); } ruleFinallyStateUpdate() { this.RULE_STACK.pop(); this.RULE_OCCURRENCE_STACK.pop(); this.cstFinallyStateUpdate(); if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) { const firstRedundantTok = this.LA(1); const errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({ firstRedundant: firstRedundantTok, ruleName: this.getCurrRuleFullName() }); this.SAVE_ERROR(new NotAllInputParsedException(errMsg, firstRedundantTok)); } } subruleInternal(ruleToCall, idx, options) { let ruleResult; try { const args = options !== void 0 ? options.ARGS : void 0; this.subruleIdx = idx; ruleResult = ruleToCall.apply(this, args); this.cstPostNonTerminal( ruleResult, options !== void 0 && options.LABEL !== void 0 ? options.LABEL : ruleToCall.ruleName ); return ruleResult; } catch (e2) { throw this.subruleInternalError(e2, options, ruleToCall.ruleName); } } subruleInternalError(e2, options, ruleName) { if (isRecognitionException(e2) && e2.partialCstResult !== void 0) { this.cstPostNonTerminal( e2.partialCstResult, options !== void 0 && options.LABEL !== void 0 ? options.LABEL : ruleName ); delete e2.partialCstResult; } throw e2; } consumeInternal(tokType, idx, options) { let consumedToken; try { const nextToken = this.LA(1); if (this.tokenMatcher(nextToken, tokType) === true) { this.consumeToken(); consumedToken = nextToken; } else { this.consumeInternalError(tokType, nextToken, options); } } catch (eFromConsumption) { consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption); } this.cstPostTerminal( options !== void 0 && options.LABEL !== void 0 ? options.LABEL : tokType.name, consumedToken ); return consumedToken; } consumeInternalError(tokType, nextToken, options) { let msg; const previousToken = this.LA(0); if (options !== void 0 && options.ERR_MSG) { msg = options.ERR_MSG; } else { msg = this.errorMessageProvider.buildMismatchTokenMessage({ expected: tokType, actual: nextToken, previous: previousToken, ruleName: this.getCurrRuleFullName() }); } throw this.SAVE_ERROR(new MismatchedTokenException(msg, nextToken, previousToken)); } consumeInternalRecovery(tokType, idx, eFromConsumption) { if (this.recoveryEnabled && // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions? eFromConsumption.name === "MismatchedTokenException" && !this.isBackTracking()) { const follows = this.getFollowsForInRuleRecovery(tokType, idx); try { return this.tryInRuleRecovery(tokType, follows); } catch (eFromInRuleRecovery) { if (eFromInRuleRecovery.name === IN_RULE_RECOVERY_EXCEPTION) { throw eFromConsumption; } else { throw eFromInRuleRecovery; } } } else { throw eFromConsumption; } } saveRecogState() { const savedErrors = this.errors; const savedRuleStack = clone2(this.RULE_STACK); return { errors: savedErrors, lexerState: this.exportLexerState(), RULE_STACK: savedRuleStack, CST_STACK: this.CST_STACK }; } reloadRecogState(newState) { this.errors = newState.errors; this.importLexerState(newState.lexerState); this.RULE_STACK = newState.RULE_STACK; } ruleInvocationStateUpdate(shortName, fullName, idxInCallingRule) { this.RULE_OCCURRENCE_STACK.push(idxInCallingRule); this.RULE_STACK.push(shortName); this.cstInvocationStateUpdate(fullName); } isBackTracking() { return this.isBackTrackingStack.length !== 0; } getCurrRuleFullName() { const shortName = this.getLastExplicitRuleShortName(); return this.shortRuleNameToFull[shortName]; } shortRuleNameToFullName(shortName) { return this.shortRuleNameToFull[shortName]; } isAtEndOfInput() { return this.tokenMatcher(this.LA(1), EOF); } reset() { this.resetLexerState(); this.subruleIdx = 0; this.isBackTrackingStack = []; this.errors = []; this.RULE_STACK = []; this.CST_STACK = []; this.RULE_OCCURRENCE_STACK = []; } } class ErrorHandler { initErrorHandler(config) { this._errors = []; this.errorMessageProvider = has(config, "errorMessageProvider") ? config.errorMessageProvider : DEFAULT_PARSER_CONFIG.errorMessageProvider; } SAVE_ERROR(error) { if (isRecognitionException(error)) { error.context = { ruleStack: this.getHumanReadableRuleStack(), ruleOccurrenceStack: clone2(this.RULE_OCCURRENCE_STACK) }; this._errors.push(error); return error; } else { throw Error("Trying to save an Error which is not a RecognitionException"); } } get errors() { return clone2(this._errors); } set errors(newErrors) { this._errors = newErrors; } // TODO: consider caching the error message computed information raiseEarlyExitException(occurrence, prodType, userDefinedErrMsg) { const ruleName = this.getCurrRuleFullName(); const ruleGrammar = this.getGAstProductions()[ruleName]; const lookAheadPathsPerAlternative = getLookaheadPathsForOptionalProd( occurrence, ruleGrammar, prodType, this.maxLookahead ); const insideProdPaths = lookAheadPathsPerAlternative[0]; const actualTokens = []; for (let i4 = 1; i4 <= this.maxLookahead; i4++) { actualTokens.push(this.LA(i4)); } const msg = this.errorMessageProvider.buildEarlyExitMessage({ expectedIterationPaths: insideProdPaths, actual: actualTokens, previous: this.LA(0), customUserDescription: userDefinedErrMsg, ruleName }); throw this.SAVE_ERROR(new EarlyExitException(msg, this.LA(1), this.LA(0))); } // TODO: consider caching the error message computed information raiseNoAltException(occurrence, errMsgTypes) { const ruleName = this.getCurrRuleFullName(); const ruleGrammar = this.getGAstProductions()[ruleName]; const lookAheadPathsPerAlternative = getLookaheadPathsForOr(occurrence, ruleGrammar, this.maxLookahead); const actualTokens = []; for (let i4 = 1; i4 <= this.maxLookahead; i4++) { actualTokens.push(this.LA(i4)); } const previousToken = this.LA(0); const errMsg = this.errorMessageProvider.buildNoViableAltMessage({ expectedPathsPerAlt: lookAheadPathsPerAlternative, actual: actualTokens, previous: previousToken, customUserDescription: errMsgTypes, ruleName: this.getCurrRuleFullName() }); throw this.SAVE_ERROR(new NoViableAltException(errMsg, this.LA(1), previousToken)); } } class ContentAssist { initContentAssist() { } computeContentAssist(startRuleName, precedingInput) { const startRuleGast = this.gastProductionsCache[startRuleName]; if (isUndefined(startRuleGast)) { throw Error(`Rule ->${startRuleName}<- does not exist in this grammar.`); } return nextPossibleTokensAfter([startRuleGast], precedingInput, this.tokenMatcher, this.maxLookahead); } // TODO: should this be a member method or a utility? it does not have any state or usage of 'this'... // TODO: should this be more explicitly part of the public API? getNextPossibleTokenTypes(grammarPath) { const topRuleName = head(grammarPath.ruleStack); const gastProductions = this.getGAstProductions(); const topProduction = gastProductions[topRuleName]; const nextPossibleTokenTypes = new NextAfterTokenWalker(topProduction, grammarPath).startWalking(); return nextPossibleTokenTypes; } } const RECORDING_NULL_OBJECT = { description: "This Object indicates the Parser is during Recording Phase" }; Object.freeze(RECORDING_NULL_OBJECT); const HANDLE_SEPARATOR = true; const MAX_METHOD_IDX = Math.pow(2, BITS_FOR_OCCURRENCE_IDX) - 1; const RFT = createToken2({ name: "RECORDING_PHASE_TOKEN", pattern: Lexer2.NA }); augmentTokenTypes([RFT]); const RECORDING_PHASE_TOKEN = createTokenInstance( RFT, "This IToken indicates the Parser is in Recording Phase\n See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details", // Using "-1" instead of NaN (as in EOF) because an actual number is less likely to // cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase. -1, -1, -1, -1, -1, -1 ); Object.freeze(RECORDING_PHASE_TOKEN); const RECORDING_PHASE_CSTNODE = { name: "This CSTNode indicates the Parser is in Recording Phase\n See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details", children: {} }; class GastRecorder { initGastRecorder(config) { this.recordingProdStack = []; this.RECORDING_PHASE = false; } enableRecording() { this.RECORDING_PHASE = true; this.TRACE_INIT("Enable Recording", () => { for (let i4 = 0; i4 < 10; i4++) { const idx = i4 > 0 ? i4 : ""; this[`CONSUME${idx}`] = function(arg1, arg2) { return this.consumeInternalRecord(arg1, i4, arg2); }; this[`SUBRULE${idx}`] = function(arg1, arg2) { return this.subruleInternalRecord(arg1, i4, arg2); }; this[`OPTION${idx}`] = function(arg1) { return this.optionInternalRecord(arg1, i4); }; this[`OR${idx}`] = function(arg1) { return this.orInternalRecord(arg1, i4); }; this[`MANY${idx}`] = function(arg1) { this.manyInternalRecord(i4, arg1); }; this[`MANY_SEP${idx}`] = function(arg1) { this.manySepFirstInternalRecord(i4, arg1); }; this[`AT_LEAST_ONE${idx}`] = function(arg1) { this.atLeastOneInternalRecord(i4, arg1); }; this[`AT_LEAST_ONE_SEP${idx}`] = function(arg1) { this.atLeastOneSepFirstInternalRecord(i4, arg1); }; } this[`consume`] = function(idx, arg1, arg2) { return this.consumeInternalRecord(arg1, idx, arg2); }; this[`subrule`] = function(idx, arg1, arg2) { return this.subruleInternalRecord(arg1, idx, arg2); }; this[`option`] = function(idx, arg1) { return this.optionInternalRecord(arg1, idx); }; this[`or`] = function(idx, arg1) { return this.orInternalRecord(arg1, idx); }; this[`many`] = function(idx, arg1) { this.manyInternalRecord(idx, arg1); }; this[`atLeastOne`] = function(idx, arg1) { this.atLeastOneInternalRecord(idx, arg1); }; this.ACTION = this.ACTION_RECORD; this.BACKTRACK = this.BACKTRACK_RECORD; this.LA = this.LA_RECORD; }); } disableRecording() { this.RECORDING_PHASE = false; this.TRACE_INIT("Deleting Recording methods", () => { const that = this; for (let i4 = 0; i4 < 10; i4++) { const idx = i4 > 0 ? i4 : ""; delete that[`CONSUME${idx}`]; delete that[`SUBRULE${idx}`]; delete that[`OPTION${idx}`]; delete that[`OR${idx}`]; delete that[`MANY${idx}`]; delete that[`MANY_SEP${idx}`]; delete that[`AT_LEAST_ONE${idx}`]; delete that[`AT_LEAST_ONE_SEP${idx}`]; } delete that[`consume`]; delete that[`subrule`]; delete that[`option`]; delete that[`or`]; delete that[`many`]; delete that[`atLeastOne`]; delete that.ACTION; delete that.BACKTRACK; delete that.LA; }); } // Parser methods are called inside an ACTION? // Maybe try/catch/finally on ACTIONS while disabling the recorders state changes? // @ts-expect-error -- noop place holder ACTION_RECORD(impl) { } // Executing backtracking logic will break our recording logic assumptions BACKTRACK_RECORD(grammarRule, args) { return () => true; } // LA is part of the official API and may be used for custom lookahead logic // by end users who may forget to wrap it in ACTION or inside a GATE LA_RECORD(howMuch) { return END_OF_FILE; } topLevelRuleRecord(name, def) { try { const newTopLevelRule = new Rule({ definition: [], name }); newTopLevelRule.name = name; this.recordingProdStack.push(newTopLevelRule); def.call(this); this.recordingProdStack.pop(); return newTopLevelRule; } catch (originalError) { if (originalError.KNOWN_RECORDER_ERROR !== true) { try { originalError.message = originalError.message + '\n This error was thrown during the "grammar recording phase" For more info see:\n https://chevrotain.io/docs/guide/internals.html#grammar-recording'; } catch (mutabilityError) { throw originalError; } } throw originalError; } } // Implementation of parsing DSL optionInternalRecord(actionORMethodDef, occurrence) { return recordProd.call(this, Option, actionORMethodDef, occurrence); } atLeastOneInternalRecord(occurrence, actionORMethodDef) { recordProd.call(this, RepetitionMandatory, actionORMethodDef, occurrence); } atLeastOneSepFirstInternalRecord(occurrence, options) { recordProd.call(this, RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR); } manyInternalRecord(occurrence, actionORMethodDef) { recordProd.call(this, Repetition, actionORMethodDef, occurrence); } manySepFirstInternalRecord(occurrence, options) { recordProd.call(this, RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR); } orInternalRecord(altsOrOpts, occurrence) { return recordOrProd.call(this, altsOrOpts, occurrence); } subruleInternalRecord(ruleToCall, occurrence, options) { assertMethodIdxIsValid(occurrence); if (!ruleToCall || has(ruleToCall, "ruleName") === false) { const error = new Error( ` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(ruleToCall)}> inside top level rule: <${this.recordingProdStack[0].name}>` ); error.KNOWN_RECORDER_ERROR = true; throw error; } const prevProd = last(this.recordingProdStack); const ruleName = ruleToCall.ruleName; const newNoneTerminal = new NonTerminal({ idx: occurrence, nonTerminalName: ruleName, label: options === null || options === void 0 ? void 0 : options.LABEL, // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created referencedRule: void 0 }); prevProd.definition.push(newNoneTerminal); return this.outputCst ? RECORDING_PHASE_CSTNODE : RECORDING_NULL_OBJECT; } consumeInternalRecord(tokType, occurrence, options) { assertMethodIdxIsValid(occurrence); if (!hasShortKeyProperty(tokType)) { const error = new Error( ` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(tokType)}> inside top level rule: <${this.recordingProdStack[0].name}>` ); error.KNOWN_RECORDER_ERROR = true; throw error; } const prevProd = last(this.recordingProdStack); const newNoneTerminal = new Terminal({ idx: occurrence, terminalType: tokType, label: options === null || options === void 0 ? void 0 : options.LABEL }); prevProd.definition.push(newNoneTerminal); return RECORDING_PHASE_TOKEN; } } function recordProd(prodConstructor, mainProdArg, occurrence, handleSep = false) { assertMethodIdxIsValid(occurrence); const prevProd = last(this.recordingProdStack); const grammarAction = isFunction3(mainProdArg) ? mainProdArg : mainProdArg.DEF; const newProd = new prodConstructor({ definition: [], idx: occurrence }); if (handleSep) { newProd.separator = mainProdArg.SEP; } if (has(mainProdArg, "MAX_LOOKAHEAD")) { newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; } this.recordingProdStack.push(newProd); grammarAction.call(this); prevProd.definition.push(newProd); this.recordingProdStack.pop(); return RECORDING_NULL_OBJECT; } function recordOrProd(mainProdArg, occurrence) { assertMethodIdxIsValid(occurrence); const prevProd = last(this.recordingProdStack); const hasOptions = isArray$1(mainProdArg) === false; const alts = hasOptions === false ? mainProdArg : mainProdArg.DEF; const newOrProd = new Alternation({ definition: [], idx: occurrence, ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true }); if (has(mainProdArg, "MAX_LOOKAHEAD")) { newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; } const hasPredicates = some(alts, (currAlt) => isFunction3(currAlt.GATE)); newOrProd.hasPredicates = hasPredicates; prevProd.definition.push(newOrProd); forEach(alts, (currAlt) => { const currAltFlat = new Alternative({ definition: [] }); newOrProd.definition.push(currAltFlat); if (has(currAlt, "IGNORE_AMBIGUITIES")) { currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES; } else if (has(currAlt, "GATE")) { currAltFlat.ignoreAmbiguities = true; } this.recordingProdStack.push(currAltFlat); currAlt.ALT.call(this); this.recordingProdStack.pop(); }); return RECORDING_NULL_OBJECT; } function getIdxSuffix(idx) { return idx === 0 ? "" : `${idx}`; } function assertMethodIdxIsValid(idx) { if (idx < 0 || idx > MAX_METHOD_IDX) { const error = new Error( // The stack trace will contain all the needed details `Invalid DSL Method idx value: <${idx}> Idx value must be a none negative value smaller than ${MAX_METHOD_IDX + 1}` ); error.KNOWN_RECORDER_ERROR = true; throw error; } } class PerformanceTracer { initPerformanceTracer(config) { if (has(config, "traceInitPerf")) { const userTraceInitPerf = config.traceInitPerf; const traceIsNumber = typeof userTraceInitPerf === "number"; this.traceInitMaxIdent = traceIsNumber ? userTraceInitPerf : Infinity; this.traceInitPerf = traceIsNumber ? userTraceInitPerf > 0 : userTraceInitPerf; } else { this.traceInitMaxIdent = 0; this.traceInitPerf = DEFAULT_PARSER_CONFIG.traceInitPerf; } this.traceInitIndent = -1; } TRACE_INIT(phaseDesc, phaseImpl) { if (this.traceInitPerf === true) { this.traceInitIndent++; const indent = new Array(this.traceInitIndent + 1).join(" "); if (this.traceInitIndent < this.traceInitMaxIdent) { console.log(`${indent}--> <${phaseDesc}>`); } const { time, value } = timer2(phaseImpl); const traceMethod = time > 10 ? console.warn : console.log; if (this.traceInitIndent < this.traceInitMaxIdent) { traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`); } this.traceInitIndent--; return value; } else { return phaseImpl(); } } } function applyMixins(derivedCtor, baseCtors) { baseCtors.forEach((baseCtor) => { const baseProto = baseCtor.prototype; Object.getOwnPropertyNames(baseProto).forEach((propName) => { if (propName === "constructor") { return; } const basePropDescriptor = Object.getOwnPropertyDescriptor(baseProto, propName); if (basePropDescriptor && (basePropDescriptor.get || basePropDescriptor.set)) { Object.defineProperty(derivedCtor.prototype, propName, basePropDescriptor); } else { derivedCtor.prototype[propName] = baseCtor.prototype[propName]; } }); }); } const END_OF_FILE = createTokenInstance(EOF, "", NaN, NaN, NaN, NaN, NaN, NaN); Object.freeze(END_OF_FILE); const DEFAULT_PARSER_CONFIG = Object.freeze({ recoveryEnabled: false, maxLookahead: 3, dynamicTokensEnabled: false, outputCst: true, errorMessageProvider: defaultParserErrorProvider, nodeLocationTracking: "none", traceInitPerf: false, skipValidations: false }); const DEFAULT_RULE_CONFIG = Object.freeze({ recoveryValueFunc: () => void 0, resyncEnabled: true }); var ParserDefinitionErrorType; (function(ParserDefinitionErrorType2) { ParserDefinitionErrorType2[ParserDefinitionErrorType2["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["LEFT_RECURSION"] = 5] = "LEFT_RECURSION"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["NO_NON_EMPTY_LOOKAHEAD"] = 10] = "NO_NON_EMPTY_LOOKAHEAD"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["AMBIGUOUS_PREFIX_ALTS"] = 11] = "AMBIGUOUS_PREFIX_ALTS"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["TOO_MANY_ALTS"] = 12] = "TOO_MANY_ALTS"; ParserDefinitionErrorType2[ParserDefinitionErrorType2["CUSTOM_LOOKAHEAD_VALIDATION"] = 13] = "CUSTOM_LOOKAHEAD_VALIDATION"; })(ParserDefinitionErrorType || (ParserDefinitionErrorType = {})); class Parser2 { /** * @deprecated use the **instance** method with the same name instead */ static performSelfAnalysis(parserInstance) { throw Error( "The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead." ); } performSelfAnalysis() { this.TRACE_INIT("performSelfAnalysis", () => { let defErrorsMsgs; this.selfAnalysisDone = true; const className = this.className; this.TRACE_INIT("toFastProps", () => { toFastProperties(this); }); this.TRACE_INIT("Grammar Recording", () => { try { this.enableRecording(); forEach(this.definedRulesNames, (currRuleName) => { const wrappedRule = this[currRuleName]; const originalGrammarAction = wrappedRule["originalGrammarAction"]; let recordedRuleGast; this.TRACE_INIT(`${currRuleName} Rule`, () => { recordedRuleGast = this.topLevelRuleRecord(currRuleName, originalGrammarAction); }); this.gastProductionsCache[currRuleName] = recordedRuleGast; }); } finally { this.disableRecording(); } }); let resolverErrors = []; this.TRACE_INIT("Grammar Resolving", () => { resolverErrors = resolveGrammar({ rules: values(this.gastProductionsCache) }); this.definitionErrors = this.definitionErrors.concat(resolverErrors); }); this.TRACE_INIT("Grammar Validations", () => { if (isEmpty(resolverErrors) && this.skipValidations === false) { const validationErrors = validateGrammar({ rules: values(this.gastProductionsCache), tokenTypes: values(this.tokensMap), errMsgProvider: defaultGrammarValidatorErrorProvider, grammarName: className }); const lookaheadValidationErrors = validateLookahead({ lookaheadStrategy: this.lookaheadStrategy, rules: values(this.gastProductionsCache), tokenTypes: values(this.tokensMap), grammarName: className }); this.definitionErrors = this.definitionErrors.concat(validationErrors, lookaheadValidationErrors); } }); if (isEmpty(this.definitionErrors)) { if (this.recoveryEnabled) { this.TRACE_INIT("computeAllProdsFollows", () => { const allFollows = computeAllProdsFollows(values(this.gastProductionsCache)); this.resyncFollows = allFollows; }); } this.TRACE_INIT("ComputeLookaheadFunctions", () => { var _a3, _b3; (_b3 = (_a3 = this.lookaheadStrategy).initialize) === null || _b3 === void 0 ? void 0 : _b3.call(_a3, { rules: values(this.gastProductionsCache) }); this.preComputeLookaheadFunctions(values(this.gastProductionsCache)); }); } if (!Parser2.DEFER_DEFINITION_ERRORS_HANDLING && !isEmpty(this.definitionErrors)) { defErrorsMsgs = map2(this.definitionErrors, (defError) => defError.message); throw new Error( `Parser Definition Errors detected: ${defErrorsMsgs.join("\n-------------------------------\n")}` ); } }); } constructor(tokenVocabulary, config) { this.definitionErrors = []; this.selfAnalysisDone = false; const that = this; that.initErrorHandler(config); that.initLexerAdapter(); that.initLooksAhead(config); that.initRecognizerEngine(tokenVocabulary, config); that.initRecoverable(config); that.initTreeBuilder(config); that.initContentAssist(); that.initGastRecorder(config); that.initPerformanceTracer(config); if (has(config, "ignoredIssues")) { throw new Error( "The IParserConfig property has been deprecated.\n Please use the flag on the relevant DSL method instead.\n See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n For further details." ); } this.skipValidations = has(config, "skipValidations") ? config.skipValidations : DEFAULT_PARSER_CONFIG.skipValidations; } } Parser2.DEFER_DEFINITION_ERRORS_HANDLING = false; applyMixins(Parser2, [ Recoverable, LooksAhead, TreeBuilder, LexerAdapter, RecognizerEngine, RecognizerApi, ErrorHandler, ContentAssist, GastRecorder, PerformanceTracer ]); class CstParser2 extends Parser2 { constructor(tokenVocabulary, config = DEFAULT_PARSER_CONFIG) { const configClone = clone2(config); configClone.outputCst = true; super(tokenVocabulary, configClone); } } return { CstParser: CstParser2, Lexer: Lexer2, createToken: createToken2 }; })(); // node_modules/three-stdlib/utils/WorkerPool.js var WorkerPool = class { constructor(pool = 4) { this.pool = pool; this.queue = []; this.workers = []; this.workersResolve = []; this.workerStatus = 0; } _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 i4 = 0; i4 < this.pool; i4++) if (!(this.workerStatus & 1 << i4)) return i4; 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; } } setWorkerCreator(workerCreator) { this.workerCreator = workerCreator; } setWorkerLimit(pool) { this.pool = pool; } 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 }); } }); } 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-stdlib/libs/ktx-parse.js var KHR_SUPERCOMPRESSION_NONE = 0; var KHR_SUPERCOMPRESSION_ZSTD = 2; var KHR_DF_KHR_DESCRIPTORTYPE_BASICFORMAT = 0; var KHR_DF_VENDORID_KHRONOS = 0; var KHR_DF_VERSION = 2; var KHR_DF_MODEL_UNSPECIFIED = 0; var KHR_DF_FLAG_ALPHA_STRAIGHT = 0; var KHR_DF_FLAG_ALPHA_PREMULTIPLIED = 1; var KHR_DF_TRANSFER_SRGB = 2; var KHR_DF_PRIMARIES_UNSPECIFIED = 0; var KHR_DF_PRIMARIES_BT709 = 1; var KHR_DF_PRIMARIES_DISPLAYP3 = 10; var KHR_DF_SAMPLE_DATATYPE_SIGNED = 64; var VK_FORMAT_UNDEFINED = 0; var VK_FORMAT_R8_UNORM = 9; var VK_FORMAT_R8_SRGB = 15; var VK_FORMAT_R8G8_UNORM = 16; var VK_FORMAT_R8G8_SRGB = 22; var VK_FORMAT_R8G8B8A8_UNORM = 37; var VK_FORMAT_R8G8B8A8_SRGB = 43; var VK_FORMAT_R16_SFLOAT = 76; var VK_FORMAT_R16G16_SFLOAT = 83; var VK_FORMAT_R16G16B16A16_SFLOAT = 97; var VK_FORMAT_R32_SFLOAT = 100; var VK_FORMAT_R32G32_SFLOAT = 103; var VK_FORMAT_R32G32B32A32_SFLOAT = 109; var VK_FORMAT_ASTC_6x6_UNORM_BLOCK = 165; var VK_FORMAT_ASTC_6x6_SRGB_BLOCK = 166; var KTX2Container = class { constructor() { this.vkFormat = VK_FORMAT_UNDEFINED; this.typeSize = 1; this.pixelWidth = 0; this.pixelHeight = 0; this.pixelDepth = 0; this.layerCount = 0; this.faceCount = 1; this.supercompressionScheme = KHR_SUPERCOMPRESSION_NONE; this.levels = []; this.dataFormatDescriptor = [ { vendorId: KHR_DF_VENDORID_KHRONOS, descriptorType: KHR_DF_KHR_DESCRIPTORTYPE_BASICFORMAT, descriptorBlockSize: 0, versionNumber: KHR_DF_VERSION, colorModel: KHR_DF_MODEL_UNSPECIFIED, colorPrimaries: KHR_DF_PRIMARIES_BT709, transferFunction: KHR_DF_TRANSFER_SRGB, flags: KHR_DF_FLAG_ALPHA_STRAIGHT, texelBlockDimension: [0, 0, 0, 0], bytesPlane: [0, 0, 0, 0, 0, 0, 0, 0], samples: [] } ]; this.keyValue = {}; this.globalData = null; } }; var BufferReader = class { constructor(data, byteOffset, byteLength, littleEndian) { this._dataView = void 0; this._littleEndian = void 0; this._offset = void 0; this._dataView = new DataView(data.buffer, data.byteOffset + byteOffset, byteLength); this._littleEndian = littleEndian; this._offset = 0; } _nextUint8() { const value = this._dataView.getUint8(this._offset); this._offset += 1; return value; } _nextUint16() { const value = this._dataView.getUint16(this._offset, this._littleEndian); this._offset += 2; return value; } _nextUint32() { const value = this._dataView.getUint32(this._offset, this._littleEndian); this._offset += 4; return value; } _nextUint64() { const left = this._dataView.getUint32(this._offset, this._littleEndian); const right = this._dataView.getUint32(this._offset + 4, this._littleEndian); const value = left + 2 ** 32 * right; this._offset += 8; return value; } _nextInt32() { const value = this._dataView.getInt32(this._offset, this._littleEndian); this._offset += 4; return value; } _nextUint8Array(len) { const value = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._offset, len); this._offset += len; return value; } _skip(bytes) { this._offset += bytes; return this; } _scan(maxByteLength, term) { if (term === void 0) { term = 0; } const byteOffset = this._offset; let byteLength = 0; while (this._dataView.getUint8(this._offset) !== term && byteLength < maxByteLength) { byteLength++; this._offset++; } if (byteLength < maxByteLength) this._offset++; return new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + byteOffset, byteLength); } }; var KTX2_ID = [ // '´', 'K', 'T', 'X', '2', '0', 'ª', '\r', '\n', '\x1A', '\n' 171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10 ]; function decodeText2(buffer2) { if (typeof TextDecoder !== "undefined") { return new TextDecoder().decode(buffer2); } return Buffer.from(buffer2).toString("utf8"); } function read(data) { const id = new Uint8Array(data.buffer, data.byteOffset, KTX2_ID.length); if (id[0] !== KTX2_ID[0] || // '´' id[1] !== KTX2_ID[1] || // 'K' id[2] !== KTX2_ID[2] || // 'T' id[3] !== KTX2_ID[3] || // 'X' id[4] !== KTX2_ID[4] || // ' ' id[5] !== KTX2_ID[5] || // '2' id[6] !== KTX2_ID[6] || // '0' id[7] !== KTX2_ID[7] || // 'ª' id[8] !== KTX2_ID[8] || // '\r' id[9] !== KTX2_ID[9] || // '\n' id[10] !== KTX2_ID[10] || // '\x1A' id[11] !== KTX2_ID[11]) { throw new Error("Missing KTX 2.0 identifier."); } const container = new KTX2Container(); const headerByteLength = 17 * Uint32Array.BYTES_PER_ELEMENT; const headerReader = new BufferReader(data, KTX2_ID.length, headerByteLength, true); container.vkFormat = headerReader._nextUint32(); container.typeSize = headerReader._nextUint32(); container.pixelWidth = headerReader._nextUint32(); container.pixelHeight = headerReader._nextUint32(); container.pixelDepth = headerReader._nextUint32(); container.layerCount = headerReader._nextUint32(); container.faceCount = headerReader._nextUint32(); const levelCount = headerReader._nextUint32(); container.supercompressionScheme = headerReader._nextUint32(); const dfdByteOffset = headerReader._nextUint32(); const dfdByteLength = headerReader._nextUint32(); const kvdByteOffset = headerReader._nextUint32(); const kvdByteLength = headerReader._nextUint32(); const sgdByteOffset = headerReader._nextUint64(); const sgdByteLength = headerReader._nextUint64(); const levelByteLength = levelCount * 3 * 8; const levelReader = new BufferReader(data, KTX2_ID.length + headerByteLength, levelByteLength, true); for (let i4 = 0; i4 < levelCount; i4++) { container.levels.push({ levelData: new Uint8Array(data.buffer, data.byteOffset + levelReader._nextUint64(), levelReader._nextUint64()), uncompressedByteLength: levelReader._nextUint64() }); } const dfdReader = new BufferReader(data, dfdByteOffset, dfdByteLength, true); const dfd = { vendorId: dfdReader._skip( 4 /* totalSize */ )._nextUint16(), descriptorType: dfdReader._nextUint16(), versionNumber: dfdReader._nextUint16(), descriptorBlockSize: dfdReader._nextUint16(), colorModel: dfdReader._nextUint8(), colorPrimaries: dfdReader._nextUint8(), transferFunction: dfdReader._nextUint8(), flags: dfdReader._nextUint8(), texelBlockDimension: [ dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8() ], bytesPlane: [ dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8() ], samples: [] }; const sampleStart = 6; const sampleWords = 4; const numSamples = (dfd.descriptorBlockSize / 4 - sampleStart) / sampleWords; for (let i4 = 0; i4 < numSamples; i4++) { const sample = { bitOffset: dfdReader._nextUint16(), bitLength: dfdReader._nextUint8(), channelType: dfdReader._nextUint8(), samplePosition: [dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8(), dfdReader._nextUint8()], sampleLower: -Infinity, sampleUpper: Infinity }; if (sample.channelType & KHR_DF_SAMPLE_DATATYPE_SIGNED) { sample.sampleLower = dfdReader._nextInt32(); sample.sampleUpper = dfdReader._nextInt32(); } else { sample.sampleLower = dfdReader._nextUint32(); sample.sampleUpper = dfdReader._nextUint32(); } dfd.samples[i4] = sample; } container.dataFormatDescriptor.length = 0; container.dataFormatDescriptor.push(dfd); const kvdReader = new BufferReader(data, kvdByteOffset, kvdByteLength, true); while (kvdReader._offset < kvdByteLength) { const keyValueByteLength = kvdReader._nextUint32(); const keyData = kvdReader._scan(keyValueByteLength); const key = decodeText2(keyData); container.keyValue[key] = kvdReader._nextUint8Array(keyValueByteLength - keyData.byteLength - 1); if (key.match(/^ktx/i)) { const text = decodeText2(container.keyValue[key]); container.keyValue[key] = text.substring(0, text.lastIndexOf("\0")); } const kvPadding = keyValueByteLength % 4 ? 4 - keyValueByteLength % 4 : 0; kvdReader._skip(kvPadding); } if (sgdByteLength <= 0) return container; const sgdReader = new BufferReader(data, sgdByteOffset, sgdByteLength, true); const endpointCount = sgdReader._nextUint16(); const selectorCount = sgdReader._nextUint16(); const endpointsByteLength = sgdReader._nextUint32(); const selectorsByteLength = sgdReader._nextUint32(); const tablesByteLength = sgdReader._nextUint32(); const extendedByteLength = sgdReader._nextUint32(); const imageDescs = []; for (let i4 = 0; i4 < levelCount; i4++) { imageDescs.push({ imageFlags: sgdReader._nextUint32(), rgbSliceByteOffset: sgdReader._nextUint32(), rgbSliceByteLength: sgdReader._nextUint32(), alphaSliceByteOffset: sgdReader._nextUint32(), alphaSliceByteLength: sgdReader._nextUint32() }); } const endpointsByteOffset = sgdByteOffset + sgdReader._offset; const selectorsByteOffset = endpointsByteOffset + endpointsByteLength; const tablesByteOffset = selectorsByteOffset + selectorsByteLength; const extendedByteOffset = tablesByteOffset + tablesByteLength; const endpointsData = new Uint8Array(data.buffer, data.byteOffset + endpointsByteOffset, endpointsByteLength); const selectorsData = new Uint8Array(data.buffer, data.byteOffset + selectorsByteOffset, selectorsByteLength); const tablesData = new Uint8Array(data.buffer, data.byteOffset + tablesByteOffset, tablesByteLength); const extendedData = new Uint8Array(data.buffer, data.byteOffset + extendedByteOffset, extendedByteLength); container.globalData = { endpointCount, selectorCount, imageDescs, endpointsData, selectorsData, tablesData, extendedData }; return container; } // node_modules/three-stdlib/libs/zstddec.js var init2; var instance; var heap; var IMPORT_OBJECT = { env: { emscripten_notify_memory_growth: function(index2) { heap = new Uint8Array(instance.exports.memory.buffer); } } }; var ZSTDDecoder = class { init() { if (init2) return init2; if (typeof fetch !== "undefined") { init2 = fetch("data:application/wasm;base64," + wasm).then((response) => response.arrayBuffer()).then((arrayBuffer) => WebAssembly.instantiate(arrayBuffer, IMPORT_OBJECT)).then(this._init); } else { init2 = WebAssembly.instantiate(Buffer.from(wasm, "base64"), IMPORT_OBJECT).then(this._init); } return init2; } _init(result) { instance = result.instance; IMPORT_OBJECT.env.emscripten_notify_memory_growth(0); } decode(array, uncompressedSize = 0) { if (!instance) throw new Error(`ZSTDDecoder: Await .init() before decoding.`); const compressedSize = array.byteLength; const compressedPtr = instance.exports.malloc(compressedSize); heap.set(array, compressedPtr); uncompressedSize = uncompressedSize || Number(instance.exports.ZSTD_findDecompressedSize(compressedPtr, compressedSize)); const uncompressedPtr = instance.exports.malloc(uncompressedSize); const actualSize = instance.exports.ZSTD_decompress( uncompressedPtr, uncompressedSize, compressedPtr, compressedSize ); const dec = heap.slice(uncompressedPtr, uncompressedPtr + actualSize); instance.exports.free(compressedPtr); instance.exports.free(uncompressedPtr); return dec; } }; var wasm = "AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ"; // node_modules/three-stdlib/_polyfill/CompressedCubeTexture.js var CompressedCubeTexture = class extends CompressedTexture { constructor(images, format, type) { super(void 0, images[0].width, images[0].height, format, type, CubeReflectionMapping); this.isCompressedCubeTexture = true; this.isCubeTexture = true; this.image = images; } }; // node_modules/three-stdlib/_polyfill/CompressedArrayTexture.js var CompressedArrayTexture = class extends CompressedTexture { constructor(mipmaps, width, height, depth, format, type) { super(mipmaps, width, height, format, type); this.isCompressedArrayTexture = true; this.image.depth = depth; this.wrapR = ClampToEdgeWrapping; } }; // node_modules/three-stdlib/loaders/KTX2Loader.js var __defProp31 = Object.defineProperty; var __defNormalProp31 = (obj, key, value) => key in obj ? __defProp31(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField31 = (obj, key, value) => { __defNormalProp31(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var LinearEncoding2 = 3e3; var sRGBEncoding2 = 3001; var NoColorSpace = ""; var DisplayP3ColorSpace = "display-p3"; var LinearDisplayP3ColorSpace = "display-p3-linear"; var LinearSRGBColorSpace3 = "srgb-linear"; var SRGBColorSpace3 = "srgb"; var _taskCache = /* @__PURE__ */ new WeakMap(); var _activeLoaders = 0; var _zstd; var KTX2Loader = (() => { const _KTX2Loader = class extends Loader { 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+.' ); } } setTranscoderPath(path) { this.transcoderPath = path; return this; } setWorkerLimit(num) { this.workerPool.setWorkerLimit(num); return this; } detectSupport(renderer) { this.workerConfig = { astcSupported: renderer.extensions.has("WEBGL_compressed_texture_astc"), etc1Supported: renderer.extensions.has("WEBGL_compressed_texture_etc1"), etc2Supported: renderer.extensions.has("WEBGL_compressed_texture_etc"), dxtSupported: renderer.extensions.has("WEBGL_compressed_texture_s3tc"), bptcSupported: renderer.extensions.has("EXT_texture_compression_bptc"), pvrtcSupported: renderer.extensions.has("WEBGL_compressed_texture_pvrtc") || renderer.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc") }; if (renderer.capabilities.isWebGL2) { this.workerConfig.etc1Supported = false; } return this; } 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 _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; } load(url, onLoad, onProgress, onError) { if (this.workerConfig === null) { throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`."); } const loader2 = new FileLoader(this.manager); loader2.setResponseType("arraybuffer"); loader2.setWithCredentials(this.withCredentials); loader2.load( url, (buffer2) => { if (_taskCache.has(buffer2)) { const cachedTask = _taskCache.get(buffer2); return cachedTask.promise.then(onLoad).catch(onError); } this._createTexture(buffer2).then((texture) => onLoad ? onLoad(texture) : null).catch(onError); }, onProgress, onError ); } _createTextureFrom(transcodeResult, container) { const { faces, width, height, format, type, error, dfdFlags } = transcodeResult; if (type === "error") return Promise.reject(error); let texture; if (container.faceCount === 6) { texture = new CompressedCubeTexture(faces, format, UnsignedByteType); } else { const mipmaps = faces[0].mipmaps; texture = container.layerCount > 1 ? new CompressedArrayTexture(mipmaps, width, height, container.layerCount, format, UnsignedByteType) : new CompressedTexture(mipmaps, width, height, format, UnsignedByteType); } texture.minFilter = faces[0].mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; texture.magFilter = LinearFilter; texture.generateMipmaps = false; texture.needsUpdate = true; const colorSpace = parseColorSpace(container); if ("colorSpace" in texture) texture.colorSpace = colorSpace; else texture.encoding = colorSpace === SRGBColorSpace3 ? sRGBEncoding2 : LinearEncoding2; texture.premultiplyAlpha = !!(dfdFlags & KHR_DF_FLAG_ALPHA_PREMULTIPLIED); return texture; } /** * @param {ArrayBuffer} buffer * @param {object?} config * @return {Promise} */ async _createTexture(buffer2, config = {}) { const container = read(new Uint8Array(buffer2)); if (container.vkFormat !== VK_FORMAT_UNDEFINED) { return createRawTexture(container); } const taskConfig = config; const texturePending = this.init().then(() => { return this.workerPool.postMessage({ type: "transcode", buffer: buffer2, taskConfig }, [buffer2]); }).then((e2) => this._createTextureFrom(e2.data, container)); _taskCache.set(buffer2, { promise: texturePending }); return texturePending; } dispose() { this.workerPool.dispose(); if (this.workerSourceURL) URL.revokeObjectURL(this.workerSourceURL); _activeLoaders--; return this; } }; let KTX2Loader2 = _KTX2Loader; __publicField31(KTX2Loader2, "BasisFormat", { ETC1S: 0, UASTC_4x4: 1 }); __publicField31(KTX2Loader2, "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 }); __publicField31(KTX2Loader2, "EngineFormat", { RGBAFormat, RGBA_ASTC_4x4_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, RGB_S3TC_DXT1_Format }); __publicField31(KTX2Loader2, "BasisWorker", function() { let config; let transcoderPending; let BasisModule; const EngineFormat = _EngineFormat; const TranscoderFormat = _TranscoderFormat; const BasisFormat = _BasisFormat; self.addEventListener("message", function(e2) { const message = e2.data; switch (message.type) { case "init": config = message.config; init3(message.transcoderBinary); break; case "transcode": transcoderPending.then(() => { try { const { faces, buffers, width, height, hasAlpha, format, dfdFlags } = transcode(message.buffer); self.postMessage( { type: "transcode", id: message.id, faces, width, height, hasAlpha, format, dfdFlags }, buffers ); } catch (error) { console.error(error); self.postMessage({ type: "error", id: message.id, error: error.message }); } }); break; } }); function init3(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(buffer2) { const ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer2)); function cleanup() { ktx2File.close(); ktx2File.delete(); } if (!ktx2File.isValid()) { cleanup(); throw new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file"); } const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; const width = ktx2File.getWidth(); const height = 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 } = getTranscoderFormat(basisFormat, width, height, hasAlpha); if (!width || !height || !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; } const dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, layer, 0, transcoderFormat)); const status = ktx2File.transcodeImage(dst, mip, layer, face, transcoderFormat, 0, -1, -1); 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, height, format: engineFormat }); } cleanup(); return { faces, buffers, width, height, hasAlpha, format: engineFormat, dfdFlags }; } const FORMAT_OPTIONS = [ { if: "astcSupported", basisFormat: [BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4], engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format], priorityETC1S: Infinity, priorityUASTC: 1, needsPowerOfTwo: false }, { if: "bptcSupported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5], engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format], priorityETC1S: 3, priorityUASTC: 2, needsPowerOfTwo: false }, { if: "dxtSupported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3], engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format], priorityETC1S: 4, priorityUASTC: 5, needsPowerOfTwo: false }, { if: "etc2Supported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2], engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format], priorityETC1S: 1, priorityUASTC: 3, needsPowerOfTwo: false }, { if: "etc1Supported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ETC1], engineFormat: [EngineFormat.RGB_ETC1_Format], priorityETC1S: 2, priorityUASTC: 4, needsPowerOfTwo: false }, { if: "pvrtcSupported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA], engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format], priorityETC1S: 5, priorityUASTC: 6, needsPowerOfTwo: true } ]; const ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function(a6, b5) { return a6.priorityETC1S - b5.priorityETC1S; }); const UASTC_OPTIONS = FORMAT_OPTIONS.sort(function(a6, b5) { return a6.priorityUASTC - b5.priorityUASTC; }); function getTranscoderFormat(basisFormat, width, height, hasAlpha) { let transcoderFormat; let engineFormat; const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; for (let i4 = 0; i4 < options.length; i4++) { const opt = options[i4]; if (!config[opt.if]) continue; if (!opt.basisFormat.includes(basisFormat)) continue; if (hasAlpha && opt.transcoderFormat.length < 2) continue; if (opt.needsPowerOfTwo && !(isPowerOfTwo(width) && isPowerOfTwo(height))) continue; transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0]; engineFormat = opt.engineFormat[hasAlpha ? 1 : 0]; return { transcoderFormat, engineFormat }; } console.warn("THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32."); transcoderFormat = TranscoderFormat.RGBA32; engineFormat = EngineFormat.RGBAFormat; return { transcoderFormat, engineFormat }; } function isPowerOfTwo(value) { if (value <= 2) return true; return (value & value - 1) === 0 && value !== 0; } function concat(arrays) { if (arrays.length === 1) return arrays[0]; let totalByteLength = 0; for (let i4 = 0; i4 < arrays.length; i4++) { const array = arrays[i4]; totalByteLength += array.byteLength; } const result = new Uint8Array(totalByteLength); let byteOffset = 0; for (let i4 = 0; i4 < arrays.length; i4++) { const array = arrays[i4]; result.set(array, byteOffset); byteOffset += array.byteLength; } return result; } }); return KTX2Loader2; })(); var UNCOMPRESSED_FORMATS = /* @__PURE__ */ new Set([RGBAFormat, RGFormat, RedFormat]); var FORMAT_MAP = { [VK_FORMAT_R32G32B32A32_SFLOAT]: RGBAFormat, [VK_FORMAT_R16G16B16A16_SFLOAT]: RGBAFormat, [VK_FORMAT_R8G8B8A8_UNORM]: RGBAFormat, [VK_FORMAT_R8G8B8A8_SRGB]: RGBAFormat, [VK_FORMAT_R32G32_SFLOAT]: RGFormat, [VK_FORMAT_R16G16_SFLOAT]: RGFormat, [VK_FORMAT_R8G8_UNORM]: RGFormat, [VK_FORMAT_R8G8_SRGB]: RGFormat, [VK_FORMAT_R32_SFLOAT]: RedFormat, [VK_FORMAT_R16_SFLOAT]: RedFormat, [VK_FORMAT_R8_SRGB]: RedFormat, [VK_FORMAT_R8_UNORM]: RedFormat, [VK_FORMAT_ASTC_6x6_SRGB_BLOCK]: RGBA_ASTC_6x6_Format, [VK_FORMAT_ASTC_6x6_UNORM_BLOCK]: RGBA_ASTC_6x6_Format }; var TYPE_MAP = { [VK_FORMAT_R32G32B32A32_SFLOAT]: FloatType, [VK_FORMAT_R16G16B16A16_SFLOAT]: HalfFloatType, [VK_FORMAT_R8G8B8A8_UNORM]: UnsignedByteType, [VK_FORMAT_R8G8B8A8_SRGB]: UnsignedByteType, [VK_FORMAT_R32G32_SFLOAT]: FloatType, [VK_FORMAT_R16G16_SFLOAT]: HalfFloatType, [VK_FORMAT_R8G8_UNORM]: UnsignedByteType, [VK_FORMAT_R8G8_SRGB]: UnsignedByteType, [VK_FORMAT_R32_SFLOAT]: FloatType, [VK_FORMAT_R16_SFLOAT]: HalfFloatType, [VK_FORMAT_R8_SRGB]: UnsignedByteType, [VK_FORMAT_R8_UNORM]: UnsignedByteType, [VK_FORMAT_ASTC_6x6_SRGB_BLOCK]: UnsignedByteType, [VK_FORMAT_ASTC_6x6_UNORM_BLOCK]: 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 === KHR_SUPERCOMPRESSION_ZSTD) { if (!_zstd) { _zstd = new Promise(async (resolve) => { const zstd2 = new ZSTDDecoder(); 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 === KHR_SUPERCOMPRESSION_NONE) { levelData = level.levelData; } else if (container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD) { levelData = zstd.decode(level.levelData, level.uncompressedByteLength); } else { throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme."); } let data; if (TYPE_MAP[vkFormat] === FloatType) { data = new Float32Array( levelData.buffer, levelData.byteOffset, levelData.byteLength / Float32Array.BYTES_PER_ELEMENT ); } else if (TYPE_MAP[vkFormat] === HalfFloatType) { data = new Uint16Array( levelData.buffer, levelData.byteOffset, levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT ); } else { data = levelData; } mipmaps.push({ data, 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.mipmaps = mipmaps; texture.type = TYPE_MAP[vkFormat]; texture.format = FORMAT_MAP[vkFormat]; texture.needsUpdate = true; const colorSpace = parseColorSpace(container); if ("colorSpace" in texture) texture.colorSpace = colorSpace; else texture.encoding = colorSpace === SRGBColorSpace3 ? sRGBEncoding2 : LinearEncoding2; return Promise.resolve(texture); } function parseColorSpace(container) { const dfd = container.dataFormatDescriptor[0]; if (dfd.colorPrimaries === KHR_DF_PRIMARIES_BT709) { return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? SRGBColorSpace3 : LinearSRGBColorSpace3; } else if (dfd.colorPrimaries === KHR_DF_PRIMARIES_DISPLAYP3) { return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace; } else if (dfd.colorPrimaries === KHR_DF_PRIMARIES_UNSPECIFIED) { return NoColorSpace; } else { console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${dfd.colorPrimaries}"`); return NoColorSpace; } } // node_modules/three-stdlib/libs/lottie.js var lottie = (() => { if (typeof navigator === "undefined" || navigator.product === "ReactNative" || typeof document === "undefined" || typeof document.getElementsByTagName !== "function" || typeof document.createElement !== "function" || typeof CanvasRenderingContext2D === "undefined") return {}; 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 = (value) => { locationHref = value; }; const getLocationHref = () => locationHref; function createTag(type) { return document.createElement(type); } function extendPrototype(sources, destination) { var i4; var len = sources.length; var sourcePrototype; for (i4 = 0; i4 < len; i4 += 1) { sourcePrototype = sources[i4].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; } 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 i4; var len = this.audios.length; for (i4 = 0; i4 < len; i4 += 1) { this.audios[i4].pause(); } }, resume: function() { var i4; var len = this.audios.length; for (i4 = 0; i4 < len; i4 += 1) { this.audios[i4].resume(); } }, setRate: function(rateValue) { var i4; var len = this.audios.length; for (i4 = 0; i4 < len; i4 += 1) { this.audios[i4].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(value) { this._volume = value; this._updateVolume(); }, mute: function() { this._isMuted = true; this._updateVolume(); }, unmute: function() { this._isMuted = false; this._updateVolume(); }, getVolume: function() { return this._volume; }, _updateVolume: function() { var i4; var len = this.audios.length; for (i4 = 0; i4 < len; i4 += 1) { this.audios[i4].volume(this._volume * (this._isMuted ? 0 : 1)); } } }; return function() { return new AudioController(); }; })(); const createTypedArray = (function() { function createRegularArray(type, len) { var i4 = 0; var arr = []; var value; switch (type) { case "int16": case "uint8c": value = 1; break; default: value = 1.1; break; } for (i4 = 0; i4 < len; i4 += 1) { arr.push(value); } 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; })(); function createSizedArray(len) { return Array.apply(null, { length: len }); } let subframeEnabled = true; let expressionsPlugin = null; let idPrefix$1 = ""; const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); const bmPow = Math.pow; const bmSqrt = Math.sqrt; const bmFloor = Math.floor; 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 i4; var len = propertyNames.length; for (i4 = 0; i4 < len; i4 += 1) { BMMath[propertyNames[i4]] = Math[propertyNames[i4]]; } })(); BMMath.random = Math.random; BMMath.abs = function(val) { var tOfVal = typeof val; if (tOfVal === "object" && val.length) { var absArr = createSizedArray(val.length); var i4; var len = val.length; for (i4 = 0; i4 < len; i4 += 1) { absArr[i4] = Math.abs(val[i4]); } return absArr; } return Math.abs(val); }; let defaultCurveSegments = 150; const degToRads = Math.PI / 180; const roundCorner = 0.5519; 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, target2) { this.type = type; this.target = target2; } function BMRenderFrameErrorEvent(nativeError, currentTime) { this.type = "renderFrameError"; this.nativeError = nativeError; this.currentTime = currentTime; } function BMConfigErrorEvent(nativeError) { this.type = "configError"; this.nativeError = nativeError; } const createElementID = /* @__PURE__ */ (function() { var _count = 0; return function createID() { _count += 1; return idPrefix$1 + "__lottie_element_" + _count; }; })(); function HSVtoRGB(h, s2, v5) { var r2; var g; var b5; var i4; var f2; var p2; var q; var t3; i4 = Math.floor(h * 6); f2 = h * 6 - i4; p2 = v5 * (1 - s2); q = v5 * (1 - f2 * s2); t3 = v5 * (1 - (1 - f2) * s2); switch (i4 % 6) { case 0: r2 = v5; g = t3; b5 = p2; break; case 1: r2 = q; g = v5; b5 = p2; break; case 2: r2 = p2; g = v5; b5 = t3; break; case 3: r2 = p2; g = q; b5 = v5; break; case 4: r2 = t3; g = p2; b5 = v5; break; case 5: r2 = v5; g = p2; b5 = q; break; } return [r2, g, b5]; } function RGBtoHSV(r2, g, b5) { var max2 = Math.max(r2, g, b5); var min = Math.min(r2, g, b5); var d2 = max2 - min; var h; var s2 = max2 === 0 ? 0 : d2 / max2; var v5 = max2 / 255; switch (max2) { case min: h = 0; break; case r2: h = g - b5 + d2 * (g < b5 ? 6 : 0); h /= 6 * d2; break; case g: h = b5 - r2 + d2 * 2; h /= 6 * d2; break; case b5: h = r2 - g + d2 * 4; h /= 6 * d2; break; } return [h, s2, v5]; } 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() { var colorMap = []; var i4; var hex; for (i4 = 0; i4 < 256; i4 += 1) { hex = i4.toString(16); colorMap[i4] = hex.length === 1 ? "0" + hex : hex; } return function(r2, g, b5) { if (r2 < 0) { r2 = 0; } if (g < 0) { g = 0; } if (b5 < 0) { b5 = 0; } return "#" + colorMap[r2] + colorMap[g] + colorMap[b5]; }; })(); const setSubframeEnabled = (flag) => { subframeEnabled = !!flag; }; const getSubframeEnabled = () => subframeEnabled; const setExpressionsPlugin = (value) => { expressionsPlugin = value; }; const getExpressionsPlugin = () => expressionsPlugin; const setDefaultCurveSegments = (value) => { defaultCurveSegments = value; }; const getDefaultCurveSegments = () => defaultCurveSegments; const setIdPrefix = (value) => { idPrefix$1 = value; }; function createNS(type) { return document.createElementNS(svgNS, type); } 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(data) { workerProxy.onmessage({ data }); } }; function createWorker2(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 = createWorker2(function workerStart(e2) { function dataFunctionManager() { function completeLayers(layers, comps) { var layerData; var i4; var len = layers.length; var j; var jLen; var k; var kLen; for (i4 = 0; i4 < len; i4 += 1) { layerData = layers[i4]; if ("ks" in layerData && !layerData.completed) { layerData.completed = true; if (layerData.tt) { layers[i4 - 1].td = layerData.tt; } if (layerData.hasMask) { var maskProps = layerData.masksProperties; jLen = maskProps.length; for (j = 0; j < jLen; j += 1) { if (maskProps[j].pt.k.i) { convertPathsToAbsoluteValues(maskProps[j].pt.k); } else { kLen = maskProps[j].pt.k.length; for (k = 0; k < kLen; k += 1) { if (maskProps[j].pt.k[k].s) { convertPathsToAbsoluteValues(maskProps[j].pt.k[k].s[0]); } if (maskProps[j].pt.k[k].e) { convertPathsToAbsoluteValues(maskProps[j].pt.k[k].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 i4 = 0; var len = chars.length; for (i4 = 0; i4 < len; i4 += 1) { if (chars[i4].t === 1) { chars[i4].data.layers = findCompLayers(chars[i4].data.refId, assets); completeLayers(chars[i4].data.layers, assets); } } } } function findComp(id, comps) { var i4 = 0; var len = comps.length; while (i4 < len) { if (comps[i4].id === id) { return comps[i4]; } i4 += 1; } return null; } function findCompLayers(id, comps) { var comp = findComp(id, comps); if (comp) { if (!comp.layers.__used) { comp.layers.__used = true; return comp.layers; } return JSON.parse(JSON.stringify(comp.layers)); } return null; } function completeShapes(arr) { var i4; var len = arr.length; var j; var jLen; for (i4 = len - 1; i4 >= 0; i4 -= 1) { if (arr[i4].ty === "sh") { if (arr[i4].ks.k.i) { convertPathsToAbsoluteValues(arr[i4].ks.k); } else { jLen = arr[i4].ks.k.length; for (j = 0; j < jLen; j += 1) { if (arr[i4].ks.k[j].s) { convertPathsToAbsoluteValues(arr[i4].ks.k[j].s[0]); } if (arr[i4].ks.k[j].e) { convertPathsToAbsoluteValues(arr[i4].ks.k[j].e[0]); } } } } else if (arr[i4].ty === "gr") { completeShapes(arr[i4].it); } } } function convertPathsToAbsoluteValues(path) { var i4; var len = path.i.length; for (i4 = 0; i4 < len; i4 += 1) { path.i[i4][0] += path.v[i4][0]; path.i[i4][1] += path.v[i4][1]; path.o[i4][0] += path.v[i4][0]; path.o[i4][1] += path.v[i4][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 i4; var len = layers.length; for (i4 = 0; i4 < len; i4 += 1) { if (layers[i4].ty === 5) { updateTextLayer(layers[i4]); } } } return function(animationData) { if (checkVersion(minimumVersion, animationData.v)) { iterateLayers(animationData.layers); if (animationData.assets) { var i4; var len = animationData.assets.length; for (i4 = 0; i4 < len; i4 += 1) { if (animationData.assets[i4].layers) { iterateLayers(animationData.assets[i4].layers); } } } } }; })(); var checkChars = /* @__PURE__ */ (function() { var minimumVersion = [4, 7, 99]; return function(animationData) { if (animationData.chars && !checkVersion(minimumVersion, animationData.v)) { var i4; var len = animationData.chars.length; for (i4 = 0; i4 < len; i4 += 1) { var charData = animationData.chars[i4]; 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 (!animationData.chars[i4].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 i4; var len = layers.length; for (i4 = 0; i4 < len; i4 += 1) { if (layers[i4].ty === 5) { updateTextLayer(layers[i4]); } } } return function(animationData) { if (checkVersion(minimumVersion, animationData.v)) { iterateLayers(animationData.layers); if (animationData.assets) { var i4; var len = animationData.assets.length; for (i4 = 0; i4 < len; i4 += 1) { if (animationData.assets[i4].layers) { iterateLayers(animationData.assets[i4].layers); } } } } }; })(); var checkColors = /* @__PURE__ */ (function() { var minimumVersion = [4, 1, 9]; function iterateShapes(shapes) { var i4; var len = shapes.length; var j; var jLen; for (i4 = 0; i4 < len; i4 += 1) { if (shapes[i4].ty === "gr") { iterateShapes(shapes[i4].it); } else if (shapes[i4].ty === "fl" || shapes[i4].ty === "st") { if (shapes[i4].c.k && shapes[i4].c.k[0].i) { jLen = shapes[i4].c.k.length; for (j = 0; j < jLen; j += 1) { if (shapes[i4].c.k[j].s) { shapes[i4].c.k[j].s[0] /= 255; shapes[i4].c.k[j].s[1] /= 255; shapes[i4].c.k[j].s[2] /= 255; shapes[i4].c.k[j].s[3] /= 255; } if (shapes[i4].c.k[j].e) { shapes[i4].c.k[j].e[0] /= 255; shapes[i4].c.k[j].e[1] /= 255; shapes[i4].c.k[j].e[2] /= 255; shapes[i4].c.k[j].e[3] /= 255; } } } else { shapes[i4].c.k[0] /= 255; shapes[i4].c.k[1] /= 255; shapes[i4].c.k[2] /= 255; shapes[i4].c.k[3] /= 255; } } } } function iterateLayers(layers) { var i4; var len = layers.length; for (i4 = 0; i4 < len; i4 += 1) { if (layers[i4].ty === 4) { iterateShapes(layers[i4].shapes); } } } return function(animationData) { if (checkVersion(minimumVersion, animationData.v)) { iterateLayers(animationData.layers); if (animationData.assets) { var i4; var len = animationData.assets.length; for (i4 = 0; i4 < len; i4 += 1) { if (animationData.assets[i4].layers) { iterateLayers(animationData.assets[i4].layers); } } } } }; })(); var checkShapes = /* @__PURE__ */ (function() { var minimumVersion = [4, 4, 18]; function completeClosingShapes(arr) { var i4; var len = arr.length; var j; var jLen; for (i4 = len - 1; i4 >= 0; i4 -= 1) { if (arr[i4].ty === "sh") { if (arr[i4].ks.k.i) { arr[i4].ks.k.c = arr[i4].closed; } else { jLen = arr[i4].ks.k.length; for (j = 0; j < jLen; j += 1) { if (arr[i4].ks.k[j].s) { arr[i4].ks.k[j].s[0].c = arr[i4].closed; } if (arr[i4].ks.k[j].e) { arr[i4].ks.k[j].e[0].c = arr[i4].closed; } } } } else if (arr[i4].ty === "gr") { completeClosingShapes(arr[i4].it); } } } function iterateLayers(layers) { var layerData; var i4; var len = layers.length; var j; var jLen; var k; var kLen; for (i4 = 0; i4 < len; i4 += 1) { layerData = layers[i4]; if (layerData.hasMask) { var maskProps = layerData.masksProperties; jLen = maskProps.length; for (j = 0; j < jLen; j += 1) { if (maskProps[j].pt.k.i) { maskProps[j].pt.k.c = maskProps[j].cl; } else { kLen = maskProps[j].pt.k.length; for (k = 0; k < kLen; k += 1) { if (maskProps[j].pt.k[k].s) { maskProps[j].pt.k[k].s[0].c = maskProps[j].cl; } if (maskProps[j].pt.k[k].e) { maskProps[j].pt.k[k].e[0].c = maskProps[j].cl; } } } } } if (layerData.ty === 4) { completeClosingShapes(layerData.shapes); } } } return function(animationData) { if (checkVersion(minimumVersion, animationData.v)) { iterateLayers(animationData.layers); if (animationData.assets) { var i4; var len = animationData.assets.length; for (i4 = 0; i4 < len; i4 += 1) { if (animationData.assets[i4].layers) { iterateLayers(animationData.assets[i4].layers); } } } } }; })(); function completeData(animationData) { if (animationData.__complete) { return; } checkColors(animationData); checkText(animationData); checkChars(animationData); checkPathProperties(animationData); checkShapes(animationData); completeLayers(animationData.layers, animationData.assets); completeChars(animationData.chars, animationData.assets); animationData.__complete = true; } function completeText(data) { if (data.t.a.length === 0 && !("m" in data.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 (err) { } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { response = formatResponse(xhr); callback(response); } else { try { response = formatResponse(xhr); callback(response); } catch (err) { if (errorCallback) { errorCallback(err); } } } } }; try { xhr.open("GET", path, true); } catch (error) { xhr.open("GET", fullPath + "/" + path, true); } xhr.send(); } return { load: loadAsset }; })(); } if (e2.data.type === "loadAnimation") { _workerSelf.assetLoader.load( e2.data.path, e2.data.fullPath, function(data) { _workerSelf.dataManager.completeData(data); _workerSelf.postMessage({ id: e2.data.id, payload: data, status: "success" }); }, function() { _workerSelf.postMessage({ id: e2.data.id, status: "error" }); } ); } else if (e2.data.type === "complete") { var animation = e2.data.animation; _workerSelf.dataManager.completeData(animation); _workerSelf.postMessage({ id: e2.data.id, payload: animation, status: "success" }); } else if (e2.data.type === "loadData") { _workerSelf.assetLoader.load( e2.data.path, e2.data.fullPath, function(data) { _workerSelf.postMessage({ id: e2.data.id, payload: data, status: "success" }); }, function() { _workerSelf.postMessage({ id: e2.data.id, status: "error" }); } ); } }); workerInstance.onmessage = function(event) { var data = event.data; var id = data.id; var process2 = processes[id]; processes[id] = null; if (data.status === "success") { process2.onComplete(data.payload); } else if (process2.onError) { process2.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() { ob.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 ob = { img, assetData }; return ob; } 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() { ob.img = proxyImage; this._imageLoaded(); }).bind(this), false ); img.src = path; var ob = { img, assetData }; return ob; } function createFootageData(data) { var ob = { assetData: data }; var path = getAssetsPath(data, this.assetsPath, this.path); dataManager.loadData( path, (function(footageData) { ob.img = footageData; this._footageLoaded(); }).bind(this), (function() { ob.img = {}; this._footageLoaded(); }).bind(this) ); return ob; } function loadAssets(assets, cb2) { this.imagesLoadedCb = cb2; var i4; var len = assets.length; for (i4 = 0; i4 < len; i4 += 1) { if (!assets[i4].layers) { if (!assets[i4].t || assets[i4].t === "seq") { this.totalImages += 1; this.images.push(this._createImageData(assets[i4])); } else if (assets[i4].t === 3) { this.totalFootages += 1; this.images.push(this.createFootageData(assets[i4])); } } } } function setPath(path) { this.path = path || ""; } function setAssetsPath(path) { this.assetsPath = path || ""; } function getAsset(assetData) { var i4 = 0; var len = this.images.length; while (i4 < len) { if (this.images[i4].assetData === assetData) { return this.images[i4].img; } i4 += 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; })(); function BaseEvent() { } BaseEvent.prototype = { triggerEvent: function(eventName, args) { if (this._cbs[eventName]) { var callbacks = this._cbs[eventName]; for (var i4 = 0; i4 < callbacks.length; i4 += 1) { callbacks[i4](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 i4 = 0; var len = this._cbs[eventName].length; while (i4 < len) { if (this._cbs[eventName][i4] === callback) { this._cbs[eventName].splice(i4, 1); i4 -= 1; len -= 1; } i4 += 1; } if (!this._cbs[eventName].length) { this._cbs[eventName] = null; } } } }; const markerParser = /* @__PURE__ */ (function() { function parsePayloadLines(payload) { var lines = payload.split("\r\n"); var keys = {}; var line; var keysCount = 0; for (var i4 = 0; i4 < lines.length; i4 += 1) { line = lines[i4].split(":"); if (line.length === 2) { keys[line[0]] = line[1].trim(); keysCount += 1; } } if (keysCount === 0) { throw new Error(); } return keys; } return function(_markers) { var markers = []; for (var i4 = 0; i4 < _markers.length; i4 += 1) { var _marker = _markers[i4]; var markerData = { time: _marker.tm, duration: _marker.dr }; try { markerData.payload = JSON.parse(_markers[i4].cm); } catch (_) { try { markerData.payload = parsePayloadLines(_markers[i4].cm); } catch (__) { markerData.payload = { name: _markers[i4].cm }; } } markers.push(markerData); } return markers; }; })(); const ProjectInterface = /* @__PURE__ */ (function() { function registerComposition(comp) { this.compositions.push(comp); } return function() { function _thisProjectFunction(name) { var i4 = 0; var len = this.compositions.length; while (i4 < len) { if (this.compositions[i4].data && this.compositions[i4].data.nm === name) { if (this.compositions[i4].prepareFrame && this.compositions[i4].data.xt) { this.compositions[i4].prepareFrame(this.currentFrame); } return this.compositions[i4].compInterface; } i4 += 1; } return null; } _thisProjectFunction.compositions = []; _thisProjectFunction.currentFrame = 0; _thisProjectFunction.registerComposition = registerComposition; return _thisProjectFunction; }; })(); const renderers = {}; const registerRenderer = (key, value) => { renderers[key] = value; }; function getRenderer(key) { return renderers[key]; } 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(data) { dataManager.completeAnimation(data, this.configAnimation); }; AnimationItem.prototype.setData = function(wrapper, animationData) { if (animationData) { if (typeof animationData !== "object") { animationData = JSON.parse(animationData); } } var params = { wrapper, animationData }; 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(data) { if (data.op > this.animationData.op) { this.animationData.op = data.op; this.totalFrames = Math.floor(data.op - this.animationData.ip); } var layers = this.animationData.layers; var i4; var len = layers.length; var newLayers = data.layers; var j; var jLen = newLayers.length; for (j = 0; j < jLen; j += 1) { i4 = 0; while (i4 < len) { if (layers[i4].id === newLayers[j].id) { layers[i4] = newLayers[j]; break; } i4 += 1; } } if (data.chars || data.fonts) { this.renderer.globalData.fontManager.addChars(data.chars); this.renderer.globalData.fontManager.addFonts(data.fonts, this.renderer.globalData.defs); } if (data.assets) { len = data.assets.length; for (i4 = 0; i4 < len; i4 += 1) { this.animationData.assets.push(data.assets[i4]); } } this.animationData.__complete = false; dataManager.completeAnimation(this.animationData, this.onSegmentComplete); }; AnimationItem.prototype.onSegmentComplete = function(data) { this.animationData = data; 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(name) { if (name && this.name !== name) { 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(name) { if (name && this.name !== name) { return; } if (this.isPaused === false) { this.isPaused = true; this.trigger("_play"); this._idle = true; this.trigger("_idle"); this.audioController.pause(); } }; AnimationItem.prototype.togglePause = function(name) { if (name && this.name !== name) { return; } if (this.isPaused === true) { this.play(); } else { this.pause(); } }; AnimationItem.prototype.stop = function(name) { if (name && this.name !== name) { return; } this.pause(); this.playCount = 0; this._completedLoop = false; this.setCurrentRawFrameValue(0); }; AnimationItem.prototype.getMarkerData = function(markerName) { var marker; for (var i4 = 0; i4 < this.markers.length; i4 += 1) { marker = this.markers[i4]; if (marker.payload && marker.payload.name === markerName) { return marker; } } return null; }; AnimationItem.prototype.goToAndStop = function(value, isFrame, name) { if (name && this.name !== name) { return; } var numValue = Number(value); if (isNaN(numValue)) { var marker = this.getMarkerData(value); if (marker) { this.goToAndStop(marker.time, true); } } else if (isFrame) { this.setCurrentRawFrameValue(value); } else { this.setCurrentRawFrameValue(value * this.frameModifier); } this.pause(); }; AnimationItem.prototype.goToAndPlay = function(value, isFrame, name) { if (name && this.name !== name) { return; } var numValue = Number(value); if (isNaN(numValue)) { var marker = this.getMarkerData(value); 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, name); } this.play(); }; AnimationItem.prototype.advanceTime = function(value) { if (this.isPaused === true || this.isLoaded === false) { return; } var nextValue = this.currentRawFrame + value * 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(init3, end) { var pendingFrame = -1; if (this.isPaused) { if (this.currentRawFrame + this.firstFrame < init3) { pendingFrame = init3; } else if (this.currentRawFrame + this.firstFrame > end) { pendingFrame = end - init3; } } this.firstFrame = init3; this.totalFrames = end - init3; 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 i4; var len = arr.length; for (i4 = 0; i4 < len; i4 += 1) { this.segments.push(arr[i4]); } } 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(name) { if (name && this.name !== name || !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(value) { this.currentRawFrame = value; this.gotoFrame(); }; AnimationItem.prototype.setSpeed = function(val) { this.playSpeed = val; this.updaFrameModifier(); }; AnimationItem.prototype.setDirection = function(val) { this.playDirection = val < 0 ? -1 : 1; this.updaFrameModifier(); }; AnimationItem.prototype.setVolume = function(val, name) { if (name && this.name !== name) { return; } this.audioController.setVolume(val); }; AnimationItem.prototype.getVolume = function() { return this.audioController.getVolume(); }; AnimationItem.prototype.mute = function(name) { if (name && this.name !== name) { return; } this.audioController.mute(); }; AnimationItem.prototype.unmute = function(name) { if (name && this.name !== name) { 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 i4 = 0; var len = this.assets.length; while (i4 < len) { if (id === this.assets[i4].id) { return this.assets[i4]; } i4 += 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, index22) { try { var element = this.renderer.getElementByPath(path); element.updateDocumentData(documentData, index22); } catch (error) { } }; AnimationItem.prototype.trigger = function(name) { if (this._cbs && this._cbs[name]) { switch (name) { case "enterFrame": this.triggerEvent(name, new BMEnterFrameEvent(name, 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(name, this.drawnFrameEvent); break; case "loopComplete": this.triggerEvent(name, new BMCompleteLoopEvent(name, this.loop, this.playCount, this.frameMult)); break; case "complete": this.triggerEvent(name, new BMCompleteEvent(name, this.frameMult)); break; case "segmentStart": this.triggerEvent(name, new BMSegmentStartEvent(name, this.firstFrame, this.totalFrames)); break; case "destroy": this.triggerEvent(name, new BMDestroyEvent(name, this)); break; default: this.triggerEvent(name); } } if (name === "enterFrame" && this.onEnterFrame) { this.onEnterFrame.call(this, new BMEnterFrameEvent(name, this.currentFrame, this.totalFrames, this.frameMult)); } if (name === "loopComplete" && this.onLoopComplete) { this.onLoopComplete.call(this, new BMCompleteLoopEvent(name, this.loop, this.playCount, this.frameMult)); } if (name === "complete" && this.onComplete) { this.onComplete.call(this, new BMCompleteEvent(name, this.frameMult)); } if (name === "segmentStart" && this.onSegmentStart) { this.onSegmentStart.call(this, new BMSegmentStartEvent(name, this.firstFrame, this.totalFrames)); } if (name === "destroy" && this.onDestroy) { this.onDestroy.call(this, new BMDestroyEvent(name, 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 i4 = 0; var animItem = ev.target; while (i4 < len) { if (registeredAnimations[i4].animation === animItem) { registeredAnimations.splice(i4, 1); i4 -= 1; len -= 1; if (!animItem.isPaused) { subtractPlayingCount(); } } i4 += 1; } } function registerAnimation(element, animationData) { if (!element) { return null; } var i4 = 0; while (i4 < len) { if (registeredAnimations[i4].elem === element && registeredAnimations[i4].elem !== null) { return registeredAnimations[i4].animation; } i4 += 1; } var animItem = new AnimationItem(); setupAnimation(animItem, element); animItem.setData(element, animationData); return animItem; } function getRegisteredAnimations() { var i4; var lenAnims = registeredAnimations.length; var animations = []; for (i4 = 0; i4 < lenAnims; i4 += 1) { animations.push(registeredAnimations[i4].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(val, animation) { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].animation.setSpeed(val, animation); } } function setDirection(val, animation) { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].animation.setDirection(val, animation); } } function play(animation) { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].animation.play(animation); } } function resume(nowTime) { var elapsedTime = nowTime - initTime; var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].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 i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].animation.pause(animation); } } function goToAndStop(value, isFrame, animation) { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].animation.goToAndStop(value, isFrame, animation); } } function stop(animation) { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].animation.stop(animation); } } function togglePause(animation) { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].animation.togglePause(animation); } } function destroy(animation) { var i4; for (i4 = len - 1; i4 >= 0; i4 -= 1) { registeredAnimations[i4].animation.destroy(animation); } } function searchAnimations2(animationData, standalone, renderer) { var animElements = [].concat( [].slice.call(document.getElementsByClassName("lottie")), [].slice.call(document.getElementsByClassName("bodymovin")) ); var i4; var lenAnims = animElements.length; for (i4 = 0; i4 < lenAnims; i4 += 1) { if (renderer) { animElements[i4].setAttribute("data-bm-type", renderer); } registerAnimation(animElements[i4], animationData); } if (standalone && lenAnims === 0) { if (!renderer) { renderer = "svg"; } var body = document.getElementsByTagName("body")[0]; body.innerText = ""; var div = createTag("div"); div.style.width = "100%"; div.style.height = "100%"; div.setAttribute("data-bm-type", renderer); body.appendChild(div); registerAnimation(div, animationData); } } function resize() { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].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(val, animation) { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].animation.setVolume(val, animation); } } function mute(animation) { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].animation.mute(animation); } } function unmute(animation) { var i4; for (i4 = 0; i4 < len; i4 += 1) { registeredAnimations[i4].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 ob = {}; ob.getBezierEasing = getBezierEasing; var beziers = {}; function getBezierEasing(a6, b5, c2, d2, nm) { var str = nm || ("bez_" + a6 + "_" + b5 + "_" + c2 + "_" + d2).replace(/\./g, "p"); if (beziers[str]) { return beziers[str]; } var bezEasing = new BezierEasing([a6, b5, c2, d2]); 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 A(aA1, aA2) { return 1 - 3 * aA2 + 3 * aA1; } function B(aA1, aA2) { return 3 * aA2 - 6 * aA1; } function C(aA1) { return 3 * aA1; } function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; } function getSlope(aT, aA1, aA2) { return 3 * A(aA1, aA2) * aT * aT + 2 * B(aA1, aA2) * aT + C(aA1); } function binarySubdivide(aX, aA, aB, mX1, mX2) { var currentX, currentT, i4 = 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 && ++i4 < SUBDIVISION_MAX_ITERATIONS); return currentT; } function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { for (var i4 = 0; i4 < NEWTON_ITERATIONS; ++i4) { 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(x) { 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 x; if (x === 0) return 0; if (x === 1) return 1; return calcBezier(this._getTForX(x), 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 i4 = 0; i4 < kSplineTableSize; ++i4) { this._mSampleValues[i4] = calcBezier(i4 * 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 ob; })(); 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 ob = { 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 ob; }; })(); const bezierLengthPool = (function() { function create4() { return { addedLength: 0, percents: createTypedArray("float32", getDefaultCurveSegments()), lengths: createTypedArray("float32", getDefaultCurveSegments()) }; } return poolFactory(8, create4); })(); const segmentsLengthPool = (function() { function create4() { return { lengths: [], totalLength: 0 }; } function release(element) { var i4; var len = element.lengths.length; for (i4 = 0; i4 < len; i4 += 1) { bezierLengthPool.release(element.lengths[i4]); } element.lengths.length = 0; } return poolFactory(8, create4, release); })(); 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 k; var i4; var len; var ptCoord; var perc; var addedLength = 0; var ptDistance; var point = []; var lastPoint = []; var lengthData = bezierLengthPool.newElement(); len = pt3.length; for (k = 0; k < curveSegments; k += 1) { perc = k / (curveSegments - 1); ptDistance = 0; for (i4 = 0; i4 < len; i4 += 1) { ptCoord = bmPow(1 - perc, 3) * pt1[i4] + 3 * bmPow(1 - perc, 2) * perc * pt3[i4] + 3 * (1 - perc) * bmPow(perc, 2) * pt4[i4] + bmPow(perc, 3) * pt2[i4]; point[i4] = ptCoord; if (lastPoint[i4] !== null) { ptDistance += bmPow(point[i4] - lastPoint[i4], 2); } lastPoint[i4] = point[i4]; } if (ptDistance) { ptDistance = bmSqrt(ptDistance); addedLength += ptDistance; } lengthData.percents[k] = perc; lengthData.lengths[k] = 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 i4; var len = shapeData._length; var lengths = segmentsLength.lengths; var totalLength = 0; for (i4 = 0; i4 < len - 1; i4 += 1) { lengths[i4] = getBezierLength(pathV[i4], pathV[i4 + 1], pathO[i4], pathI[i4 + 1]); totalLength += lengths[i4].addedLength; } if (closed && len) { lengths[i4] = getBezierLength(pathV[i4], pathV[0], pathO[i4], pathI[0]); totalLength += lengths[i4].addedLength; } segmentsLength.totalLength = totalLength; return segmentsLength; } function BezierData(length3) { this.segmentLength = 0; this.points = new Array(length3); } function PointData(partial, point) { this.partialLength = partial; 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 k; var i4; 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 (k = 0; k < curveSegments; k += 1) { point = createSizedArray(len); perc = k / (curveSegments - 1); ptDistance = 0; for (i4 = 0; i4 < len; i4 += 1) { ptCoord = bmPow(1 - perc, 3) * pt1[i4] + 3 * bmPow(1 - perc, 2) * perc * (pt1[i4] + pt3[i4]) + 3 * (1 - perc) * bmPow(perc, 2) * (pt2[i4] + pt4[i4]) + bmPow(perc, 3) * pt2[i4]; point[i4] = ptCoord; if (lastPoint !== null) { ptDistance += bmPow(point[i4] - lastPoint[i4], 2); } } ptDistance = bmSqrt(ptDistance); addedLength += ptDistance; bezierData.points[k] = new PointData(ptDistance, point); lastPoint = point; } bezierData.segmentLength = addedLength; storedData[bezierName] = bezierData; } return storedData[bezierName]; }; })(); function getDistancePerc(perc, bezierData) { var percents = bezierData.percents; var lengths = 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 === lengths[initPos]) { return percents[initPos]; } var dir = lengths[initPos] > lengthPos ? -1 : 1; var flag = true; while (flag) { if (lengths[initPos] <= lengthPos && lengths[initPos + 1] > lengthPos) { lPerc = (lengthPos - lengths[initPos]) / (lengths[initPos + 1] - lengths[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 i4; 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 (i4 = 0; i4 < len; i4 += 1) { bezierSegmentPoints[i4 * 4] = math.round((u0u0u0 * pt1[i4] + t0u0u0_3 * pt3[i4] + t0t0u0_3 * pt4[i4] + t0t0t0 * pt2[i4]) * 1e3) / 1e3; bezierSegmentPoints[i4 * 4 + 1] = math.round((u0u0u1 * pt1[i4] + t0u0u1_3 * pt3[i4] + t0t0u1_3 * pt4[i4] + t0t0t1 * pt2[i4]) * 1e3) / 1e3; bezierSegmentPoints[i4 * 4 + 2] = math.round((u0u1u1 * pt1[i4] + t0u1u1_3 * pt3[i4] + t0t1u1_3 * pt4[i4] + t0t1t1 * pt2[i4]) * 1e3) / 1e3; bezierSegmentPoints[i4 * 4 + 3] = math.round((u1u1u1 * pt1[i4] + t1u1u1_3 * pt3[i4] + t1t1u1_3 * pt4[i4] + t1t1t1 * pt2[i4]) * 1e3) / 1e3; } return bezierSegmentPoints; } return { getSegmentsLength, getNewSegment, getPointInSegment, buildBezierData, pointOnLine2D, pointOnLine3D }; } 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 i4 = iterationIndex; var len = this.keyframes.length - 1; var flag = true; var keyData; var nextKeyData; var keyframeMetadata; while (flag) { keyData = this.keyframes[i4]; nextKeyData = this.keyframes[i4 + 1]; if (i4 === len - 1 && frameNum >= nextKeyData.t - offsetTime) { if (keyData.h) { keyData = nextKeyData; } iterationIndex = 0; break; } if (nextKeyData.t - offsetTime > frameNum) { iterationIndex = i4; break; } if (i4 < len - 1) { i4 += 1; } else { iterationIndex = 0; flag = false; } } keyframeMetadata = this.keyframesMetadata[i4] || {}; var k; var kLen; var perc; var jLen; var j; 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 (k = 0; k < kLen; k += 1) { newValue[k] = bezierData.points[ind].point[k]; } } 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 === i4 ? caching._lastAddedLength : 0; j = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i4 ? caching._lastPoint : 0; flag = true; jLen = bezierData.points.length; while (flag) { addedLength += bezierData.points[j].partialLength; if (distanceInLine === 0 || perc === 0 || j === bezierData.points.length - 1) { kLen = bezierData.points[j].point.length; for (k = 0; k < kLen; k += 1) { newValue[k] = bezierData.points[j].point[k]; } break; } else if (distanceInLine >= addedLength && distanceInLine < addedLength + bezierData.points[j + 1].partialLength) { segmentPerc = (distanceInLine - addedLength) / bezierData.points[j + 1].partialLength; kLen = bezierData.points[j].point.length; for (k = 0; k < kLen; k += 1) { newValue[k] = bezierData.points[j].point[k] + (bezierData.points[j + 1].point[k] - bezierData.points[j].point[k]) * segmentPerc; } break; } if (j < jLen - 1) { j += 1; } else { flag = false; } } caching._lastPoint = j; caching._lastAddedLength = addedLength - bezierData.points[j].partialLength; caching._lastKeyframeIndex = i4; } } 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 time = (frameNum - keyTime) / (nextKeyTime - keyTime); quaternionToEuler(newValue, slerp(quatStart, quatEnd, time)); } } else { for (i4 = 0; i4 < len; i4 += 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[i4]) { outX = keyData.o.x[i4] === void 0 ? keyData.o.x[0] : keyData.o.x[i4]; outY = keyData.o.y[i4] === void 0 ? keyData.o.y[0] : keyData.o.y[i4]; inX = keyData.i.x[i4] === void 0 ? keyData.i.x[0] : keyData.i.x[i4]; inY = keyData.i.y[i4] === void 0 ? keyData.i.y[0] : keyData.i.y[i4]; fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; keyframeMetadata.__fnct[i4] = fnc; } else { fnc = keyframeMetadata.__fnct[i4]; } } 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[i4] : keyData.s[i4] + (endValue[i4] - keyData.s[i4]) * perc; if (this.propType === "multidimensional") { newValue[i4] = keyValue; } else { newValue = keyValue; } } } } caching.lastIndex = iterationIndex; return newValue; } function slerp(a6, b5, t3) { var out7 = []; var ax = a6[0]; var ay = a6[1]; var az = a6[2]; var aw = a6[3]; var bx = b5[0]; var by = b5[1]; var bz = b5[2]; var bw = b5[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; } out7[0] = scale0 * ax + scale1 * bx; out7[1] = scale0 * ay + scale1 * by; out7[2] = scale0 * az + scale1 * bz; out7[3] = scale0 * aw + scale1 * bw; return out7; } function quaternionToEuler(out7, 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); out7[0] = heading / degToRads; out7[1] = attitude / degToRads; out7[2] = bank / degToRads; } function createQuaternion(values) { var heading = values[0] * degToRads; var attitude = values[1] * degToRads; var bank = values[2] * degToRads; var c1 = Math.cos(heading / 2); var c2 = Math.cos(attitude / 2); var c32 = 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 * c32 - s1 * s2 * s3; var x = s1 * s2 * c32 + c1 * c2 * s3; var y = s1 * c2 * c32 + c1 * s2 * s3; var z = c1 * s2 * c32 - s1 * c2 * s3; return [x, 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(val) { var multipliedValue; if (this.propType === "unidimensional") { multipliedValue = val * this.mult; if (mathAbs(this.v - multipliedValue) > 1e-5) { this.v = multipliedValue; this._mdf = true; } } else { var i4 = 0; var len = this.v.length; while (i4 < len) { multipliedValue = val[i4] * this.mult; if (mathAbs(this.v[i4] - multipliedValue) > 1e-5) { this.v[i4] = multipliedValue; this._mdf = true; } i4 += 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 i4; var len = this.effectsSequence.length; var finalValue = this.kf ? this.pv : this.data.k; for (i4 = 0; i4 < len; i4 += 1) { finalValue = this.effectsSequence[i4](finalValue); } this.setVValue(finalValue); this._isFirstFrame = false; this.lock = false; this.frameId = this.elem.globalData.frameId; } function addEffect2(effectFunction) { this.effectsSequence.push(effectFunction); this.container.addDynamicProperty(this); } function ValueProperty(elem, data, mult, container) { this.propType = "unidimensional"; this.mult = mult || 1; this.data = data; this.v = mult ? data.k * mult : data.k; this.pv = data.k; this._mdf = false; this.elem = elem; this.container = container; this.comp = elem.comp; this.k = false; this.kf = false; this.vel = 0; this.effectsSequence = []; this._isFirstFrame = true; this.getValue = processEffectsSequence; this.setVValue = setVValue; this.addEffect = addEffect2; } function MultiDimensionalProperty(elem, data, mult, container) { this.propType = "multidimensional"; this.mult = mult || 1; this.data = data; this._mdf = false; this.elem = elem; this.container = container; this.comp = elem.comp; this.k = false; this.kf = false; this.frameId = -1; var i4; var len = data.k.length; this.v = createTypedArray("float32", len); this.pv = createTypedArray("float32", len); this.vel = createTypedArray("float32", len); for (i4 = 0; i4 < len; i4 += 1) { this.v[i4] = data.k[i4] * this.mult; this.pv[i4] = data.k[i4]; } this._isFirstFrame = true; this.effectsSequence = []; this.getValue = processEffectsSequence; this.setVValue = setVValue; this.addEffect = addEffect2; } function KeyframedValueProperty(elem, data, mult, container) { this.propType = "unidimensional"; this.keyframes = data.k; this.keyframesMetadata = []; this.offsetTime = elem.data.st; this.frameId = -1; this._caching = { lastFrame: initFrame, lastIndex: 0, value: 0, _lastKeyframeIndex: -1 }; this.k = true; this.kf = true; this.data = data; this.mult = mult || 1; this.elem = elem; this.container = container; this.comp = elem.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 = addEffect2; } function KeyframedMultidimensionalProperty(elem, data, mult, container) { this.propType = "multidimensional"; var i4; var len = data.k.length; var s2; var e2; var to; var ti; for (i4 = 0; i4 < len - 1; i4 += 1) { if (data.k[i4].to && data.k[i4].s && data.k[i4 + 1] && data.k[i4 + 1].s) { s2 = data.k[i4].s; e2 = data.k[i4 + 1].s; to = data.k[i4].to; ti = data.k[i4].ti; if (s2.length === 2 && !(s2[0] === e2[0] && s2[1] === e2[1]) && bez.pointOnLine2D(s2[0], s2[1], e2[0], e2[1], s2[0] + to[0], s2[1] + to[1]) && bez.pointOnLine2D(s2[0], s2[1], e2[0], e2[1], e2[0] + ti[0], e2[1] + ti[1]) || s2.length === 3 && !(s2[0] === e2[0] && s2[1] === e2[1] && s2[2] === e2[2]) && bez.pointOnLine3D(s2[0], s2[1], s2[2], e2[0], e2[1], e2[2], s2[0] + to[0], s2[1] + to[1], s2[2] + to[2]) && bez.pointOnLine3D(s2[0], s2[1], s2[2], e2[0], e2[1], e2[2], e2[0] + ti[0], e2[1] + ti[1], e2[2] + ti[2])) { data.k[i4].to = null; data.k[i4].ti = null; } if (s2[0] === e2[0] && s2[1] === e2[1] && to[0] === 0 && to[1] === 0 && ti[0] === 0 && ti[1] === 0) { if (s2.length === 2 || s2[2] === e2[2] && to[2] === 0 && ti[2] === 0) { data.k[i4].to = null; data.k[i4].ti = null; } } } } this.effectsSequence = [getValueAtCurrentTime.bind(this)]; this.data = data; this.keyframes = data.k; this.keyframesMetadata = []; this.offsetTime = elem.data.st; this.k = true; this.kf = true; this._isFirstFrame = true; this.mult = mult || 1; this.elem = elem; this.container = container; this.comp = elem.comp; this.getValue = processEffectsSequence; this.setVValue = setVValue; this.interpolateValue = interpolateValue; this.frameId = -1; var arrLen = data.k[0].s.length; this.v = createTypedArray("float32", arrLen); this.pv = createTypedArray("float32", arrLen); for (i4 = 0; i4 < arrLen; i4 += 1) { this.v[i4] = initFrame; this.pv[i4] = initFrame; } this._caching = { lastFrame: initFrame, lastIndex: 0, value: createTypedArray("float32", arrLen) }; this.addEffect = addEffect2; } function getProp(elem, data, type, mult, container) { var p2; if (!data.k.length) { p2 = new ValueProperty(elem, data, mult, container); } else if (typeof data.k[0] === "number") { p2 = new MultiDimensionalProperty(elem, data, mult, container); } else { switch (type) { case 0: p2 = new KeyframedValueProperty(elem, data, mult, container); break; case 1: p2 = new KeyframedMultidimensionalProperty(elem, data, mult, container); break; } } if (p2.effectsSequence.length) { container.addDynamicProperty(p2); } return p2; } var ob = { getProp }; return ob; })(); function DynamicPropertyContainer() { } 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 i4; var len = this.dynamicProperties.length; for (i4 = 0; i4 < len; i4 += 1) { this.dynamicProperties[i4].getValue(); if (this.dynamicProperties[i4]._mdf) { this._mdf = true; } } }, initDynamicPropertyContainer: function(container) { this.container = container; this.dynamicProperties = []; this._mdf = false; this._isAnimated = false; } }; const pointPool = (function() { function create4() { return createTypedArray("float32", 2); } return poolFactory(8, create4); })(); function ShapePath2() { this.c = false; this._length = 0; this._maxLength = 8; this.v = createSizedArray(this._maxLength); this.o = createSizedArray(this._maxLength); this.i = createSizedArray(this._maxLength); } ShapePath2.prototype.setPathData = function(closed, len) { this.c = closed; this.setLength(len); var i4 = 0; while (i4 < len) { this.v[i4] = pointPool.newElement(); this.o[i4] = pointPool.newElement(); this.i[i4] = pointPool.newElement(); i4 += 1; } }; ShapePath2.prototype.setLength = function(len) { while (this._maxLength < len) { this.doubleArrayLength(); } this._length = len; }; ShapePath2.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; }; ShapePath2.prototype.setXYAt = function(x, 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] = x; arr[pos][1] = y; }; ShapePath2.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); }; ShapePath2.prototype.reverse = function() { var newPath = new ShapePath2(); newPath.setPathData(this.c, this._length); var vertices = this.v; var outPoints = this.o; var inPoints = this.i; var init3 = 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 ); init3 = 1; } var cnt = this._length - 1; var len = this._length; var i4; for (i4 = init3; i4 < len; i4 += 1) { newPath.setTripleAt( vertices[cnt][0], vertices[cnt][1], inPoints[cnt][0], inPoints[cnt][1], outPoints[cnt][0], outPoints[cnt][1], i4, false ); cnt -= 1; } return newPath; }; const shapePool = (function() { function create4() { return new ShapePath2(); } function release(shapePath) { var len = shapePath._length; var i4; for (i4 = 0; i4 < len; i4 += 1) { pointPool.release(shapePath.v[i4]); pointPool.release(shapePath.i[i4]); pointPool.release(shapePath.o[i4]); shapePath.v[i4] = null; shapePath.i[i4] = null; shapePath.o[i4] = null; } shapePath._length = 0; shapePath.c = false; } function clone2(shape) { var cloned = factory.newElement(); var i4; var len = shape._length === void 0 ? shape.v.length : shape._length; cloned.setLength(len); cloned.c = shape.c; for (i4 = 0; i4 < len; i4 += 1) { cloned.setTripleAt(shape.v[i4][0], shape.v[i4][1], shape.o[i4][0], shape.o[i4][1], shape.i[i4][0], shape.i[i4][1], i4); } return cloned; } var factory = poolFactory(4, create4, release); factory.clone = clone2; return factory; })(); function ShapeCollection() { this._length = 0; this._maxLength = 4; this.shapes = createSizedArray(this._maxLength); } 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 i4; for (i4 = 0; i4 < this._length; i4 += 1) { shapePool.release(this.shapes[i4]); } this._length = 0; }; const shapeCollectionPool = (function() { var ob = { 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 i4; var len = shapeCollection._length; for (i4 = 0; i4 < len; i4 += 1) { shapePool.release(shapeCollection.shapes[i4]); } shapeCollection._length = 0; if (_length === _maxLength) { pool = pooling.double(pool); _maxLength *= 2; } pool[_length] = shapeCollection; _length += 1; } return ob; })(); const ShapePropertyFactory = (function() { var initFrame = -999999; function interpolateShape(frameNum, previousValue, caching) { var iterationIndex = caching.lastIndex; var keyPropS; var keyPropE; var isHold; var j; var k; 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 i4 = iterationIndex; var len = kf.length - 1; var flag = true; var keyData; var nextKeyData; var keyframeMetadata; while (flag) { keyData = kf[i4]; nextKeyData = kf[i4 + 1]; if (nextKeyData.t - this.offsetTime > frameNum) { break; } if (i4 < len - 1) { i4 += 1; } else { flag = false; } } keyframeMetadata = this.keyframesMetadata[i4] || {}; isHold = keyData.h === 1; iterationIndex = i4; 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 (j = 0; j < jLen; j += 1) { for (k = 0; k < kLen; k += 1) { vertexValue = isHold ? keyPropS.i[j][k] : keyPropS.i[j][k] + (keyPropE.i[j][k] - keyPropS.i[j][k]) * perc; previousValue.i[j][k] = vertexValue; vertexValue = isHold ? keyPropS.o[j][k] : keyPropS.o[j][k] + (keyPropE.o[j][k] - keyPropS.o[j][k]) * perc; previousValue.o[j][k] = vertexValue; vertexValue = isHold ? keyPropS.v[j][k] : keyPropS.v[j][k] + (keyPropE.v[j][k] - keyPropS.v[j][k]) * perc; previousValue.v[j][k] = 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 i4; var len = shape1._length; for (i4 = 0; i4 < len; i4 += 1) { if (shape1.v[i4][0] !== shape2.v[i4][0] || shape1.v[i4][1] !== shape2.v[i4][1] || shape1.o[i4][0] !== shape2.o[i4][0] || shape1.o[i4][1] !== shape2.o[i4][1] || shape1.i[i4][0] !== shape2.i[i4][0] || shape1.i[i4][1] !== shape2.i[i4][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 i4; var len = this.effectsSequence.length; for (i4 = 0; i4 < len; i4 += 1) { finalValue = this.effectsSequence[i4](finalValue); } this.setVValue(finalValue); this.lock = false; this.frameId = this.elem.globalData.frameId; } function ShapeProperty(elem, data, type) { this.propType = "shape"; this.comp = elem.comp; this.container = elem; this.elem = elem; this.data = data; this.k = false; this.kf = false; this._mdf = false; var pathData = type === 3 ? data.pt.k : data.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 addEffect2(effectFunction) { this.effectsSequence.push(effectFunction); this.container.addDynamicProperty(this); } ShapeProperty.prototype.interpolateShape = interpolateShape; ShapeProperty.prototype.getValue = processEffectsSequence; ShapeProperty.prototype.setVValue = setVValue; ShapeProperty.prototype.addEffect = addEffect2; function KeyframedShapeProperty(elem, data, type) { this.propType = "shape"; this.comp = elem.comp; this.elem = elem; this.container = elem; this.offsetTime = elem.data.st; this.keyframes = type === 3 ? data.pt.k : data.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 = addEffect2; var EllShapeProperty = (function() { var cPoint = roundCorner; function EllShapePropertyFactory(elem, data) { this.v = shapePool.newElement(); this.v.setPathData(true, 4); this.localShapeCollection = shapeCollectionPool.newShapeCollection(); this.paths = this.localShapeCollection; this.localShapeCollection.addShape(this.v); this.d = data.d; this.elem = elem; this.comp = elem.comp; this.frameId = -1; this.initDynamicPropertyContainer(elem); this.p = PropertyFactory.getProp(elem, data.p, 1, 0, this); this.s = PropertyFactory.getProp(elem, data.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(elem, data) { this.v = shapePool.newElement(); this.v.setPathData(true, 0); this.elem = elem; this.comp = elem.comp; this.data = data; this.frameId = -1; this.d = data.d; this.initDynamicPropertyContainer(elem); if (data.sy === 1) { this.ir = PropertyFactory.getProp(elem, data.ir, 0, 0, this); this.is = PropertyFactory.getProp(elem, data.is, 0, 0.01, this); this.convertToPath = this.convertStarToPath; } else { this.convertToPath = this.convertPolygonToPath; } this.pt = PropertyFactory.getProp(elem, data.pt, 0, 0, this); this.p = PropertyFactory.getProp(elem, data.p, 1, 0, this); this.r = PropertyFactory.getProp(elem, data.r, 0, degToRads, this); this.or = PropertyFactory.getProp(elem, data.or, 0, 0, this); this.os = PropertyFactory.getProp(elem, data.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 i4; 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 (i4 = 0; i4 < numPts; i4 += 1) { rad = longFlag ? longRad : shortRad; roundness = longFlag ? longRound : shortRound; perimSegment = longFlag ? longPerimSegment : shortPerimSegment; var x = rad * Math.cos(currentAng); var y = rad * Math.sin(currentAng); var ox = x === 0 && y === 0 ? 0 : y / Math.sqrt(x * x + y * y); var oy = x === 0 && y === 0 ? 0 : -x / Math.sqrt(x * x + y * y); x += +this.p.v[0]; y += +this.p.v[1]; this.v.setTripleAt( x, y, x - ox * perimSegment * roundness * dir, y - oy * perimSegment * roundness * dir, x + ox * perimSegment * roundness * dir, y + oy * perimSegment * roundness * dir, i4, 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 i4; var currentAng = -Math.PI * 0.5; var dir = this.data.d === 3 ? -1 : 1; currentAng += this.r.v; this.v._length = 0; for (i4 = 0; i4 < numPts; i4 += 1) { var x = rad * Math.cos(currentAng); var y = rad * Math.sin(currentAng); var ox = x === 0 && y === 0 ? 0 : y / Math.sqrt(x * x + y * y); var oy = x === 0 && y === 0 ? 0 : -x / Math.sqrt(x * x + y * y); x += +this.p.v[0]; y += +this.p.v[1]; this.v.setTripleAt( x, y, x - ox * perimSegment * roundness * dir, y - oy * perimSegment * roundness * dir, x + ox * perimSegment * roundness * dir, y + oy * perimSegment * roundness * dir, i4, true ); currentAng += angle * dir; } this.paths.length = 0; this.paths[0] = this.v; } }; extendPrototype([DynamicPropertyContainer], StarShapePropertyFactory); return StarShapePropertyFactory; })(); var RectShapeProperty = (function() { function RectShapePropertyFactory(elem, data) { this.v = shapePool.newElement(); this.v.c = true; this.localShapeCollection = shapeCollectionPool.newShapeCollection(); this.localShapeCollection.addShape(this.v); this.paths = this.localShapeCollection; this.elem = elem; this.comp = elem.comp; this.frameId = -1; this.d = data.d; this.initDynamicPropertyContainer(elem); this.p = PropertyFactory.getProp(elem, data.p, 1, 0, this); this.s = PropertyFactory.getProp(elem, data.s, 1, 0, this); this.r = PropertyFactory.getProp(elem, data.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 v13 = this.s.v[1] / 2; var round = bmMin(v0, v13, 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 - v13 + round, p0 + v0, p1 - v13 + round, p0 + v0, p1 - v13 + cPoint, 0, true); this.v.setTripleAt(p0 + v0, p1 + v13 - round, p0 + v0, p1 + v13 - cPoint, p0 + v0, p1 + v13 - round, 1, true); if (round !== 0) { this.v.setTripleAt(p0 + v0 - round, p1 + v13, p0 + v0 - round, p1 + v13, p0 + v0 - cPoint, p1 + v13, 2, true); this.v.setTripleAt(p0 - v0 + round, p1 + v13, p0 - v0 + cPoint, p1 + v13, p0 - v0 + round, p1 + v13, 3, true); this.v.setTripleAt(p0 - v0, p1 + v13 - round, p0 - v0, p1 + v13 - round, p0 - v0, p1 + v13 - cPoint, 4, true); this.v.setTripleAt(p0 - v0, p1 - v13 + round, p0 - v0, p1 - v13 + cPoint, p0 - v0, p1 - v13 + round, 5, true); this.v.setTripleAt(p0 - v0 + round, p1 - v13, p0 - v0 + round, p1 - v13, p0 - v0 + cPoint, p1 - v13, 6, true); this.v.setTripleAt(p0 + v0 - round, p1 - v13, p0 + v0 - cPoint, p1 - v13, p0 + v0 - round, p1 - v13, 7, true); } else { this.v.setTripleAt(p0 - v0, p1 + v13, p0 - v0 + cPoint, p1 + v13, p0 - v0, p1 + v13, 2); this.v.setTripleAt(p0 - v0, p1 - v13, p0 - v0, p1 - v13 + cPoint, p0 - v0, p1 - v13, 3); } } else { this.v.setTripleAt(p0 + v0, p1 - v13 + round, p0 + v0, p1 - v13 + cPoint, p0 + v0, p1 - v13 + round, 0, true); if (round !== 0) { this.v.setTripleAt(p0 + v0 - round, p1 - v13, p0 + v0 - round, p1 - v13, p0 + v0 - cPoint, p1 - v13, 1, true); this.v.setTripleAt(p0 - v0 + round, p1 - v13, p0 - v0 + cPoint, p1 - v13, p0 - v0 + round, p1 - v13, 2, true); this.v.setTripleAt(p0 - v0, p1 - v13 + round, p0 - v0, p1 - v13 + round, p0 - v0, p1 - v13 + cPoint, 3, true); this.v.setTripleAt(p0 - v0, p1 + v13 - round, p0 - v0, p1 + v13 - cPoint, p0 - v0, p1 + v13 - round, 4, true); this.v.setTripleAt(p0 - v0 + round, p1 + v13, p0 - v0 + round, p1 + v13, p0 - v0 + cPoint, p1 + v13, 5, true); this.v.setTripleAt(p0 + v0 - round, p1 + v13, p0 + v0 - cPoint, p1 + v13, p0 + v0 - round, p1 + v13, 6, true); this.v.setTripleAt(p0 + v0, p1 + v13 - round, p0 + v0, p1 + v13 - round, p0 + v0, p1 + v13 - cPoint, 7, true); } else { this.v.setTripleAt(p0 - v0, p1 - v13, p0 - v0 + cPoint, p1 - v13, p0 - v0, p1 - v13, 1, true); this.v.setTripleAt(p0 - v0, p1 + v13, p0 - v0, p1 + v13 - cPoint, p0 - v0, p1 + v13, 2, true); this.v.setTripleAt(p0 + v0, p1 + v13, p0 + v0 - cPoint, p1 + v13, p0 + v0, p1 + v13, 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(elem, data, type) { var prop; if (type === 3 || type === 4) { var dataProp = type === 3 ? data.pt : data.ks; var keys = dataProp.k; if (keys.length) { prop = new KeyframedShapeProperty(elem, data, type); } else { prop = new ShapeProperty(elem, data, type); } } else if (type === 5) { prop = new RectShapeProperty(elem, data); } else if (type === 6) { prop = new EllShapeProperty(elem, data); } else if (type === 7) { prop = new StarShapeProperty(elem, data); } if (prop.k) { elem.addDynamicProperty(prop); } return prop; } function getConstructorFunction() { return ShapeProperty; } function getKeyframedConstructorFunction() { return KeyframedShapeProperty; } var ob = {}; ob.getShapeProp = getShapeProp; ob.getConstructorFunction = getConstructorFunction; ob.getKeyframedConstructorFunction = getKeyframedConstructorFunction; return ob; })(); const Matrix = /* @__PURE__ */ (function() { var _cos = Math.cos; var _sin = Math.sin; var _tan = Math.tan; var _rnd = Math.round; function reset2() { 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 rotate2(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 scale5(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(a6, b5, c2, d2, e2, f2, g, h, i4, j, k, l2, m, n2, o2, p2) { this.props[0] = a6; this.props[1] = b5; this.props[2] = c2; this.props[3] = d2; this.props[4] = e2; this.props[5] = f2; this.props[6] = g; this.props[7] = h; this.props[8] = i4; this.props[9] = j; this.props[10] = k; this.props[11] = l2; this.props[12] = m; this.props[13] = n2; this.props[14] = o2; this.props[15] = p2; return this; } function translate2(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 transform(a22, b23, c2, d2, e2, f2, g2, h2, i22, j2, k2, l2, m2, n2, o2, p2) { var _p2 = this.props; if (a22 === 1 && b23 === 0 && c2 === 0 && d2 === 0 && e2 === 0 && f2 === 1 && g2 === 0 && h2 === 0 && i22 === 0 && j2 === 0 && k2 === 1 && l2 === 0) { _p2[12] = _p2[12] * a22 + _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 * a22 + b1 * e2 + c1 * i22 + d1 * m2; _p2[1] = a1 * b23 + b1 * f2 + c1 * j2 + d1 * n2; _p2[2] = a1 * c2 + b1 * g2 + c1 * k2 + d1 * o2; _p2[3] = a1 * d2 + b1 * h2 + c1 * l2 + d1 * p2; _p2[4] = e1 * a22 + f1 * e2 + g1 * i22 + h1 * m2; _p2[5] = e1 * b23 + f1 * f2 + g1 * j2 + h1 * n2; _p2[6] = e1 * c2 + f1 * g2 + g1 * k2 + h1 * o2; _p2[7] = e1 * d2 + f1 * h2 + g1 * l2 + h1 * p2; _p2[8] = i1 * a22 + j1 * e2 + k1 * i22 + l1 * m2; _p2[9] = i1 * b23 + j1 * f2 + k1 * j2 + l1 * n2; _p2[10] = i1 * c2 + j1 * g2 + k1 * k2 + l1 * o2; _p2[11] = i1 * d2 + j1 * h2 + k1 * l2 + l1 * p2; _p2[12] = m1 * a22 + n1 * e2 + o1 * i22 + p1 * m2; _p2[13] = m1 * b23 + n1 * f2 + o1 * j2 + p1 * n2; _p2[14] = m1 * c2 + n1 * g2 + 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 equals(matr) { var i4 = 0; while (i4 < 16) { if (matr.props[i4] !== this.props[i4]) { return false; } i4 += 1; } return true; } function clone2(matr) { var i4; for (i4 = 0; i4 < 16; i4 += 1) { matr.props[i4] = this.props[i4]; } return matr; } function cloneFromProps(props) { var i4; for (i4 = 0; i4 < 16; i4 += 1) { this.props[i4] = props[i4]; } } function applyToPoint(x, y, z) { return { x: x * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12], y: x * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13], z: x * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14] }; } function applyToX(x, y, z) { return x * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12]; } function applyToY(x, y, z) { return x * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13]; } function applyToZ(x, y, z) { return x * 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 a6 = this.props[5] / determinant; var b5 = -this.props[1] / determinant; var c2 = -this.props[4] / determinant; var d2 = this.props[0] / determinant; var e2 = (this.props[4] * this.props[13] - this.props[5] * this.props[12]) / determinant; var f2 = -(this.props[0] * this.props[13] - this.props[1] * this.props[12]) / determinant; var inverseMatrix = new Matrix(); inverseMatrix.props[0] = a6; inverseMatrix.props[1] = b5; inverseMatrix.props[4] = c2; inverseMatrix.props[5] = d2; inverseMatrix.props[12] = e2; inverseMatrix.props[13] = f2; return inverseMatrix; } function inversePoint(pt) { var inverseMatrix = this.getInverseMatrix(); return inverseMatrix.applyToPointArray(pt[0], pt[1], pt[2] || 0); } function inversePoints(pts) { var i4; var len = pts.length; var retPts = []; for (i4 = 0; i4 < len; i4 += 1) { retPts[i4] = inversePoint(pts[i4]); } 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(x, y, z) { var arr; if (this.isIdentity()) { arr = [x, y, z]; } else { arr = [ x * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12], x * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13], x * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14] ]; } return arr; } function applyToPointStringified(x, y) { if (this.isIdentity()) { return x + "," + y; } var _p2 = this.props; return Math.round((x * _p2[0] + y * _p2[4] + _p2[12]) * 100) / 100 + "," + Math.round((x * _p2[1] + y * _p2[5] + _p2[13]) * 100) / 100; } function toCSS() { var i4 = 0; var props = this.props; var cssValue = "matrix3d("; var v5 = 1e4; while (i4 < 16) { cssValue += _rnd(props[i4] * v5) / v5; cssValue += i4 === 15 ? ")" : ","; i4 += 1; } return cssValue; } function roundMatrixProperty(val) { var v5 = 1e4; if (val < 1e-6 && val > 0 || val > -1e-6 && val < 0) { return _rnd(val * v5) / v5; } return val; } 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 = reset2; this.rotate = rotate2; this.rotateX = rotateX; this.rotateY = rotateY; this.rotateZ = rotateZ; this.skew = skew; this.skewFromAxis = skewFromAxis; this.shear = shear; this.scale = scale5; this.setTransform = setTransform; this.translate = translate2; this.transform = transform; 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 = equals; 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(); }; })(); const lottie2 = {}; function setLocation(href) { setLocationHref(href); } function searchAnimations() { { animationManager.searchAnimations(); } } function setSubframeRendering(flag) { setSubframeEnabled(flag); } function setPrefix(prefix) { setIdPrefix(prefix); } function loadAnimation(params) { return animationManager.loadAnimation(params); } function setQuality(value) { if (typeof value === "string") { switch (value) { case "high": setDefaultCurveSegments(200); break; default: case "medium": setDefaultCurveSegments(50); break; case "low": setDefaultCurveSegments(10); break; } } else if (!isNaN(value) && value > 1) { setDefaultCurveSegments(value); } } function inBrowser() { return typeof navigator !== "undefined"; } function installPlugin(type, plugin) { if (type === "expressions") { setExpressionsPlugin(plugin); } } function getFactory(name) { switch (name) { case "propertyFactory": return PropertyFactory; case "shapePropertyFactory": return ShapePropertyFactory; case "matrix": return Matrix; default: return null; } } lottie2.play = animationManager.play; lottie2.pause = animationManager.pause; lottie2.setLocationHref = setLocation; lottie2.togglePause = animationManager.togglePause; lottie2.setSpeed = animationManager.setSpeed; lottie2.setDirection = animationManager.setDirection; lottie2.stop = animationManager.stop; lottie2.searchAnimations = searchAnimations; lottie2.registerAnimation = animationManager.registerAnimation; lottie2.loadAnimation = loadAnimation; lottie2.setSubframeRendering = setSubframeRendering; lottie2.resize = animationManager.resize; lottie2.goToAndStop = animationManager.goToAndStop; lottie2.destroy = animationManager.destroy; lottie2.setQuality = setQuality; lottie2.inBrowser = inBrowser; lottie2.installPlugin = installPlugin; lottie2.freeze = animationManager.freeze; lottie2.unfreeze = animationManager.unfreeze; lottie2.setVolume = animationManager.setVolume; lottie2.mute = animationManager.mute; lottie2.unmute = animationManager.unmute; lottie2.getRegisteredAnimations = animationManager.getRegisteredAnimations; lottie2.useWebWorker = setWebWorker; lottie2.setIDPrefix = setPrefix; lottie2.__getFactory = getFactory; lottie2.version = "[[BM_VERSION]]"; function checkReady() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); searchAnimations(); } } function getQueryVariable(variable) { var vars = queryString.split("&"); for (var i4 = 0; i4 < vars.length; i4 += 1) { var pair = vars[i4].split("="); if (decodeURIComponent(pair[0]) == variable) { return decodeURIComponent(pair[1]); } } return null; } var queryString = ""; { var scripts = document.getElementsByTagName("script"); var index2 = scripts.length - 1; var myScript = scripts[index2] || { src: "" }; queryString = myScript.src ? myScript.src.replace(/^[^\?]+\??/, "") : ""; getQueryVariable("renderer"); } var readyStateCheckInterval = setInterval(checkReady, 100); try { if (!(typeof exports === "object" && typeof module !== "undefined") && !(typeof define === "function" && define.amd)) { window.bodymovin = lottie2; } } catch (err) { } const ShapeModifiers = (function() { var ob = {}; var modifiers = {}; ob.registerModifier = registerModifier; ob.getModifier = getModifier; function registerModifier(nm, factory) { if (!modifiers[nm]) { modifiers[nm] = factory; } } function getModifier(nm, elem, data) { return new modifiers[nm](elem, data); } return ob; })(); function ShapeModifier() { } ShapeModifier.prototype.initModifierProperties = function() { }; ShapeModifier.prototype.addShapeToModifier = function() { }; ShapeModifier.prototype.addShape = function(data) { if (!this.closed) { data.sh.container.addDynamicProperty(data.sh); var shapeData = { shape: data.sh, data, localShapeCollection: shapeCollectionPool.newShapeCollection() }; this.shapes.push(shapeData); this.addShapeToModifier(shapeData); if (this._isAnimated) { data.setAsAnimated(); } } }; ShapeModifier.prototype.init = function(elem, data) { this.shapes = []; this.elem = elem; this.initDynamicPropertyContainer(elem); this.initModifierProperties(elem, data); 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); function TrimModifier() { } extendPrototype([ShapeModifier], TrimModifier); TrimModifier.prototype.initModifierProperties = function(elem, data) { this.s = PropertyFactory.getProp(elem, data.s, 0, 0.01, this); this.e = PropertyFactory.getProp(elem, data.e, 0, 0.01, this); this.o = PropertyFactory.getProp(elem, data.o, 0, 0, this); this.sValue = 0; this.eValue = 0; this.getValue = this.processKeys; this.m = data.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(s2, e2, shapeLength, addedLength, totalModifierLength) { var segments = []; if (e2 <= 1) { segments.push({ s: s2, e: e2 }); } else if (s2 >= 1) { segments.push({ s: s2 - 1, e: e2 - 1 }); } else { segments.push({ s: s2, e: 1 }); segments.push({ s: 0, e: e2 - 1 }); } var shapeSegments = []; var i4; var len = segments.length; var segmentOb; for (i4 = 0; i4 < len; i4 += 1) { segmentOb = segments[i4]; 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 i4; var len = pathsData.length; for (i4 = 0; i4 < len; i4 += 1) { segmentsLengthPool.release(pathsData[i4]); } pathsData.length = 0; return pathsData; }; TrimModifier.prototype.processShapes = function(_isFirstFrame) { var s2; var e2; if (this._mdf || _isFirstFrame) { var o2 = this.o.v % 360 / 360; if (o2 < 0) { o2 += 1; } if (this.s.v > 1) { s2 = 1 + o2; } else if (this.s.v < 0) { s2 = 0 + o2; } else { s2 = this.s.v + o2; } if (this.e.v > 1) { e2 = 1 + o2; } else if (this.e.v < 0) { e2 = 0 + o2; } else { e2 = this.e.v + o2; } if (s2 > e2) { var _s = s2; s2 = e2; e2 = _s; } s2 = Math.round(s2 * 1e4) * 1e-4; e2 = Math.round(e2 * 1e4) * 1e-4; this.sValue = s2; this.eValue = e2; } else { s2 = this.sValue; e2 = this.eValue; } var shapePaths; var i4; var len = this.shapes.length; var j; var jLen; var pathsData; var pathData; var totalShapeLength; var totalModifierLength = 0; if (e2 === s2) { for (i4 = 0; i4 < len; i4 += 1) { this.shapes[i4].localShapeCollection.releaseShapes(); this.shapes[i4].shape._mdf = true; this.shapes[i4].shape.paths = this.shapes[i4].localShapeCollection; if (this._mdf) { this.shapes[i4].pathsData.length = 0; } } } else if (!(e2 === 1 && s2 === 0 || e2 === 0 && s2 === 1)) { var segments = []; var shapeData; var localShapeCollection; for (i4 = 0; i4 < len; i4 += 1) { shapeData = this.shapes[i4]; 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 (j = 0; j < jLen; j += 1) { pathData = bez.getSegmentsLength(shapePaths.shapes[j]); pathsData.push(pathData); totalShapeLength += pathData.totalLength; } shapeData.totalShapeLength = totalShapeLength; shapeData.pathsData = pathsData; } totalModifierLength += totalShapeLength; shapeData.shape._mdf = true; } } var shapeS = s2; var shapeE = e2; var addedLength = 0; var edges2; for (i4 = len - 1; i4 >= 0; i4 -= 1) { shapeData = this.shapes[i4]; if (shapeData.shape._mdf) { localShapeCollection = shapeData.localShapeCollection; localShapeCollection.releaseShapes(); if (this.m === 2 && len > 1) { edges2 = this.calculateShapeEdges(s2, e2, shapeData.totalShapeLength, addedLength, totalModifierLength); addedLength += shapeData.totalShapeLength; } else { edges2 = [[shapeS, shapeE]]; } jLen = edges2.length; for (j = 0; j < jLen; j += 1) { shapeS = edges2[j][0]; shapeE = edges2[j][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 (i4 = 0; i4 < len; i4 += 1) { this.shapes[i4].pathsData.length = 0; this.shapes[i4].shape._mdf = true; } } }; TrimModifier.prototype.addPaths = function(newPaths, localShapeCollection) { var i4; var len = newPaths.length; for (i4 = 0; i4 < len; i4 += 1) { localShapeCollection.addShape(newPaths[i4]); } }; 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 i4; var len = shapeData.shape.paths._length; var j; var jLen; var addedLength = 0; var currentLengthData; var segmentCount; var lengths; 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 (i4 = 0; i4 < len; i4 += 1) { lengths = pathsData[i4].lengths; shapePath.c = shapePaths[i4].c; jLen = shapePaths[i4].c ? lengths.length : lengths.length + 1; for (j = 1; j < jLen; j += 1) { currentLengthData = lengths[j - 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[i4].v[j - 1], shapePaths[i4].o[j - 1], shapePaths[i4].i[j], shapePaths[i4].v[j], shapePath, segmentCount, newShape ); newShape = false; } else { segment = bez.getNewSegment( shapePaths[i4].v[j - 1], shapePaths[i4].v[j], shapePaths[i4].o[j - 1], shapePaths[i4].i[j], (shapeSegment.s - addedLength) / currentLengthData.addedLength, (shapeSegment.e - addedLength) / currentLengthData.addedLength, lengths[j - 1] ); this.addSegmentFromArray(segment, shapePath, segmentCount, newShape); newShape = false; shapePath.c = false; } addedLength += currentLengthData.addedLength; segmentCount += 1; } } if (shapePaths[i4].c && lengths.length) { currentLengthData = lengths[j - 1]; if (addedLength <= shapeSegment.e) { var segmentLength = lengths[j - 1].addedLength; if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + segmentLength) { this.addSegment( shapePaths[i4].v[j - 1], shapePaths[i4].o[j - 1], shapePaths[i4].i[0], shapePaths[i4].v[0], shapePath, segmentCount, newShape ); newShape = false; } else { segment = bez.getNewSegment( shapePaths[i4].v[j - 1], shapePaths[i4].v[0], shapePaths[i4].o[j - 1], shapePaths[i4].i[0], (shapeSegment.s - addedLength) / segmentLength, (shapeSegment.e - addedLength) / segmentLength, lengths[j - 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 (i4 < len - 1) { shapePath = shapePool.newElement(); newShape = true; shapes.push(shapePath); segmentCount = 0; } } return shapes; }; function PuckerAndBloatModifier() { } extendPrototype([ShapeModifier], PuckerAndBloatModifier); PuckerAndBloatModifier.prototype.initModifierProperties = function(elem, data) { this.getValue = this.processKeys; this.amount = PropertyFactory.getProp(elem, data.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 i4 = 0; for (i4 = 0; i4 < pathLength; i4 += 1) { centerPoint[0] += path.v[i4][0]; centerPoint[1] += path.v[i4][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 (i4 = 0; i4 < pathLength; i4 += 1) { vX = path.v[i4][0] + (centerPoint[0] - path.v[i4][0]) * percent; vY = path.v[i4][1] + (centerPoint[1] - path.v[i4][1]) * percent; oX = path.o[i4][0] + (centerPoint[0] - path.o[i4][0]) * -percent; oY = path.o[i4][1] + (centerPoint[1] - path.o[i4][1]) * -percent; iX = path.i[i4][0] + (centerPoint[0] - path.i[i4][0]) * -percent; iY = path.i[i4][1] + (centerPoint[1] - path.i[i4][1]) * -percent; clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, i4); } return clonedPath; }; PuckerAndBloatModifier.prototype.processShapes = function(_isFirstFrame) { var shapePaths; var i4; var len = this.shapes.length; var j; var jLen; var amount = this.amount.v; if (amount !== 0) { var shapeData; var localShapeCollection; for (i4 = 0; i4 < len; i4 += 1) { shapeData = this.shapes[i4]; 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 (j = 0; j < jLen; j += 1) { localShapeCollection.addShape(this.processPath(shapePaths[j], amount)); } } shapeData.shape.paths = shapeData.localShapeCollection; } } if (!this.dynamicProperties.length) { this._mdf = false; } }; const TransformPropertyFactory = (function() { var defaultVector = [0, 0]; function applyToMatrix(mat2) { var _mdf = this._mdf; this.iterateDynamicProperties(); this._mdf = this._mdf || _mdf; if (this.a) { mat2.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); } if (this.s) { mat2.scale(this.s.v[0], this.s.v[1], this.s.v[2]); } if (this.sk) { mat2.skewFromAxis(-this.sk.v, this.sa.v); } if (this.r) { mat2.rotate(-this.r.v); } else { mat2.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) { mat2.translate(this.px.v, this.py.v, -this.pz.v); } else { mat2.translate(this.px.v, this.py.v, 0); } } else { mat2.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 frameRate; 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 v13; var v22; frameRate = 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) { v13 = this.p.getValueAtTime((this.p.keyframes[0].t + 0.01) / frameRate, 0); v22 = this.p.getValueAtTime(this.p.keyframes[0].t / frameRate, 0); } else if (this.p._caching.lastFrame + this.p.offsetTime >= this.p.keyframes[this.p.keyframes.length - 1].t) { v13 = this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length - 1].t / frameRate, 0); v22 = this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length - 1].t - 0.05) / frameRate, 0); } else { v13 = this.p.pv; v22 = this.p.getValueAtTime( (this.p._caching.lastFrame + this.p.offsetTime - 0.01) / frameRate, this.p.offsetTime ); } } else if (this.px && this.px.keyframes && this.py.keyframes && this.px.getValueAtTime && this.py.getValueAtTime) { v13 = []; v22 = []; var px = this.px; var py = this.py; if (px._caching.lastFrame + px.offsetTime <= px.keyframes[0].t) { v13[0] = px.getValueAtTime((px.keyframes[0].t + 0.01) / frameRate, 0); v13[1] = py.getValueAtTime((py.keyframes[0].t + 0.01) / frameRate, 0); v22[0] = px.getValueAtTime(px.keyframes[0].t / frameRate, 0); v22[1] = py.getValueAtTime(py.keyframes[0].t / frameRate, 0); } else if (px._caching.lastFrame + px.offsetTime >= px.keyframes[px.keyframes.length - 1].t) { v13[0] = px.getValueAtTime(px.keyframes[px.keyframes.length - 1].t / frameRate, 0); v13[1] = py.getValueAtTime(py.keyframes[py.keyframes.length - 1].t / frameRate, 0); v22[0] = px.getValueAtTime((px.keyframes[px.keyframes.length - 1].t - 0.01) / frameRate, 0); v22[1] = py.getValueAtTime((py.keyframes[py.keyframes.length - 1].t - 0.01) / frameRate, 0); } else { v13 = [px.pv, py.pv]; v22[0] = px.getValueAtTime((px._caching.lastFrame + px.offsetTime - 0.01) / frameRate, px.offsetTime); v22[1] = py.getValueAtTime((py._caching.lastFrame + py.offsetTime - 0.01) / frameRate, py.offsetTime); } } else { v22 = defaultVector; v13 = v22; } this.v.rotate(-Math.atan2(v13[1] - v22[1], v13[0] - v22[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(elem, data, container) { this.elem = elem; this.frameId = -1; this.propType = "transform"; this.data = data; this.v = new Matrix(); this.pre = new Matrix(); this.appliedTransformations = 0; this.initDynamicPropertyContainer(container || elem); if (data.p && data.p.s) { this.px = PropertyFactory.getProp(elem, data.p.x, 0, 0, this); this.py = PropertyFactory.getProp(elem, data.p.y, 0, 0, this); if (data.p.z) { this.pz = PropertyFactory.getProp(elem, data.p.z, 0, 0, this); } } else { this.p = PropertyFactory.getProp(elem, data.p || { k: [0, 0, 0] }, 1, 0, this); } if (data.rx) { this.rx = PropertyFactory.getProp(elem, data.rx, 0, degToRads, this); this.ry = PropertyFactory.getProp(elem, data.ry, 0, degToRads, this); this.rz = PropertyFactory.getProp(elem, data.rz, 0, degToRads, this); if (data.or.k[0].ti) { var i4; var len = data.or.k.length; for (i4 = 0; i4 < len; i4 += 1) { data.or.k[i4].to = null; data.or.k[i4].ti = null; } } this.or = PropertyFactory.getProp(elem, data.or, 1, degToRads, this); this.or.sh = true; } else { this.r = PropertyFactory.getProp(elem, data.r || { k: 0 }, 0, degToRads, this); } if (data.sk) { this.sk = PropertyFactory.getProp(elem, data.sk, 0, degToRads, this); this.sa = PropertyFactory.getProp(elem, data.sa, 0, degToRads, this); } this.a = PropertyFactory.getProp(elem, data.a || { k: [0, 0, 0] }, 1, 0, this); this.s = PropertyFactory.getProp(elem, data.s || { k: [100, 100, 100] }, 1, 0.01, this); if (data.o) { this.o = PropertyFactory.getProp(elem, data.o, 0, 0.01, elem); } 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(elem, data, container) { return new TransformProperty(elem, data, container); } return { getTransformProperty }; })(); function RepeaterModifier() { } extendPrototype([ShapeModifier], RepeaterModifier); RepeaterModifier.prototype.initModifierProperties = function(elem, data) { this.getValue = this.processKeys; this.c = PropertyFactory.getProp(elem, data.c, 0, null, this); this.o = PropertyFactory.getProp(elem, data.o, 0, null, this); this.tr = TransformPropertyFactory.getTransformProperty(elem, data.tr, this); this.so = PropertyFactory.getProp(elem, data.tr.so, 0, 0.01, this); this.eo = PropertyFactory.getProp(elem, data.tr.eo, 0, 0.01, this); this.data = data; 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, transform, perc, inv) { var dir = inv ? -1 : 1; var scaleX = transform.s.v[0] + (1 - transform.s.v[0]) * (1 - perc); var scaleY = transform.s.v[1] + (1 - transform.s.v[1]) * (1 - perc); pMatrix.translate(transform.p.v[0] * dir * perc, transform.p.v[1] * dir * perc, transform.p.v[2]); rMatrix.translate(-transform.a.v[0], -transform.a.v[1], transform.a.v[2]); rMatrix.rotate(-transform.r.v * dir * perc); rMatrix.translate(transform.a.v[0], transform.a.v[1], transform.a.v[2]); sMatrix.translate(-transform.a.v[0], -transform.a.v[1], transform.a.v[2]); sMatrix.scale(inv ? 1 / scaleX : scaleX, inv ? 1 / scaleY : scaleY); sMatrix.translate(transform.a.v[0], transform.a.v[1], transform.a.v[2]); }; RepeaterModifier.prototype.init = function(elem, arr, pos, elemsData) { this.elem = elem; this.arr = arr; this.pos = pos; this.elemsData = elemsData; this._currentCopies = 0; this._elements = []; this._groups = []; this.frameId = -1; this.initDynamicPropertyContainer(elem); this.initModifierProperties(elem, 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 i4; var len = elements.length; for (i4 = 0; i4 < len; i4 += 1) { elements[i4]._processed = false; if (elements[i4].ty === "gr") { this.resetElements(elements[i4].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 i4; var len = elements.length; for (i4 = 0; i4 < len; i4 += 1) { elements[i4]._render = renderFlag; if (elements[i4].ty === "gr") { this.changeGroupRender(elements[i4].it, renderFlag); } } }; RepeaterModifier.prototype.processShapes = function(_isFirstFrame) { var items; var itemsTransform; var i4; 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 (i4 = 0; i4 <= this._groups.length - 1; i4 += 1) { renderFlag = cont < copies; this._groups[i4]._render = renderFlag; this.changeGroupRender(this._groups[i4].it, renderFlag); if (!renderFlag) { var elems = this.elemsData[i4].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; } } i4 = this.data.m === 1 ? 0 : this._currentCopies - 1; dir = this.data.m === 1 ? 1 : -1; cont = this._currentCopies; var j; var jLen; while (cont) { items = this.elemsData[i4].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) * (i4 / (this._currentCopies - 1)); if (iteration !== 0) { if (i4 !== 0 && dir === 1 || i4 !== 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 (j = 0; j < jLen; j += 1) { itemsTransform[j] = this.matrix.props[j]; } this.matrix.reset(); } else { this.matrix.reset(); for (j = 0; j < jLen; j += 1) { itemsTransform[j] = this.matrix.props[j]; } } iteration += 1; cont -= 1; i4 += dir; } } else { cont = this._currentCopies; i4 = 0; dir = 1; while (cont) { items = this.elemsData[i4].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; i4 += dir; } } return hasReloaded; }; RepeaterModifier.prototype.addShape = function() { }; function RoundCornersModifier() { } extendPrototype([ShapeModifier], RoundCornersModifier); RoundCornersModifier.prototype.initModifierProperties = function(elem, data) { this.getValue = this.processKeys; this.rd = PropertyFactory.getProp(elem, data.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 i4; var len = path._length; var currentV; var currentI; var currentO; var closerV; var distance3; var newPosPerc; var index22 = 0; var vX; var vY; var oX; var oY; var iX; var iY; for (i4 = 0; i4 < len; i4 += 1) { currentV = path.v[i4]; currentO = path.o[i4]; currentI = path.i[i4]; if (currentV[0] === currentO[0] && currentV[1] === currentO[1] && currentV[0] === currentI[0] && currentV[1] === currentI[1]) { if ((i4 === 0 || i4 === len - 1) && !path.c) { clonedPath.setTripleAt(currentV[0], currentV[1], currentO[0], currentO[1], currentI[0], currentI[1], index22); index22 += 1; } else { if (i4 === 0) { closerV = path.v[len - 1]; } else { closerV = path.v[i4 - 1]; } distance3 = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); newPosPerc = distance3 ? Math.min(distance3 / 2, round) / distance3 : 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, index22); index22 += 1; if (i4 === len - 1) { closerV = path.v[0]; } else { closerV = path.v[i4 + 1]; } distance3 = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); newPosPerc = distance3 ? Math.min(distance3 / 2, round) / distance3 : 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, index22); index22 += 1; } } else { clonedPath.setTripleAt( path.v[i4][0], path.v[i4][1], path.o[i4][0], path.o[i4][1], path.i[i4][0], path.i[i4][1], index22 ); index22 += 1; } } return clonedPath; }; RoundCornersModifier.prototype.processShapes = function(_isFirstFrame) { var shapePaths; var i4; var len = this.shapes.length; var j; var jLen; var rd = this.rd.v; if (rd !== 0) { var shapeData; var localShapeCollection; for (i4 = 0; i4 < len; i4 += 1) { shapeData = this.shapes[i4]; 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 (j = 0; j < jLen; j += 1) { localShapeCollection.addShape(this.processPath(shapePaths[j], rd)); } } shapeData.shape.paths = shapeData.localShapeCollection; } } if (!this.dynamicProperties.length) { this._mdf = false; } }; function getFontProperties(fontData) { var styles2 = fontData.fStyle ? fontData.fStyle.split(" ") : []; var fWeight = "normal"; var fStyle = "normal"; var len = styles2.length; var styleName; for (var i4 = 0; i4 < len; i4 += 1) { styleName = styles2[i4].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; } } return { style: fStyle, weight: fontData.fWeight || fWeight }; } 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 i4; var len = familyArray.length; var enabledFamilies = []; for (i4 = 0; i4 < len; i4 += 1) { if (familyArray[i4] !== "sans-serif" && familyArray[i4] !== "monospace") { enabledFamilies.push(familyArray[i4]); } } 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 width = node.offsetWidth; node.style.fontFamily = trimFontOptions(font) + ", " + family; return { node, w: width, parent: parentNode }; } function checkLoadedFonts() { var i4; var len = this.fonts.length; var node; var w; var loadedCount = len; for (i4 = 0; i4 < len; i4 += 1) { if (this.fonts[i4].loaded) { loadedCount -= 1; } else if (this.fonts[i4].fOrigin === "n" || this.fonts[i4].origin === 0) { this.fonts[i4].loaded = true; } else { node = this.fonts[i4].monoCase.node; w = this.fonts[i4].monoCase.w; if (node.offsetWidth !== w) { loadedCount -= 1; this.fonts[i4].loaded = true; } else { node = this.fonts[i4].sansCase.node; w = this.fonts[i4].sansCase.w; if (node.offsetWidth !== w) { loadedCount -= 1; this.fonts[i4].loaded = true; } } if (this.fonts[i4].loaded) { this.fonts[i4].sansCase.parent.parentNode.removeChild(this.fonts[i4].sansCase.parent); this.fonts[i4].monoCase.parent.parentNode.removeChild(this.fonts[i4].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(text) { if (engine === "svg") { helper.textContent = text; return helper.getComputedTextLength(); } return helper.measureText(text).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((data) => { data.helper = createHelper(data); data.cache = {}; }); this.fonts = fontData.list; return; } var fontArr = fontData.list; var i4; var len = fontArr.length; var _pendingFonts = len; for (i4 = 0; i4 < len; i4 += 1) { var shouldLoadFont = true; var loadedSelector; var j; fontArr[i4].loaded = false; fontArr[i4].monoCase = setUpNode(fontArr[i4].fFamily, "monospace"); fontArr[i4].sansCase = setUpNode(fontArr[i4].fFamily, "sans-serif"); if (!fontArr[i4].fPath) { fontArr[i4].loaded = true; _pendingFonts -= 1; } else if (fontArr[i4].fOrigin === "p" || fontArr[i4].origin === 3) { loadedSelector = document.querySelectorAll( 'style[f-forigin="p"][f-family="' + fontArr[i4].fFamily + '"], style[f-origin="3"][f-family="' + fontArr[i4].fFamily + '"]' ); if (loadedSelector.length > 0) { shouldLoadFont = false; } if (shouldLoadFont) { var s2 = createTag("style"); s2.setAttribute("f-forigin", fontArr[i4].fOrigin); s2.setAttribute("f-origin", fontArr[i4].origin); s2.setAttribute("f-family", fontArr[i4].fFamily); s2.type = "text/css"; s2.innerText = "@font-face {font-family: " + fontArr[i4].fFamily + "; font-style: normal; src: url('" + fontArr[i4].fPath + "');}"; defs.appendChild(s2); } } else if (fontArr[i4].fOrigin === "g" || fontArr[i4].origin === 1) { loadedSelector = document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]'); for (j = 0; j < loadedSelector.length; j += 1) { if (loadedSelector[j].href.indexOf(fontArr[i4].fPath) !== -1) { shouldLoadFont = false; } } if (shouldLoadFont) { var l2 = createTag("link"); l2.setAttribute("f-forigin", fontArr[i4].fOrigin); l2.setAttribute("f-origin", fontArr[i4].origin); l2.type = "text/css"; l2.rel = "stylesheet"; l2.href = fontArr[i4].fPath; document.body.appendChild(l2); } } else if (fontArr[i4].fOrigin === "t" || fontArr[i4].origin === 2) { loadedSelector = document.querySelectorAll('script[f-forigin="t"], script[f-origin="2"]'); for (j = 0; j < loadedSelector.length; j += 1) { if (fontArr[i4].fPath === loadedSelector[j].src) { shouldLoadFont = false; } } if (shouldLoadFont) { var sc = createTag("link"); sc.setAttribute("f-forigin", fontArr[i4].fOrigin); sc.setAttribute("f-origin", fontArr[i4].origin); sc.setAttribute("rel", "stylesheet"); sc.setAttribute("href", fontArr[i4].fPath); defs.appendChild(sc); } } fontArr[i4].helper = createHelper(fontArr[i4], defs); fontArr[i4].cache = {}; this.fonts.push(fontArr[i4]); } 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 i4; var len = chars.length; var j; var jLen = this.chars.length; var found; for (i4 = 0; i4 < len; i4 += 1) { j = 0; found = false; while (j < jLen) { if (this.chars[j].style === chars[i4].style && this.chars[j].fFamily === chars[i4].fFamily && this.chars[j].ch === chars[i4].ch) { found = true; } j += 1; } if (!found) { this.chars.push(chars[i4]); jLen += 1; } } } function getCharData(char, style, font) { var i4 = 0; var len = this.chars.length; while (i4 < len) { if (this.chars[i4].ch === char && this.chars[i4].style === style && this.chars[i4].fFamily === font) { return this.chars[i4]; } i4 += 1; } if ((typeof char === "string" && char.charCodeAt(0) !== 13 || !char) && console && console.warn && // eslint-disable-line no-console !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 index22 = char.charCodeAt(0); if (!fontData.cache[index22 + 1]) { var tHelper = fontData.helper; if (char === " ") { var doubleSize = tHelper.measureText("|" + char + "|"); var singleSize = tHelper.measureText("||"); fontData.cache[index22 + 1] = (doubleSize - singleSize) / 100; } else { fontData.cache[index22 + 1] = tHelper.measureText(char) / 100; } } return fontData.cache[index22 + 1] * size2; } function getFontByName(name) { var i4 = 0; var len = this.fonts.length; while (i4 < len) { if (this.fonts[i4].fName === name) { return this.fonts[i4]; } i4 += 1; } return this.fonts[0]; } function isModifier(firstCharCode, secondCharCode) { var sum = firstCharCode.toString(16) + secondCharCode.toString(16); return surrogateModifiers.indexOf(sum) !== -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 Font2 = 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); }; Font2.isModifier = isModifier; Font2.isZeroWidthJoiner = isZeroWidthJoiner; Font2.isCombinedCharacter = isCombinedCharacter; var fontPrototype = { addChars, addFonts, getCharData, getFontByName, measureText, checkLoadedFonts, setIsLoaded }; Font2.prototype = fontPrototype; return Font2; })(); function RenderableElement() { } 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 i4; var len = this.renderableComponents.length; for (i4 = 0; i4 < len; i4 += 1) { this.renderableComponents[i4].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(mask, data) { this._mask = mask; this._data = data; } 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 i4; var len = maskManager.viewData.length; for (i4 = 0; i4 < len; i4 += 1) { _masksInterfaces[i4] = new MaskInterface(maskManager.viewData[i4], maskManager.masksProperties[i4]); } var maskFunction = function(name) { i4 = 0; while (i4 < len) { if (maskManager.masksProperties[i4].nm === name) { return _masksInterfaces[i4]; } i4 += 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, property, type) { Object.defineProperty(expressionValue, "velocity", { get: function() { return property.getVelocityAtTime(property.comp.currentFrame); } }); expressionValue.numKeys = property.keyframes ? property.keyframes.length : 0; expressionValue.key = function(pos) { if (!expressionValue.numKeys) { return 0; } var value = ""; if ("s" in property.keyframes[pos - 1]) { value = property.keyframes[pos - 1].s; } else if ("e" in property.keyframes[pos - 2]) { value = property.keyframes[pos - 2].e; } else { value = property.keyframes[pos - 2].s; } var valueProp = type === "unidimensional" ? new Number(value) : Object.assign({}, value); valueProp.time = property.keyframes[pos - 1].t / property.elem.comp.globalData.frameRate; valueProp.value = type === "unidimensional" ? value[0] : value; return valueProp; }; expressionValue.valueAtTime = property.getValueAtTime; expressionValue.speedAtTime = property.getSpeedAtTime; expressionValue.velocityAtTime = property.getVelocityAtTime; expressionValue.propertyGroup = property.propertyGroup; } function UnidimensionalPropertyInterface(property) { if (!property || !("pv" in property)) { property = defaultUnidimensionalValue; } var mult = 1 / property.mult; var val = property.pv * mult; var expressionValue = new Number(val); expressionValue.value = val; completeProperty(expressionValue, property, "unidimensional"); return function() { if (property.k) { property.getValue(); } val = property.v * mult; if (expressionValue.value !== val) { expressionValue = new Number(val); expressionValue.value = val; completeProperty(expressionValue, property, "unidimensional"); } return expressionValue; }; } function MultidimensionalPropertyInterface(property) { if (!property || !("pv" in property)) { property = defaultMultidimensionalValue; } var mult = 1 / property.mult; var len = property.data && property.data.l || property.pv.length; var expressionValue = createTypedArray("float32", len); var arrValue = createTypedArray("float32", len); expressionValue.value = arrValue; completeProperty(expressionValue, property, "multidimensional"); return function() { if (property.k) { property.getValue(); } for (var i4 = 0; i4 < len; i4 += 1) { arrValue[i4] = property.v[i4] * mult; expressionValue[i4] = arrValue[i4]; } return expressionValue; }; } function defaultGetter() { return defaultUnidimensionalValue; } return function(property) { if (!property) { return defaultGetter; } if (property.propType === "unidimensional") { return UnidimensionalPropertyInterface(property); } return MultidimensionalPropertyInterface(property); }; })(); const TransformExpressionInterface = /* @__PURE__ */ (function() { return function(transform) { function _thisFunction(name) { switch (name) { 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(transform.r || transform.rz) }); Object.defineProperty(_thisFunction, "zRotation", { get: ExpressionPropertyInterface(transform.rz || transform.r) }); Object.defineProperty(_thisFunction, "xRotation", { get: ExpressionPropertyInterface(transform.rx) }); Object.defineProperty(_thisFunction, "yRotation", { get: ExpressionPropertyInterface(transform.ry) }); Object.defineProperty(_thisFunction, "scale", { get: ExpressionPropertyInterface(transform.s) }); var _px; var _py; var _pz; var _transformFactory; if (transform.p) { _transformFactory = ExpressionPropertyInterface(transform.p); } else { _px = ExpressionPropertyInterface(transform.px); _py = ExpressionPropertyInterface(transform.py); if (transform.pz) { _pz = ExpressionPropertyInterface(transform.pz); } } Object.defineProperty(_thisFunction, "position", { get: function() { if (transform.p) { return _transformFactory(); } return [_px(), _py(), _pz ? _pz() : 0]; } }); Object.defineProperty(_thisFunction, "xPosition", { get: ExpressionPropertyInterface(transform.px) }); Object.defineProperty(_thisFunction, "yPosition", { get: ExpressionPropertyInterface(transform.py) }); Object.defineProperty(_thisFunction, "zPosition", { get: ExpressionPropertyInterface(transform.pz) }); Object.defineProperty(_thisFunction, "anchorPoint", { get: ExpressionPropertyInterface(transform.a) }); Object.defineProperty(_thisFunction, "opacity", { get: ExpressionPropertyInterface(transform.o) }); Object.defineProperty(_thisFunction, "skew", { get: ExpressionPropertyInterface(transform.sk) }); Object.defineProperty(_thisFunction, "skewAxis", { get: ExpressionPropertyInterface(transform.sa) }); Object.defineProperty(_thisFunction, "orientation", { get: ExpressionPropertyInterface(transform.or) }); return _thisFunction; }; })(); const LayerExpressionInterface = /* @__PURE__ */ (function() { function getMatrix(time) { var toWorldMat = new Matrix(); if (time !== void 0) { var propMatrix = this._elem.finalTransform.mProp.getValueAtTime(time); propMatrix.clone(toWorldMat); } else { var transformMat = this._elem.finalTransform.mProp; transformMat.applyToMatrix(toWorldMat); } return toWorldMat; } function toWorldVec(arr, time) { var toWorldMat = this.getMatrix(time); toWorldMat.props[12] = 0; toWorldMat.props[13] = 0; toWorldMat.props[14] = 0; return this.applyPoint(toWorldMat, arr); } function toWorld(arr, time) { var toWorldMat = this.getMatrix(time); return this.applyPoint(toWorldMat, arr); } function fromWorldVec(arr, time) { var toWorldMat = this.getMatrix(time); toWorldMat.props[12] = 0; toWorldMat.props[13] = 0; toWorldMat.props[14] = 0; return this.invertPoint(toWorldMat, arr); } function fromWorld(arr, time) { var toWorldMat = this.getMatrix(time); return this.invertPoint(toWorldMat, arr); } function applyPoint(matrix6, arr) { if (this._elem.hierarchy && this._elem.hierarchy.length) { var i4; var len = this._elem.hierarchy.length; for (i4 = 0; i4 < len; i4 += 1) { this._elem.hierarchy[i4].finalTransform.mProp.applyToMatrix(matrix6); } } return matrix6.applyToPointArray(arr[0], arr[1], arr[2] || 0); } function invertPoint(matrix6, arr) { if (this._elem.hierarchy && this._elem.hierarchy.length) { var i4; var len = this._elem.hierarchy.length; for (i4 = 0; i4 < len; i4 += 1) { this._elem.hierarchy[i4].finalTransform.mProp.applyToMatrix(matrix6); } } return matrix6.inversePoint(arr); } function fromComp(arr) { var toWorldMat = new Matrix(); toWorldMat.reset(); this._elem.finalTransform.mProp.applyToMatrix(toWorldMat); if (this._elem.hierarchy && this._elem.hierarchy.length) { var i4; var len = this._elem.hierarchy.length; for (i4 = 0; i4 < len; i4 += 1) { this._elem.hierarchy[i4].finalTransform.mProp.applyToMatrix(toWorldMat); } return toWorldMat.inversePoint(arr); } return toWorldMat.inversePoint(arr); } function sampleImage() { return [1, 1, 1, 1]; } return function(elem) { var transformInterface; function _registerMaskInterface(maskManager) { _thisLayerFunction.mask = new MaskManagerInterface(maskManager, elem); } function _registerEffectsInterface(effects) { _thisLayerFunction.effect = effects; } function _thisLayerFunction(name) { switch (name) { 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 = toWorld; _thisLayerFunction.toWorldVec = toWorldVec; _thisLayerFunction.fromWorld = fromWorld; _thisLayerFunction.fromWorldVec = fromWorldVec; _thisLayerFunction.toComp = toWorld; _thisLayerFunction.fromComp = fromComp; _thisLayerFunction.sampleImage = sampleImage; _thisLayerFunction.sourceRectAtTime = elem.sourceRectAtTime.bind(elem); _thisLayerFunction._elem = elem; transformInterface = TransformExpressionInterface(elem.finalTransform.mProp); var anchorPointDescriptor = getDescriptor(transformInterface, "anchorPoint"); Object.defineProperties(_thisLayerFunction, { hasParent: { get: function() { return elem.hierarchy.length; } }, parent: { get: function() { return elem.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 elem.isInRange; } } }); _thisLayerFunction.startTime = elem.data.st; _thisLayerFunction.index = elem.data.ind; _thisLayerFunction.source = elem.data.refId; _thisLayerFunction.height = elem.data.ty === 0 ? elem.data.h : 100; _thisLayerFunction.width = elem.data.ty === 0 ? elem.data.w : 100; _thisLayerFunction.inPoint = elem.data.ip / elem.comp.globalData.frameRate; _thisLayerFunction.outPoint = elem.data.op / elem.comp.globalData.frameRate; _thisLayerFunction._name = elem.data.nm; _thisLayerFunction.registerMaskInterface = _registerMaskInterface; _thisLayerFunction.registerEffectsInterface = _registerEffectsInterface; return _thisLayerFunction; }; })(); const propertyGroupFactory = /* @__PURE__ */ (function() { return function(interfaceFunction, parentPropertyGroup) { return function(val) { val = val === void 0 ? 1 : val; if (val <= 0) { return interfaceFunction; } return parentPropertyGroup(val - 1); }; }; })(); const PropertyInterface = /* @__PURE__ */ (function() { return function(propertyName, propertyGroup) { var interfaceFunction = { _name: propertyName }; function _propertyGroup(val) { val = val === void 0 ? 1 : val; if (val <= 0) { return interfaceFunction; } return propertyGroup(val - 1); } return _propertyGroup; }; })(); const EffectsExpressionInterface = /* @__PURE__ */ (function() { var ob = { createEffectsInterface }; function createEffectsInterface(elem, propertyGroup) { if (elem.effectsManager) { var effectElements = []; var effectsData = elem.data.ef; var i4; var len = elem.effectsManager.effectElements.length; for (i4 = 0; i4 < len; i4 += 1) { effectElements.push( createGroupInterface(effectsData[i4], elem.effectsManager.effectElements[i4], propertyGroup, elem) ); } var effects = elem.data.ef || []; var groupInterface = function(name) { i4 = 0; len = effects.length; while (i4 < len) { if (name === effects[i4].nm || name === effects[i4].mn || name === effects[i4].ix) { return effectElements[i4]; } i4 += 1; } return null; }; Object.defineProperty(groupInterface, "numProperties", { get: function() { return effects.length; } }); return groupInterface; } return null; } function createGroupInterface(data, elements, propertyGroup, elem) { function groupInterface(name) { var effects = data.ef; var i22 = 0; var len2 = effects.length; while (i22 < len2) { if (name === effects[i22].nm || name === effects[i22].mn || name === effects[i22].ix) { if (effects[i22].ty === 5) { return effectElements[i22]; } return effectElements[i22](); } i22 += 1; } throw new Error(); } var _propertyGroup = propertyGroupFactory(groupInterface, propertyGroup); var effectElements = []; var i4; var len = data.ef.length; for (i4 = 0; i4 < len; i4 += 1) { if (data.ef[i4].ty === 5) { effectElements.push( createGroupInterface( data.ef[i4], elements.effectElements[i4], elements.effectElements[i4].propertyGroup, elem ) ); } else { effectElements.push(createValueInterface(elements.effectElements[i4], data.ef[i4].ty, elem, _propertyGroup)); } } if (data.mn === "ADBE Color Control") { Object.defineProperty(groupInterface, "color", { get: function() { return effectElements[0](); } }); } Object.defineProperties(groupInterface, { numProperties: { get: function() { return data.np; } }, _name: { value: data.nm }, propertyGroup: { value: _propertyGroup } }); groupInterface.enabled = data.en !== 0; groupInterface.active = groupInterface.enabled; return groupInterface; } function createValueInterface(element, type, elem, propertyGroup) { var expressionProperty = ExpressionPropertyInterface(element.p); function interfaceFunction() { if (type === 10) { return elem.comp.compInterface(element.p.v); } return expressionProperty(); } if (element.p.setGroupProperty) { element.p.setGroupProperty(PropertyInterface("", propertyGroup)); } return interfaceFunction; } return ob; })(); const CompExpressionInterface = /* @__PURE__ */ (function() { return function(comp) { function _thisLayerFunction(name) { var i4 = 0; var len = comp.layers.length; while (i4 < len) { if (comp.layers[i4].nm === name || comp.layers[i4].ind === name) { return comp.elements[i4].layerInterface; } i4 += 1; } return null; } Object.defineProperty(_thisLayerFunction, "_name", { value: comp.data.nm }); _thisLayerFunction.layer = _thisLayerFunction; _thisLayerFunction.pixelAspect = 1; _thisLayerFunction.height = comp.data.h || comp.globalData.compSize.h; _thisLayerFunction.width = comp.data.w || comp.globalData.compSize.w; _thisLayerFunction.pixelAspect = 1; _thisLayerFunction.frameDuration = 1 / comp.globalData.frameRate; _thisLayerFunction.displayStartTime = 0; _thisLayerFunction.numLayers = comp.layers.length; return _thisLayerFunction; }; })(); const ShapePathInterface = /* @__PURE__ */ (function() { return function pathInterfaceFactory(shape, view, propertyGroup) { var prop = view.sh; function interfaceFunction(val) { if (val === "Shape" || val === "shape" || val === "Path" || val === "path" || val === "ADBE Vector Shape" || val === 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 i4; var len = shapes ? shapes.length : 0; for (i4 = 0; i4 < len; i4 += 1) { if (shapes[i4].ty === "gr") { arr.push(groupInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "fl") { arr.push(fillInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "st") { arr.push(strokeInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "tm") { arr.push(trimInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "tr") ; else if (shapes[i4].ty === "el") { arr.push(ellipseInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "sr") { arr.push(starInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "sh") { arr.push(ShapePathInterface(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "rc") { arr.push(rectInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "rd") { arr.push(roundedInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "rp") { arr.push(repeaterInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else if (shapes[i4].ty === "gf") { arr.push(gradientFillInterfaceFactory(shapes[i4], view[i4], propertyGroup)); } else { arr.push(defaultInterfaceFactory(shapes[i4], view[i4])); } } return arr; } function contentsInterfaceFactory(shape, view, propertyGroup) { var interfaces; var interfaceFunction = function _interfaceFunction(value) { var i4 = 0; var len = interfaces.length; while (i4 < len) { if (interfaces[i4]._name === value || interfaces[i4].mn === value || interfaces[i4].propertyIndex === value || interfaces[i4].ix === value || interfaces[i4].ind === value) { return interfaces[i4]; } i4 += 1; } if (typeof value === "number") { return interfaces[value - 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(value) { switch (value) { case "ADBE Vectors Group": case "Contents": case 2: return interfaceFunction.content; default: return interfaceFunction.transform; } }; interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); var content = contentsInterfaceFactory(shape, view, interfaceFunction.propertyGroup); var transformInterface = transformInterfaceFactory( shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup ); interfaceFunction.content = content; 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(val) { if (val === "Color" || val === "color") { return interfaceFunction.color; } if (val === "Opacity" || val === "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(val) { if (val === "Start Point" || val === "start point") { return interfaceFunction.startPoint; } if (val === "End Point" || val === "end point") { return interfaceFunction.endPoint; } if (val === "Opacity" || val === "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(i22) { Object.defineProperty(dashOb, shape.d[i22].nm, { get: ExpressionPropertyInterface(view.d.dataProps[i22].p) }); } var i4; var len = shape.d ? shape.d.length : 0; var dashOb = {}; for (i4 = 0; i4 < len; i4 += 1) { addPropertyToDashOb(i4); view.d.dataProps[i4].p.setGroupProperty(_dashPropertyGroup); } function interfaceFunction(val) { if (val === "Color" || val === "color") { return interfaceFunction.color; } if (val === "Opacity" || val === "opacity") { return interfaceFunction.opacity; } if (val === "Stroke Width" || val === "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(val) { if (val === shape.e.ix || val === "End" || val === "end") { return interfaceFunction.end; } if (val === shape.s.ix) { return interfaceFunction.start; } if (val === 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(value) { if (shape.a.ix === value || value === "Anchor Point") { return interfaceFunction.anchorPoint; } if (shape.o.ix === value || value === "Opacity") { return interfaceFunction.opacity; } if (shape.p.ix === value || value === "Position") { return interfaceFunction.position; } if (shape.r.ix === value || value === "Rotation" || value === "ADBE Vector Rotation") { return interfaceFunction.rotation; } if (shape.s.ix === value || value === "Scale") { return interfaceFunction.scale; } if (shape.sk && shape.sk.ix === value || value === "Skew") { return interfaceFunction.skew; } if (shape.sa && shape.sa.ix === value || value === "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(value) { if (shape.p.ix === value) { return interfaceFunction.position; } if (shape.s.ix === value) { 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(value) { if (shape.p.ix === value) { return interfaceFunction.position; } if (shape.r.ix === value) { return interfaceFunction.rotation; } if (shape.pt.ix === value) { return interfaceFunction.points; } if (shape.or.ix === value || value === "ADBE Vector Star Outer Radius") { return interfaceFunction.outerRadius; } if (shape.os.ix === value) { return interfaceFunction.outerRoundness; } if (shape.ir && (shape.ir.ix === value || value === "ADBE Vector Star Inner Radius")) { return interfaceFunction.innerRadius; } if (shape.is && shape.is.ix === value) { 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(value) { if (shape.p.ix === value) { return interfaceFunction.position; } if (shape.r.ix === value) { return interfaceFunction.roundness; } if (shape.s.ix === value || value === "Size" || value === "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(value) { if (shape.r.ix === value || value === "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(value) { if (shape.c.ix === value || value === "Copies") { return interfaceFunction.copies; } if (shape.o.ix === value || value === "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(value) { if (typeof value === "number") { value = value === void 0 ? 1 : value; if (value === 0) { return propertyGroup; } return interfaces[value - 1]; } var i4 = 0; var len = interfaces.length; while (i4 < len) { if (interfaces[i4]._name === value) { return interfaces[i4]; } i4 += 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(elem) { var _prevValue; var _sourceText; function _thisLayerFunction(name) { switch (name) { case "ADBE Text Document": return _thisLayerFunction.sourceText; default: return null; } } Object.defineProperty(_thisLayerFunction, "sourceText", { get: function() { elem.textProperty.getValue(); var stringValue = elem.textProperty.currentData.t; if (stringValue !== _prevValue) { elem.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] || ""; }; })(); function SliderEffect(data, elem, container) { this.p = PropertyFactory.getProp(elem, data.v, 0, 0, container); } function AngleEffect(data, elem, container) { this.p = PropertyFactory.getProp(elem, data.v, 0, 0, container); } function ColorEffect(data, elem, container) { this.p = PropertyFactory.getProp(elem, data.v, 1, 0, container); } function PointEffect(data, elem, container) { this.p = PropertyFactory.getProp(elem, data.v, 1, 0, container); } function LayerIndexEffect(data, elem, container) { this.p = PropertyFactory.getProp(elem, data.v, 0, 0, container); } function MaskIndexEffect(data, elem, container) { this.p = PropertyFactory.getProp(elem, data.v, 0, 0, container); } function CheckboxEffect(data, elem, container) { this.p = PropertyFactory.getProp(elem, data.v, 0, 0, container); } function NoValueEffect() { this.p = {}; } function EffectsManager(data, element) { var effects = data.ef || []; this.effectElements = []; var i4; var len = effects.length; var effectItem; for (i4 = 0; i4 < len; i4 += 1) { effectItem = new GroupEffect(effects[i4], element); this.effectElements.push(effectItem); } } function GroupEffect(data, element) { this.init(data, element); } extendPrototype([DynamicPropertyContainer], GroupEffect); GroupEffect.prototype.getValue = GroupEffect.prototype.iterateDynamicProperties; GroupEffect.prototype.init = function(data, element) { this.data = data; this.effectElements = []; this.initDynamicPropertyContainer(element); var i4; var len = this.data.ef.length; var eff; var effects = this.data.ef; for (i4 = 0; i4 < len; i4 += 1) { eff = null; switch (effects[i4].ty) { case 0: eff = new SliderEffect(effects[i4], element, this); break; case 1: eff = new AngleEffect(effects[i4], element, this); break; case 2: eff = new ColorEffect(effects[i4], element, this); break; case 3: eff = new PointEffect(effects[i4], element, this); break; case 4: case 7: eff = new CheckboxEffect(effects[i4], element, this); break; case 10: eff = new LayerIndexEffect(effects[i4], element, this); break; case 11: eff = new MaskIndexEffect(effects[i4], element, this); break; case 5: eff = new EffectsManager(effects[i4], element); break; default: eff = new NoValueEffect(effects[i4]); break; } if (eff) { this.effectElements.push(eff); } } }; function BaseElement() { } BaseElement.prototype = { checkMasks: function() { if (!this.data.hasMask) { return false; } var i4 = 0; var len = this.data.masksProperties.length; while (i4 < len) { if (this.data.masksProperties[i4].mode !== "n" && this.data.masksProperties[i4].cl !== false) { return true; } i4 += 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 elem = this.baseElement || this.layerElement; elem.style["mix-blend-mode"] = blendModeValue; }, initBaseData: function(data, globalData, comp) { this.globalData = globalData; this.comp = comp; this.data = data; 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() { } }; function FrameElement() { } 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 i4; var len = this.dynamicProperties.length; for (i4 = 0; i4 < len; i4 += 1) { if (isVisible || this._isParent && this.dynamicProperties[i4].propType === "transform") { this.dynamicProperties[i4].getValue(); if (this.dynamicProperties[i4]._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(elem) { var currentPropertyName = ""; var currentProperty = elem.getFootageData(); function init3() { currentPropertyName = ""; currentProperty = elem.getFootageData(); return searchProperty; } function searchProperty(value) { if (currentProperty[value]) { currentPropertyName = value; currentProperty = currentProperty[value]; if (typeof currentProperty === "object") { return searchProperty; } return currentProperty; } var propertyNameIndex = value.indexOf(currentPropertyName); if (propertyNameIndex !== -1) { var index22 = parseInt(value.substr(propertyNameIndex + currentPropertyName.length), 10); currentProperty = currentProperty[index22]; if (typeof currentProperty === "object") { return searchProperty; } return currentProperty; } return ""; } return init3; }; var dataInterfaceFactory = function(elem) { function interfaceFunction(value) { if (value === "Outline") { return interfaceFunction.outlineInterface(); } return null; } interfaceFunction._name = "Outline"; interfaceFunction.outlineInterface = outlineInterfaceFactory(elem); return interfaceFunction; }; return function(elem) { function _interfaceFunction(value) { if (value === "Data") { return _interfaceFunction.dataInterface; } return null; } _interfaceFunction._name = "Data"; _interfaceFunction.dataInterface = dataInterfaceFactory(elem); return _interfaceFunction; }; })(); function FootageElement(data, globalData, comp) { this.initFrame(); this.initRenderable(); this.assetData = globalData.getAssetData(data.refId); this.footageData = globalData.imageLoader.getAsset(this.assetData); this.initBaseData(data, globalData, comp); } 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; }; function AudioElement(data, globalData, comp) { this.initFrame(); this.initRenderable(); this.assetData = globalData.getAssetData(data.refId); this.initBaseData(data, globalData, comp); 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 = data.tm ? PropertyFactory.getProp(this, data.tm, 0, globalData.frameRate, this) : { _placeholder: true }; this.lv = PropertyFactory.getProp(this, data.au && data.au.lv ? data.au.lv : { k: [100] }, 1, 0.01, this); } 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() { }; function BaseRenderer() { } BaseRenderer.prototype.checkLayers = function(num) { var i4; var len = this.layers.length; var data; this.completeLayers = true; for (i4 = len - 1; i4 >= 0; i4 -= 1) { if (!this.elements[i4]) { data = this.layers[i4]; if (data.ip - data.st <= num - this.layers[i4].st && data.op - data.st > num - this.layers[i4].st) { this.buildItem(i4); } } this.completeLayers = this.elements[i4] ? 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(data) { return new AudioElement(data, this.globalData, this); }; BaseRenderer.prototype.createFootage = function(data) { return new FootageElement(data, this.globalData, this); }; BaseRenderer.prototype.buildAllItems = function() { var i4; var len = this.layers.length; for (i4 = 0; i4 < len; i4 += 1) { this.buildItem(i4); } this.checkPendingElements(); }; BaseRenderer.prototype.includeLayers = function(newLayers) { this.completeLayers = false; var i4; var len = newLayers.length; var j; var jLen = this.layers.length; for (i4 = 0; i4 < len; i4 += 1) { j = 0; while (j < jLen) { if (this.layers[j].id === newLayers[i4].id) { this.layers[j] = newLayers[i4]; break; } j += 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 i4 = 0; var len = layers.length; while (i4 < len) { if (layers[i4].ind == parentName) { if (!elements[i4] || elements[i4] === true) { this.buildItem(i4); this.addPendingElement(element); } else { hierarchy.push(elements[i4]); elements[i4].setAsParent(); if (layers[i4].parent !== void 0) { this.buildElementParenting(element, layers[i4].parent, hierarchy); } else { element.setHierarchy(hierarchy); } } } i4 += 1; } }; BaseRenderer.prototype.addPendingElement = function(element) { this.pendingElements.push(element); }; BaseRenderer.prototype.searchExtraCompositions = function(assets) { var i4; var len = assets.length; for (i4 = 0; i4 < len; i4 += 1) { if (assets[i4].xt) { var comp = this.createComp(assets[i4]); comp.initExpressions(); this.globalData.projectInterface.registerComposition(comp); } } }; BaseRenderer.prototype.getElementByPath = function(path) { var pathValue = path.shift(); var element; if (typeof pathValue === "number") { element = this.elements[pathValue]; } else { var i4; var len = this.elements.length; for (i4 = 0; i4 < len; i4 += 1) { if (this.elements[i4].data.nm === pathValue) { element = this.elements[i4]; 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 }; }; function TransformElement() { } 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 mat2; var finalMat = this.finalTransform.mat; var i4 = 0; var len = this.hierarchy.length; if (!this.finalTransform._matMdf) { while (i4 < len) { if (this.hierarchy[i4].finalTransform.mProp._mdf) { this.finalTransform._matMdf = true; break; } i4 += 1; } } if (this.finalTransform._matMdf) { mat2 = this.finalTransform.mProp.v.props; finalMat.cloneFromProps(mat2); for (i4 = 0; i4 < len; i4 += 1) { mat2 = this.hierarchy[i4].finalTransform.mProp.v.props; finalMat.transform( mat2[0], mat2[1], mat2[2], mat2[3], mat2[4], mat2[5], mat2[6], mat2[7], mat2[8], mat2[9], mat2[10], mat2[11], mat2[12], mat2[13], mat2[14], mat2[15] ); } } } }, globalToLocal: function(pt) { var transforms = []; transforms.push(this.finalTransform); var flag = true; var comp = this.comp; while (flag) { if (comp.finalTransform) { if (comp.data.hasMask) { transforms.splice(0, 0, comp.finalTransform); } comp = comp.comp; } else { flag = false; } } var i4; var len = transforms.length; var ptNew; for (i4 = 0; i4 < len; i4 += 1) { ptNew = transforms[i4].mat.applyToPointArray(0, 0, 0); pt = [pt[0] - ptNew[0], pt[1] - ptNew[1], 0]; } return pt; }, mHelper: new Matrix() }; function MaskElement(data, element, globalData) { this.data = data; this.element = element; this.globalData = globalData; this.storedData = []; this.masksProperties = this.data.masksProperties || []; this.maskElement = null; var defs = this.globalData.defs; var i4; 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 j; var jLen; var layerId = createElementID(); var rect; var expansor; var feMorph; var x; var maskType = "clipPath"; var maskRef = "clip-path"; for (i4 = 0; i4 < len; i4 += 1) { if (properties[i4].mode !== "a" && properties[i4].mode !== "n" || properties[i4].inv || properties[i4].o.k !== 100 || properties[i4].o.x) { maskType = "mask"; maskRef = "mask"; } if ((properties[i4].mode === "s" || properties[i4].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[i4].mode === "n") { this.viewData[i4] = { op: PropertyFactory.getProp(this.element, properties[i4].o, 0, 0.01, this.element), prop: ShapePropertyFactory.getShapeProp(this.element, properties[i4], 3), elem: path, lastPath: "" }; defs.appendChild(path); } else { count += 1; path.setAttribute("fill", properties[i4].mode === "s" ? "#000000" : "#ffffff"); path.setAttribute("clip-rule", "nonzero"); var filterID; if (properties[i4].x.k !== 0) { maskType = "mask"; maskRef = "mask"; x = PropertyFactory.getProp(this.element, properties[i4].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[i4].mode === "s" ? "#000000" : "#ffffff"); } else { feMorph = null; x = null; } this.storedData[i4] = { elem: path, x, expan: feMorph, lastPath: "", lastOperator: "", filterId: filterID, lastRadius: 0 }; if (properties[i4].mode === "i") { jLen = currentMasks.length; var g = createNS("g"); for (j = 0; j < jLen; j += 1) { g.appendChild(currentMasks[j]); } var mask = createNS("mask"); mask.setAttribute("mask-type", "alpha"); mask.setAttribute("id", layerId + "_" + count); mask.appendChild(path); defs.appendChild(mask); g.setAttribute("mask", "url(" + getLocationHref() + "#" + layerId + "_" + count + ")"); currentMasks.length = 0; currentMasks.push(g); } else { currentMasks.push(path); } if (properties[i4].inv && !this.solidPath) { this.solidPath = this.createLayerSolidPath(); } this.viewData[i4] = { elem: path, lastPath: "", op: PropertyFactory.getProp(this.element, properties[i4].o, 0, 0.01, this.element), prop: ShapePropertyFactory.getShapeProp(this.element, properties[i4], 3), invRect: rect }; if (!this.viewData[i4].prop.k) { this.drawPath(properties[i4], this.viewData[i4].prop.v, this.viewData[i4]); } } } this.maskElement = createNS(maskType); len = currentMasks.length; for (i4 = 0; i4 < len; i4 += 1) { this.maskElement.appendChild(currentMasks[i4]); } 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); } } MaskElement.prototype.getMaskProperty = function(pos) { return this.viewData[pos].prop; }; MaskElement.prototype.renderFrame = function(isFirstFrame) { var finalMat = this.element.finalTransform.mat; var i4; var len = this.masksProperties.length; for (i4 = 0; i4 < len; i4 += 1) { if (this.viewData[i4].prop._mdf || isFirstFrame) { this.drawPath(this.masksProperties[i4], this.viewData[i4].prop.v, this.viewData[i4]); } if (this.viewData[i4].op._mdf || isFirstFrame) { this.viewData[i4].elem.setAttribute("fill-opacity", this.viewData[i4].op.v); } if (this.masksProperties[i4].mode !== "n") { if (this.viewData[i4].invRect && (this.element.finalTransform.mProp._mdf || isFirstFrame)) { this.viewData[i4].invRect.setAttribute("transform", finalMat.getInverseMatrix().to2dCSS()); } if (this.storedData[i4].x && (this.storedData[i4].x._mdf || isFirstFrame)) { var feMorph = this.storedData[i4].expan; if (this.storedData[i4].x.v < 0) { if (this.storedData[i4].lastOperator !== "erode") { this.storedData[i4].lastOperator = "erode"; this.storedData[i4].elem.setAttribute( "filter", "url(" + getLocationHref() + "#" + this.storedData[i4].filterId + ")" ); } feMorph.setAttribute("radius", -this.storedData[i4].x.v); } else { if (this.storedData[i4].lastOperator !== "dilate") { this.storedData[i4].lastOperator = "dilate"; this.storedData[i4].elem.setAttribute("filter", null); } this.storedData[i4].elem.setAttribute("stroke-width", this.storedData[i4].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 i4; var len; len = pathNodes._length; for (i4 = 1; i4 < len; i4 += 1) { pathString += " C" + pathNodes.o[i4 - 1][0] + "," + pathNodes.o[i4 - 1][1] + " " + pathNodes.i[i4][0] + "," + pathNodes.i[i4][1] + " " + pathNodes.v[i4][0] + "," + pathNodes.v[i4][1]; } if (pathNodes.c && len > 1) { pathString += " C" + pathNodes.o[i4 - 1][0] + "," + pathNodes.o[i4 - 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 ob = {}; ob.createFilter = createFilter; ob.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 ob; })(); const featureSupport = (function() { var ob = { 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)) { ob.maskType = false; } return ob; })(); var registeredEffects = {}; var idPrefix = "filter_result_"; function SVGEffects(elem) { var i4; var source = "SourceGraphic"; var len = elem.data.ef ? elem.data.ef.length : 0; var filId = createElementID(); var fil = filtersFactory.createFilter(filId, true); var count = 0; this.filters = []; var filterManager; for (i4 = 0; i4 < len; i4 += 1) { filterManager = null; var type = elem.data.ef[i4].ty; if (registeredEffects[type]) { var Effect = registeredEffects[type].effect; filterManager = new Effect(fil, elem.effectsManager.effectElements[i4], elem, idPrefix + count, source); source = idPrefix + count; if (registeredEffects[type].countsAsEffect) { count += 1; } } if (filterManager) { this.filters.push(filterManager); } } if (count) { elem.globalData.defs.appendChild(fil); elem.layerElement.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); } if (this.filters.length) { elem.addRenderableComponent(this); } } SVGEffects.prototype.renderFrame = function(_isFirstFrame) { var i4; var len = this.filters.length; for (i4 = 0; i4 < len; i4 += 1) { this.filters[i4].renderFrame(_isFirstFrame); } }; function SVGBaseElement() { } 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 + ")"); } }; function HierarchyElement() { } 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 RenderableDOMElement() { } (function() { var _prototype = { initElement: function(data, globalData, comp) { this.initFrame(); this.initBaseData(data, globalData, comp); this.initTransform(data, globalData, comp); this.initHierarchy(); this.initRenderable(); this.initRendererElement(); this.createContainerElements(); this.createRenderableComponents(); this.createContent(); this.hide(); }, hide: function() { if (!this.hidden && (!this.isInRange || this.isTransparent)) { var elem = this.baseElement || this.layerElement; elem.style.display = "none"; this.hidden = true; } }, show: function() { if (this.isInRange && !this.isTransparent) { if (!this.data.hd) { var elem = this.baseElement || this.layerElement; elem.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); })(); function IImageElement(data, globalData, comp) { this.assetData = globalData.getAssetData(data.refId); this.initElement(data, globalData, comp); this.sourceRect = { top: 0, left: 0, width: this.assetData.w, height: this.assetData.h }; } 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; }; function ProcessedElement(element, position2) { this.elem = element; this.pos = position2; } function IShapeElement() { } IShapeElement.prototype = { addShapeToModifiers: function(data) { var i4; var len = this.shapeModifiers.length; for (i4 = 0; i4 < len; i4 += 1) { this.shapeModifiers[i4].addShape(data); } }, isShapeInAnimatedModifiers: function(data) { var i4 = 0; var len = this.shapeModifiers.length; while (i4 < len) { if (this.shapeModifiers[i4].isAnimatedWithShape(data)) { return true; } } return false; }, renderModifiers: function() { if (!this.shapeModifiers.length) { return; } var i4; var len = this.shapes.length; for (i4 = 0; i4 < len; i4 += 1) { this.shapes[i4].sh.reset(); } len = this.shapeModifiers.length; var shouldBreakProcess; for (i4 = len - 1; i4 >= 0; i4 -= 1) { shouldBreakProcess = this.shapeModifiers[i4].processShapes(this._isFirstFrame); if (shouldBreakProcess) { break; } } }, searchProcessedElement: function(elem) { var elements = this.processedElements; var i4 = 0; var len = elements.length; while (i4 < len) { if (elements[i4].elem === elem) { return elements[i4].pos; } i4 += 1; } return 0; }, addProcessedElement: function(elem, pos) { var elements = this.processedElements; var i4 = elements.length; while (i4) { i4 -= 1; if (elements[i4].elem === elem) { elements[i4].pos = pos; return; } } elements.push(new ProcessedElement(elem, 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" }; 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 i4 = 0; var len = transformers.length; while (i4 < len) { if (transformers[i4].mProps.dynamicProperties.length) { this._isAnimated = true; break; } i4 += 1; } } SVGShapeData.prototype.setAsAnimated = function() { this._isAnimated = true; }; function SVGStyleData(data, level) { this.data = data; this.type = data.ty; this.d = ""; this.lvl = level; this._mdf = false; this.closed = data.hd === true; this.pElem = createNS("path"); this.msElem = null; } SVGStyleData.prototype.reset = function() { this.d = ""; this._mdf = false; }; function DashProperty(elem, data, renderer, container) { this.elem = elem; this.frameId = -1; this.dataProps = createSizedArray(data.length); this.renderer = renderer; this.k = false; this.dashStr = ""; this.dashArray = createTypedArray("float32", data.length ? data.length - 1 : 0); this.dashoffset = createTypedArray("float32", 1); this.initDynamicPropertyContainer(container); var i4; var len = data.length || 0; var prop; for (i4 = 0; i4 < len; i4 += 1) { prop = PropertyFactory.getProp(elem, data[i4].v, 0, 0, this); this.k = prop.k || this.k; this.dataProps[i4] = { n: data[i4].n, p: prop }; } if (!this.k) { this.getValue(true); } this._isAnimated = this.k; } 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 i4 = 0; var len = this.dataProps.length; if (this.renderer === "svg") { this.dashStr = ""; } for (i4 = 0; i4 < len; i4 += 1) { if (this.dataProps[i4].n !== "o") { if (this.renderer === "svg") { this.dashStr += " " + this.dataProps[i4].p.v; } else { this.dashArray[i4] = this.dataProps[i4].p.v; } } else { this.dashoffset[0] = this.dataProps[i4].p.v; } } } }; extendPrototype([DynamicPropertyContainer], DashProperty); function SVGStrokeStyleData(elem, data, styleOb) { this.initDynamicPropertyContainer(elem); this.getValue = this.iterateDynamicProperties; this.o = PropertyFactory.getProp(elem, data.o, 0, 0.01, this); this.w = PropertyFactory.getProp(elem, data.w, 0, null, this); this.d = new DashProperty(elem, data.d || {}, "svg", this); this.c = PropertyFactory.getProp(elem, data.c, 1, 255, this); this.style = styleOb; this._isAnimated = !!this._isAnimated; } extendPrototype([DynamicPropertyContainer], SVGStrokeStyleData); function SVGFillStyleData(elem, data, styleOb) { this.initDynamicPropertyContainer(elem); this.getValue = this.iterateDynamicProperties; this.o = PropertyFactory.getProp(elem, data.o, 0, 0.01, this); this.c = PropertyFactory.getProp(elem, data.c, 1, 255, this); this.style = styleOb; } extendPrototype([DynamicPropertyContainer], SVGFillStyleData); function SVGNoStyleData(elem, data, styleOb) { this.initDynamicPropertyContainer(elem); this.getValue = this.iterateDynamicProperties; this.style = styleOb; } extendPrototype([DynamicPropertyContainer], SVGNoStyleData); function GradientProperty(elem, data, container) { this.data = data; this.c = createTypedArray("uint8c", data.p * 4); var cLength = data.k.k[0].s ? data.k.k[0].s.length - data.p * 4 : data.k.k.length - data.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(elem, data.k, 1, null, this); this.k = this.prop.k; this.getValue(true); } GradientProperty.prototype.comparePoints = function(values, points) { var i4 = 0; var len = this.o.length / 2; var diff; while (i4 < len) { diff = Math.abs(values[i4 * 4] - values[points * 4 + i4 * 2]); if (diff > 0.01) { return false; } i4 += 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 i4 = 0; var len = this.data.k.k.length; while (i4 < len) { if (!this.comparePoints(this.data.k.k[i4].s, this.data.p)) { return false; } i4 += 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 i4; var len = this.data.p * 4; var mult; var val; for (i4 = 0; i4 < len; i4 += 1) { mult = i4 % 4 === 0 ? 100 : 255; val = Math.round(this.prop.v[i4] * mult); if (this.c[i4] !== val) { this.c[i4] = val; this._cmdf = !forceRender; } } if (this.o.length) { len = this.prop.v.length; for (i4 = this.data.p * 4; i4 < len; i4 += 1) { mult = i4 % 2 === 0 ? 100 : 1; val = i4 % 2 === 0 ? Math.round(this.prop.v[i4] * 100) : this.prop.v[i4]; if (this.o[i4 - this.data.p * 4] !== val) { this.o[i4 - this.data.p * 4] = val; this._omdf = !forceRender; } } } this._mdf = !forceRender; } }; extendPrototype([DynamicPropertyContainer], GradientProperty); function SVGGradientFillStyleData(elem, data, styleOb) { this.initDynamicPropertyContainer(elem); this.getValue = this.iterateDynamicProperties; this.initGradientData(elem, data, styleOb); } SVGGradientFillStyleData.prototype.initGradientData = function(elem, data, styleOb) { this.o = PropertyFactory.getProp(elem, data.o, 0, 0.01, this); this.s = PropertyFactory.getProp(elem, data.s, 1, null, this); this.e = PropertyFactory.getProp(elem, data.e, 1, null, this); this.h = PropertyFactory.getProp(elem, data.h || { k: 0 }, 0, 0.01, this); this.a = PropertyFactory.getProp(elem, data.a || { k: 0 }, 0, degToRads, this); this.g = new GradientProperty(elem, data.g, this); this.style = styleOb; this.stops = []; this.setGradientData(styleOb.pElem, data); this.setGradientOpacity(data, styleOb); this._isAnimated = !!this._isAnimated; }; SVGGradientFillStyleData.prototype.setGradientData = function(pathElement, data) { var gradientId = createElementID(); var gfill = createNS(data.t === 1 ? "linearGradient" : "radialGradient"); gfill.setAttribute("id", gradientId); gfill.setAttribute("spreadMethod", "pad"); gfill.setAttribute("gradientUnits", "userSpaceOnUse"); var stops = []; var stop; var j; var jLen; jLen = data.g.p * 4; for (j = 0; j < jLen; j += 4) { stop = createNS("stop"); gfill.appendChild(stop); stops.push(stop); } pathElement.setAttribute(data.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + gradientId + ")"); this.gf = gfill; this.cst = stops; }; SVGGradientFillStyleData.prototype.setGradientOpacity = function(data, styleOb) { if (this.g._hasOpacity && !this.g._collapsable) { var stop; var j; var jLen; var mask = createNS("mask"); var maskElement = createNS("path"); mask.appendChild(maskElement); var opacityId = createElementID(); var maskId = createElementID(); mask.setAttribute("id", maskId); var opFill = createNS(data.t === 1 ? "linearGradient" : "radialGradient"); opFill.setAttribute("id", opacityId); opFill.setAttribute("spreadMethod", "pad"); opFill.setAttribute("gradientUnits", "userSpaceOnUse"); jLen = data.g.k.k[0].s ? data.g.k.k[0].s.length : data.g.k.k.length; var stops = this.stops; for (j = data.g.p * 4; j < jLen; j += 2) { stop = createNS("stop"); stop.setAttribute("stop-color", "rgb(255,255,255)"); opFill.appendChild(stop); stops.push(stop); } maskElement.setAttribute(data.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + opacityId + ")"); if (data.ty === "gs") { maskElement.setAttribute("stroke-linecap", lineCapEnum[data.lc || 2]); maskElement.setAttribute("stroke-linejoin", lineJoinEnum[data.lj || 2]); if (data.lj === 1) { maskElement.setAttribute("stroke-miterlimit", data.ml); } } this.of = opFill; this.ms = mask; this.ost = stops; this.maskId = maskId; styleOb.msElem = maskElement; } }; extendPrototype([DynamicPropertyContainer], SVGGradientFillStyleData); function SVGGradientStrokeStyleData(elem, data, styleOb) { this.initDynamicPropertyContainer(elem); this.getValue = this.iterateDynamicProperties; this.w = PropertyFactory.getProp(elem, data.w, 0, null, this); this.d = new DashProperty(elem, data.d || {}, "svg", this); this.initGradientData(elem, data, styleOb); this._isAnimated = !!this._isAnimated; } extendPrototype([SVGGradientFillStyleData, DynamicPropertyContainer], SVGGradientStrokeStyleData); 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; } const buildShapeString = function(pathNodes, length3, closed, mat2) { if (length3 === 0) { return ""; } var _o2 = pathNodes.o; var _i = pathNodes.i; var _v4 = pathNodes.v; var i4; var shapeString = " M" + mat2.applyToPointStringified(_v4[0][0], _v4[0][1]); for (i4 = 1; i4 < length3; i4 += 1) { shapeString += " C" + mat2.applyToPointStringified(_o2[i4 - 1][0], _o2[i4 - 1][1]) + " " + mat2.applyToPointStringified(_i[i4][0], _i[i4][1]) + " " + mat2.applyToPointStringified(_v4[i4][0], _v4[i4][1]); } if (closed && length3) { shapeString += " C" + mat2.applyToPointStringified(_o2[i4 - 1][0], _o2[i4 - 1][1]) + " " + mat2.applyToPointStringified(_i[0][0], _i[0][1]) + " " + mat2.applyToPointStringified(_v4[0][0], _v4[0][1]); shapeString += "z"; } return shapeString; }; const SVGElementsRenderer = (function() { var _identityMatrix3 = new Matrix(); var _matrixHelper = new Matrix(); var ob = { createRenderFunction }; function createRenderFunction(data) { switch (data.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 j; var jLen; var pathStringTransformed; var redraw; var pathNodes; var l2; var lLen = itemData.styles.length; var lvl = itemData.lvl; var paths; var mat2; var props; var iterations; var k; for (l2 = 0; l2 < lLen; l2 += 1) { redraw = itemData.sh._mdf || isFirstFrame; if (itemData.styles[l2].lvl < lvl) { mat2 = _matrixHelper.reset(); iterations = lvl - itemData.styles[l2].lvl; k = itemData.transformers.length - 1; while (!redraw && iterations > 0) { redraw = itemData.transformers[k].mProps._mdf || redraw; iterations -= 1; k -= 1; } if (redraw) { iterations = lvl - itemData.styles[l2].lvl; k = itemData.transformers.length - 1; while (iterations > 0) { props = itemData.transformers[k].mProps.v.props; mat2.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; k -= 1; } } } else { mat2 = _identityMatrix3; } paths = itemData.sh.paths; jLen = paths._length; if (redraw) { pathStringTransformed = ""; for (j = 0; j < jLen; j += 1) { pathNodes = paths.shapes[j]; if (pathNodes && pathNodes._length) { pathStringTransformed += buildShapeString(pathNodes, pathNodes._length, pathNodes.c, mat2); } } 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 i4; var len; var stop; if (itemData.g._cmdf || isFirstFrame) { stops = itemData.cst; var cValues = itemData.g.c; len = stops.length; for (i4 = 0; i4 < len; i4 += 1) { stop = stops[i4]; stop.setAttribute("offset", cValues[i4 * 4] + "%"); stop.setAttribute( "stop-color", "rgb(" + cValues[i4 * 4 + 1] + "," + cValues[i4 * 4 + 2] + "," + cValues[i4 * 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 (i4 = 0; i4 < len; i4 += 1) { stop = stops[i4]; if (!itemData.g._collapsable) { stop.setAttribute("offset", oValues[i4 * 2] + "%"); } stop.setAttribute("stop-opacity", oValues[i4 * 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 x = Math.cos(ang + itemData.a.v) * dist + pt1[0]; var y = Math.sin(ang + itemData.a.v) * dist + pt1[1]; gfill.setAttribute("fx", x); gfill.setAttribute("fy", y); if (hasOpacity && !itemData.g._collapsable) { itemData.of.setAttribute("fx", x); itemData.of.setAttribute("fy", y); } } } } function renderStroke(styleData, itemData, isFirstFrame) { var styleElem = itemData.style; var d2 = itemData.d; if (d2 && (d2._mdf || isFirstFrame) && d2.dashStr) { styleElem.pElem.setAttribute("stroke-dasharray", d2.dashStr); styleElem.pElem.setAttribute("stroke-dashoffset", d2.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 ob; })(); function SVGShapeElement(data, globalData, comp) { this.shapes = []; this.shapesData = data.shapes; this.stylesList = []; this.shapeModifiers = []; this.itemsData = []; this.processedElements = []; this.animatedContents = []; this.initElement(data, globalData, comp); this.prevViewData = []; } 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 i4; var len = this.shapes.length; var shape; var j; var jLen = this.stylesList.length; var style; var tempShapes = []; var areAnimated = false; for (j = 0; j < jLen; j += 1) { style = this.stylesList[j]; areAnimated = false; tempShapes.length = 0; for (i4 = 0; i4 < len; i4 += 1) { shape = this.shapes[i4]; 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 i4; var len = shapes.length; for (i4 = 0; i4 < len; i4 += 1) { shapes[i4].setAsAnimated(); } }; SVGShapeElement.prototype.createStyleElement = function(data, level) { var elementData; var styleOb = new SVGStyleData(data, level); var pathElement = styleOb.pElem; if (data.ty === "st") { elementData = new SVGStrokeStyleData(this, data, styleOb); } else if (data.ty === "fl") { elementData = new SVGFillStyleData(this, data, styleOb); } else if (data.ty === "gf" || data.ty === "gs") { var GradientConstructor = data.ty === "gf" ? SVGGradientFillStyleData : SVGGradientStrokeStyleData; elementData = new GradientConstructor(this, data, 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 (data.ty === "no") { elementData = new SVGNoStyleData(this, data, styleOb); } if (data.ty === "st" || data.ty === "gs") { pathElement.setAttribute("stroke-linecap", lineCapEnum[data.lc || 2]); pathElement.setAttribute("stroke-linejoin", lineJoinEnum[data.lj || 2]); pathElement.setAttribute("fill-opacity", "0"); if (data.lj === 1) { pathElement.setAttribute("stroke-miterlimit", data.ml); } } if (data.r === 2) { pathElement.setAttribute("fill-rule", "evenodd"); } if (data.ln) { pathElement.setAttribute("id", data.ln); } if (data.cl) { pathElement.setAttribute("class", data.cl); } if (data.bm) { pathElement.style["mix-blend-mode"] = getBlendMode(data.bm); } this.stylesList.push(styleOb); this.addToAnimatedContents(data, elementData); return elementData; }; SVGShapeElement.prototype.createGroupElement = function(data) { var elementData = new ShapeGroupData(); if (data.ln) { elementData.gr.setAttribute("id", data.ln); } if (data.cl) { elementData.gr.setAttribute("class", data.cl); } if (data.bm) { elementData.gr.style["mix-blend-mode"] = getBlendMode(data.bm); } return elementData; }; SVGShapeElement.prototype.createTransformElement = function(data, container) { var transformProperty = TransformPropertyFactory.getTransformProperty(this, data, this); var elementData = new SVGTransformData(transformProperty, transformProperty.o, container); this.addToAnimatedContents(data, elementData); return elementData; }; SVGShapeElement.prototype.createShapeElement = function(data, ownTransformers, level) { var ty = 4; if (data.ty === "rc") { ty = 5; } else if (data.ty === "el") { ty = 6; } else if (data.ty === "sr") { ty = 7; } var shapeProperty = ShapePropertyFactory.getShapeProp(this, data, ty, this); var elementData = new SVGShapeData(ownTransformers, level, shapeProperty); this.shapes.push(elementData); this.addShapeToModifiers(elementData); this.addToAnimatedContents(data, elementData); return elementData; }; SVGShapeElement.prototype.addToAnimatedContents = function(data, element) { var i4 = 0; var len = this.animatedContents.length; while (i4 < len) { if (this.animatedContents[i4].element === element) { return; } i4 += 1; } this.animatedContents.push({ fn: SVGElementsRenderer.createRenderFunction(data), element, data }); }; SVGShapeElement.prototype.setElementStyles = function(elementData) { var arr = elementData.styles; var j; var jLen = this.stylesList.length; for (j = 0; j < jLen; j += 1) { if (!this.stylesList[j].closed) { arr.push(this.stylesList[j]); } } }; SVGShapeElement.prototype.reloadShapes = function() { this._isFirstFrame = true; var i4; var len = this.itemsData.length; for (i4 = 0; i4 < len; i4 += 1) { this.prevViewData[i4] = this.itemsData[i4]; } this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true); this.filterUniqueShapes(); len = this.dynamicProperties.length; for (i4 = 0; i4 < len; i4 += 1) { this.dynamicProperties[i4].getValue(); } this.renderModifiers(); }; SVGShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, container, level, transformers, render) { var ownTransformers = [].concat(transformers); var i4; var len = arr.length - 1; var j; var jLen; var ownStyles = []; var ownModifiers = []; var currentTransform; var modifier; var processedPos; for (i4 = len; i4 >= 0; i4 -= 1) { processedPos = this.searchProcessedElement(arr[i4]); if (!processedPos) { arr[i4]._render = render; } else { itemsData[i4] = prevViewData[processedPos - 1]; } if (arr[i4].ty === "fl" || arr[i4].ty === "st" || arr[i4].ty === "gf" || arr[i4].ty === "gs" || arr[i4].ty === "no") { if (!processedPos) { itemsData[i4] = this.createStyleElement(arr[i4], level); } else { itemsData[i4].style.closed = false; } if (arr[i4]._render) { if (itemsData[i4].style.pElem.parentNode !== container) { container.appendChild(itemsData[i4].style.pElem); } } ownStyles.push(itemsData[i4].style); } else if (arr[i4].ty === "gr") { if (!processedPos) { itemsData[i4] = this.createGroupElement(arr[i4]); } else { jLen = itemsData[i4].it.length; for (j = 0; j < jLen; j += 1) { itemsData[i4].prevViewData[j] = itemsData[i4].it[j]; } } this.searchShapes( arr[i4].it, itemsData[i4].it, itemsData[i4].prevViewData, itemsData[i4].gr, level + 1, ownTransformers, render ); if (arr[i4]._render) { if (itemsData[i4].gr.parentNode !== container) { container.appendChild(itemsData[i4].gr); } } } else if (arr[i4].ty === "tr") { if (!processedPos) { itemsData[i4] = this.createTransformElement(arr[i4], container); } currentTransform = itemsData[i4].transform; ownTransformers.push(currentTransform); } else if (arr[i4].ty === "sh" || arr[i4].ty === "rc" || arr[i4].ty === "el" || arr[i4].ty === "sr") { if (!processedPos) { itemsData[i4] = this.createShapeElement(arr[i4], ownTransformers, level); } this.setElementStyles(itemsData[i4]); } else if (arr[i4].ty === "tm" || arr[i4].ty === "rd" || arr[i4].ty === "ms" || arr[i4].ty === "pb") { if (!processedPos) { modifier = ShapeModifiers.getModifier(arr[i4].ty); modifier.init(this, arr[i4]); itemsData[i4] = modifier; this.shapeModifiers.push(modifier); } else { modifier = itemsData[i4]; modifier.closed = false; } ownModifiers.push(modifier); } else if (arr[i4].ty === "rp") { if (!processedPos) { modifier = ShapeModifiers.getModifier(arr[i4].ty); itemsData[i4] = modifier; modifier.init(this, arr, i4, itemsData); this.shapeModifiers.push(modifier); render = false; } else { modifier = itemsData[i4]; modifier.closed = true; } ownModifiers.push(modifier); } this.addProcessedElement(arr[i4], i4 + 1); } len = ownStyles.length; for (i4 = 0; i4 < len; i4 += 1) { ownStyles[i4].closed = true; } len = ownModifiers.length; for (i4 = 0; i4 < len; i4 += 1) { ownModifiers[i4].closed = true; } }; SVGShapeElement.prototype.renderInnerContent = function() { this.renderModifiers(); var i4; var len = this.stylesList.length; for (i4 = 0; i4 < len; i4 += 1) { this.stylesList[i4].reset(); } this.renderShape(); for (i4 = 0; i4 < len; i4 += 1) { if (this.stylesList[i4]._mdf || this._isFirstFrame) { if (this.stylesList[i4].msElem) { this.stylesList[i4].msElem.setAttribute("d", this.stylesList[i4].d); this.stylesList[i4].d = "M0 0" + this.stylesList[i4].d; } this.stylesList[i4].pElem.setAttribute("d", this.stylesList[i4].d || "M0 0"); } } }; SVGShapeElement.prototype.renderShape = function() { var i4; var len = this.animatedContents.length; var animatedContent; for (i4 = 0; i4 < len; i4 += 1) { animatedContent = this.animatedContents[i4]; 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; }; function LetterProps(o2, sw, sc, fc, m, p2) { this.o = o2; this.sw = sw; this.sc = sc; this.fc = fc; this.m = m; this.p = p2; this._mdf = { o: true, sw: !!sw, sc: !!sc, fc: !!fc, m: true, p: true }; } LetterProps.prototype.update = function(o2, sw, sc, fc, m, p2) { 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 !== o2) { this.o = o2; 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 (p2.length && (this.p[0] !== p2[0] || this.p[1] !== p2[1] || this.p[4] !== p2[4] || this.p[5] !== p2[5] || this.p[12] !== p2[12] || this.p[13] !== p2[13])) { this.p = p2; this._mdf.p = true; updated = true; } return updated; }; function TextProperty(elem, data) { this._frameId = initialDefaultFrame; this.pv = ""; this.v = ""; this.kf = false; this._isFirstFrame = true; this._mdf = false; this.data = data; this.elem = elem; 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); } } TextProperty.prototype.defaultBoxWidth = [0, 0]; TextProperty.prototype.copyData = function(obj, data) { for (var s2 in data) { if (Object.prototype.hasOwnProperty.call(data, s2)) { obj[s2] = data[s2]; } } return obj; }; TextProperty.prototype.setCurrentData = function(data) { if (!data.__complete) { this.completeTextData(data); } this.currentData = data; 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 i4; var len = this.effectsSequence.length; var finalValue = _finalValue || this.data.d.k[this.keysIndex].s; for (i4 = 0; i4 < len; i4 += 1) { if (currentIndex !== this.keysIndex) { finalValue = this.effectsSequence[i4](finalValue, finalValue.t); } else { finalValue = this.effectsSequence[i4](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 i4 = 0; var len = textKeys.length; while (i4 <= len - 1) { if (i4 === len - 1 || textKeys[i4 + 1].t > frameNum) { break; } i4 += 1; } if (this.keysIndex !== i4) { this.keysIndex = i4; } return this.data.d.k[this.keysIndex].s; }; TextProperty.prototype.buildFinalText = function(text) { var charactersArray = []; var i4 = 0; var len = text.length; var charCode; var secondCharCode; var shouldCombine = false; while (i4 < len) { charCode = text.charCodeAt(i4); if (FontManager.isCombinedCharacter(charCode)) { charactersArray[charactersArray.length - 1] += text.charAt(i4); } else if (charCode >= 55296 && charCode <= 56319) { secondCharCode = text.charCodeAt(i4 + 1); if (secondCharCode >= 56320 && secondCharCode <= 57343) { if (shouldCombine || FontManager.isModifier(charCode, secondCharCode)) { charactersArray[charactersArray.length - 1] += text.substr(i4, 2); shouldCombine = false; } else { charactersArray.push(text.substr(i4, 2)); } i4 += 1; } else { charactersArray.push(text.charAt(i4)); } } else if (charCode > 56319) { secondCharCode = text.charCodeAt(i4 + 1); if (FontManager.isZeroWidthJoiner(charCode, secondCharCode)) { shouldCombine = true; charactersArray[charactersArray.length - 1] += text.substr(i4, 2); i4 += 1; } else { charactersArray.push(text.charAt(i4)); } } else if (FontManager.isZeroWidthJoiner(charCode)) { charactersArray[charactersArray.length - 1] += text.charAt(i4); shouldCombine = true; } else { charactersArray.push(text.charAt(i4)); } i4 += 1; } return charactersArray; }; TextProperty.prototype.completeTextData = function(documentData) { documentData.__complete = true; var fontManager = this.elem.globalData.fontManager; var data = this.data; var letters = []; var i4; var len; var newLineFlag; var index22 = 0; var val; var anchorGrouping = data.m.g; var currentSize = 0; var currentPos = 0; var currentLine = 0; var lineWidths = []; var lineWidth = 0; var maxLineWidth = 0; var j; 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 (i4 = 0; i4 < len; i4 += 1) { charCode = finalText[i4].charCodeAt(0); newLineFlag = false; if (finalText[i4] === " ") { lastSpaceIndex = i4; } else if (charCode === 13 || charCode === 3) { lineWidth = 0; newLineFlag = true; currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; } if (fontManager.chars) { charData = fontManager.getCharData(finalText[i4], fontData.fStyle, fontData.fFamily); cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100; } else { cLength = fontManager.measureText(finalText[i4], documentData.f, documentData.finalSize); } if (lineWidth + cLength > boxWidth && finalText[i4] !== " ") { if (lastSpaceIndex === -1) { len += 1; } else { i4 = lastSpaceIndex; } currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; finalText.splice(i4, lastSpaceIndex === i4 ? 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 (i4 = 0; i4 < len; i4 += 1) { newLineFlag = false; currentChar = documentData.finalText[i4]; charCode = currentChar.charCodeAt(0); if (charCode === 13 || charCode === 3) { uncollapsedSpaces = 0; lineWidths.push(lineWidth); maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; lineWidth = -2 * trackingOffset; val = ""; newLineFlag = true; currentLine += 1; } else { val = 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(val, 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, line: currentLine, animatorJustifyOffset: 0 }); if (anchorGrouping == 2) { currentSize += cLength; if (val === "" || val === " " || i4 === len - 1) { if (val === "" || val === " ") { currentSize -= cLength; } while (currentPos <= i4) { letters[currentPos].an = currentSize; letters[currentPos].ind = index22; letters[currentPos].extra = cLength; currentPos += 1; } index22 += 1; currentSize = 0; } } else if (anchorGrouping == 3) { currentSize += cLength; if (val === "" || i4 === len - 1) { if (val === "") { currentSize -= cLength; } while (currentPos <= i4) { letters[currentPos].an = currentSize; letters[currentPos].ind = index22; letters[currentPos].extra = cLength; currentPos += 1; } currentSize = 0; index22 += 1; } } else { letters[index22].ind = index22; letters[index22].extra = 0; index22 += 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 = data.a; var animatorData; var letterData; jLen = animators.length; var based; var ind; var indexes = []; for (j = 0; j < jLen; j += 1) { animatorData = animators[j]; 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 (i4 = 0; i4 < len; i4 += 1) { letterData = letters[i4]; letterData.anIndexes[j] = ind; if (based == 1 && letterData.val !== "" || based == 2 && letterData.val !== "" && letterData.val !== " " || based == 3 && (letterData.n || letterData.val == " " || i4 == len - 1) || based == 4 && (letterData.n || i4 == len - 1)) { if (animatorData.s.rn === 1) { indexes.push(ind); } ind += 1; } } data.a[j].s.totalChars = ind; var currentInd = -1; var newInd; if (animatorData.s.rn === 1) { for (i4 = 0; i4 < len; i4 += 1) { letterData = letters[i4]; if (currentInd != letterData.anIndexes[j]) { currentInd = letterData.anIndexes[j]; newInd = indexes.splice(Math.floor(Math.random() * indexes.length), 1)[0]; } letterData.anIndexes[j] = 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, index22) { index22 = index22 === void 0 ? this.keysIndex : index22; var dData = this.copyData({}, this.data.d.k[index22].s); dData = this.copyData(dData, newData); this.data.d.k[index22].s = dData; this.recalculate(index22); this.elem.addDynamicProperty(this); }; TextProperty.prototype.recalculate = function(index22) { var dData = this.data.d.k[index22].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(elem, data) { this._currentTextLength = -1; this.k = false; this.data = data; this.elem = elem; this.comp = elem.comp; this.finalS = 0; this.finalE = 0; this.initDynamicPropertyContainer(elem); this.s = PropertyFactory.getProp(elem, data.s || { k: 0 }, 0, 0, this); if ("e" in data) { this.e = PropertyFactory.getProp(elem, data.e, 0, 0, this); } else { this.e = { v: 100 }; } this.o = PropertyFactory.getProp(elem, data.o || { k: 0 }, 0, 0, this); this.xe = PropertyFactory.getProp(elem, data.xe || { k: 0 }, 0, 0, this); this.ne = PropertyFactory.getProp(elem, data.ne || { k: 0 }, 0, 0, this); this.sm = PropertyFactory.getProp(elem, data.sm || { k: 100 }, 0, 0, this); this.a = PropertyFactory.getProp(elem, data.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 s2 = this.finalS; var e2 = this.finalE; var type = this.data.sh; if (type === 2) { if (e2 === s2) { mult = ind >= e2 ? 1 : 0; } else { mult = max2(0, min(0.5 / (e2 - s2) + (ind - s2) / (e2 - s2), 1)); } mult = easer(mult); } else if (type === 3) { if (e2 === s2) { mult = ind >= e2 ? 0 : 1; } else { mult = 1 - max2(0, min(0.5 / (e2 - s2) + (ind - s2) / (e2 - s2), 1)); } mult = easer(mult); } else if (type === 4) { if (e2 === s2) { mult = 0; } else { mult = max2(0, min(0.5 / (e2 - s2) + (ind - s2) / (e2 - s2), 1)); if (mult < 0.5) { mult *= 2; } else { mult = 1 - 2 * (mult - 0.5); } } mult = easer(mult); } else if (type === 5) { if (e2 === s2) { mult = 0; } else { var tot = e2 - s2; ind = min(max2(0, ind + 0.5 - s2), e2 - s2); var x = -tot / 2 + ind; var a6 = tot / 2; mult = Math.sqrt(1 - x * x / (a6 * a6)); } mult = easer(mult); } else if (type === 6) { if (e2 === s2) { mult = 0; } else { ind = min(max2(0, ind + 0.5 - s2), e2 - s2); mult = (1 + Math.cos(Math.PI + Math.PI * 2 * ind / (e2 - s2))) / 2; } mult = easer(mult); } else { if (ind >= floor(s2)) { if (ind - s2 < 0) { mult = max2(0, min(min(e2, 1) - (s2 - ind), 1)); } else { mult = max2(0, min(e2 - 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 o2 = this.o.v / divisor; var s2 = this.s.v / divisor + o2; var e2 = this.e.v / divisor + o2; if (s2 > e2) { var _s = s2; s2 = e2; e2 = _s; } this.finalS = s2; this.finalE = e2; } }; extendPrototype([DynamicPropertyContainer], TextSelectorPropFactory); function getTextSelectorProp(elem, data, arr) { return new TextSelectorPropFactory(elem, data); } return { getTextSelectorProp }; })(); function TextAnimatorDataProperty(elem, animatorProps, container) { var defaultData = { propType: false }; var getProp = PropertyFactory.getProp; var textAnimatorAnimatables = animatorProps.a; this.a = { r: textAnimatorAnimatables.r ? getProp(elem, textAnimatorAnimatables.r, 0, degToRads, container) : defaultData, rx: textAnimatorAnimatables.rx ? getProp(elem, textAnimatorAnimatables.rx, 0, degToRads, container) : defaultData, ry: textAnimatorAnimatables.ry ? getProp(elem, textAnimatorAnimatables.ry, 0, degToRads, container) : defaultData, sk: textAnimatorAnimatables.sk ? getProp(elem, textAnimatorAnimatables.sk, 0, degToRads, container) : defaultData, sa: textAnimatorAnimatables.sa ? getProp(elem, textAnimatorAnimatables.sa, 0, degToRads, container) : defaultData, s: textAnimatorAnimatables.s ? getProp(elem, textAnimatorAnimatables.s, 1, 0.01, container) : defaultData, a: textAnimatorAnimatables.a ? getProp(elem, textAnimatorAnimatables.a, 1, 0, container) : defaultData, o: textAnimatorAnimatables.o ? getProp(elem, textAnimatorAnimatables.o, 0, 0.01, container) : defaultData, p: textAnimatorAnimatables.p ? getProp(elem, textAnimatorAnimatables.p, 1, 0, container) : defaultData, sw: textAnimatorAnimatables.sw ? getProp(elem, textAnimatorAnimatables.sw, 0, 0, container) : defaultData, sc: textAnimatorAnimatables.sc ? getProp(elem, textAnimatorAnimatables.sc, 1, 0, container) : defaultData, fc: textAnimatorAnimatables.fc ? getProp(elem, textAnimatorAnimatables.fc, 1, 0, container) : defaultData, fh: textAnimatorAnimatables.fh ? getProp(elem, textAnimatorAnimatables.fh, 0, 0, container) : defaultData, fs: textAnimatorAnimatables.fs ? getProp(elem, textAnimatorAnimatables.fs, 0, 0.01, container) : defaultData, fb: textAnimatorAnimatables.fb ? getProp(elem, textAnimatorAnimatables.fb, 0, 0.01, container) : defaultData, t: textAnimatorAnimatables.t ? getProp(elem, textAnimatorAnimatables.t, 0, 0, container) : defaultData }; this.s = TextSelectorProp.getTextSelectorProp(elem, animatorProps.s, container); this.s.t = animatorProps.s.t; } function TextAnimatorProperty(textData, renderType, elem) { this._isFirstFrame = true; this._hasMaskedPath = false; this._frameId = -1; this._textData = textData; this._renderType = renderType; this._elem = elem; this._animatorsData = createSizedArray(this._textData.a.length); this._pathData = {}; this._moreOptions = { alignment: {} }; this.renderedLetters = []; this.lettersChangedFlag = false; this.initDynamicPropertyContainer(elem); } TextAnimatorProperty.prototype.searchProperties = function() { var i4; var len = this._textData.a.length; var animatorProps; var getProp = PropertyFactory.getProp; for (i4 = 0; i4 < len; i4 += 1) { animatorProps = this._textData.a[i4]; this._animatorsData[i4] = 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 i4; 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 mask; if (this._hasMaskedPath) { mask = this._pathData.m; if (!this._pathData.n || this._pathData._mdf) { var paths = mask.v; if (this._pathData.r.v) { paths = paths.reverse(); } pathInfo = { tLength: 0, segments: [] }; len = paths._length - 1; var bezierData; totalLength = 0; for (i4 = 0; i4 < len; i4 += 1) { bezierData = bez.buildBezierData( paths.v[i4], paths.v[i4 + 1], [paths.o[i4][0] - paths.v[i4][0], paths.o[i4][1] - paths.v[i4][1]], [paths.i[i4 + 1][0] - paths.v[i4 + 1][0], paths.i[i4 + 1][1] - paths.v[i4 + 1][1]] ); pathInfo.tLength += bezierData.segmentLength; pathInfo.segments.push(bezierData); totalLength += bezierData.segmentLength; } i4 = len; if (mask.v.c) { bezierData = bez.buildBezierData( paths.v[i4], paths.v[0], [paths.o[i4][0] - paths.v[i4][0], paths.o[i4][1] - paths.v[i4][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 && mask.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 j; 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 k; 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 (i4 = 0; i4 < len; i4 += 1) { if (letters[i4].n) { if (animatorJustifyOffset) { animatorJustifyOffset += animatorFirstCharOffset; } while (lastIndex < i4) { letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; lastIndex += 1; } animatorJustifyOffset = 0; isNewLine = true; } else { for (j = 0; j < jLen; j += 1) { animatorProps = animators[j].a; if (animatorProps.t.propType) { if (isNewLine && documentData.j === 2) { animatorFirstCharOffset += animatorProps.t.v * justifyOffsetMult; } animatorSelector = animators[j].s; mult = animatorSelector.getMult(letters[i4].anIndexes[j], textData.a[j].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 < i4) { letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; lastIndex += 1; } } for (i4 = 0; i4 < len; i4 += 1) { matrixHelper.reset(); elemOpacity = 1; if (letters[i4].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[i4].line) { switch (documentData.j) { case 1: currentLength += totalLength - documentData.lineWidths[letters[i4].line]; break; case 2: currentLength += (totalLength - documentData.lineWidths[letters[i4].line]) / 2; break; } currentLine = letters[i4].line; } if (ind !== letters[i4].ind) { if (letters[ind]) { currentLength += letters[ind].extra; } currentLength += letters[i4].an / 2; ind = letters[i4].ind; } currentLength += alignment[0] * letters[i4].an * 5e-3; var animatorOffset = 0; for (j = 0; j < jLen; j += 1) { animatorProps = animators[j].a; if (animatorProps.p.propType) { animatorSelector = animators[j].s; mult = animatorSelector.getMult(letters[i4].anIndexes[j], textData.a[j].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[j].s; mult = animatorSelector.getMult(letters[i4].anIndexes[j], textData.a[j].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[i4].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 (mask.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[i4].an / 2 - letters[i4].add; matrixHelper.translate(-offf, 0, 0); } else { offf = letters[i4].an / 2 - letters[i4].add; matrixHelper.translate(-offf, 0, 0); matrixHelper.translate(-alignment[0] * letters[i4].an * 5e-3, -alignment[1] * yOff * 0.01, 0); } for (j = 0; j < jLen; j += 1) { animatorProps = animators[j].a; if (animatorProps.t.propType) { animatorSelector = animators[j].s; mult = animatorSelector.getMult(letters[i4].anIndexes[j], textData.a[j].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 (j = 0; j < jLen; j += 1) { animatorProps = animators[j].a; if (animatorProps.a.propType) { animatorSelector = animators[j].s; mult = animatorSelector.getMult(letters[i4].anIndexes[j], textData.a[j].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 (j = 0; j < jLen; j += 1) { animatorProps = animators[j].a; if (animatorProps.s.propType) { animatorSelector = animators[j].s; mult = animatorSelector.getMult(letters[i4].anIndexes[j], textData.a[j].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 (j = 0; j < jLen; j += 1) { animatorProps = animators[j].a; animatorSelector = animators[j].s; mult = animatorSelector.getMult(letters[i4].anIndexes[j], textData.a[j].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 (k = 0; k < 3; k += 1) { if (mult.length) { sc[k] += (animatorProps.sc.v[k] - sc[k]) * mult[0]; } else { sc[k] += (animatorProps.sc.v[k] - sc[k]) * mult; } } } if (documentData.fillColorAnim && documentData.fc) { if (animatorProps.fc.propType) { for (k = 0; k < 3; k += 1) { if (mult.length) { fc[k] += (animatorProps.fc.v[k] - fc[k]) * mult[0]; } else { fc[k] += (animatorProps.fc.v[k] - fc[k]) * 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 (j = 0; j < jLen; j += 1) { animatorProps = animators[j].a; if (animatorProps.p.propType) { animatorSelector = animators[j].s; mult = animatorSelector.getMult(letters[i4].anIndexes[j], textData.a[j].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 rot2 = Math.atan(tanAngle) * 180 / Math.PI; if (currentPoint.point[0] < prevPoint.point[0]) { rot2 += 180; } matrixHelper.rotate(-rot2 * Math.PI / 180); } matrixHelper.translate(xPathPos, yPathPos, 0); currentLength -= alignment[0] * letters[i4].an * 5e-3; if (letters[i4 + 1] && ind !== letters[i4 + 1].ind) { currentLength += letters[i4].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[i4].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i4].line]), 0, 0 ); break; case 2: matrixHelper.translate( letters[i4].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i4].line]) / 2, 0, 0 ); break; } matrixHelper.translate(0, -documentData.ls); matrixHelper.translate(offf, 0, 0); matrixHelper.translate(alignment[0] * letters[i4].an * 5e-3, alignment[1] * yOff * 0.01, 0); xPos += letters[i4].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 <= i4) { letterValue = new LetterProps(letterO, letterSw, letterSc, letterFc, letterM, letterP); this.renderedLetters.push(letterValue); renderedLettersCount += 1; this.lettersChangedFlag = true; } else { letterValue = this.renderedLetters[i4]; 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); function ITextElement() { } ITextElement.prototype.initElement = function(data, globalData, comp) { this.lettersChangedFlag = true; this.initFrame(); this.initBaseData(data, globalData, comp); this.textProperty = new TextProperty(this, data.t, this.dynamicProperties); this.textAnimator = new TextAnimatorProperty(data.t, this.renderType, this); this.initTransform(data, globalData, comp); 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 j; var jLen = shapes.length; var pathNodes; var shapeStr = ""; for (j = 0; j < jLen; j += 1) { if (shapes[j].ty === "sh") { pathNodes = shapes[j].ks.k; shapeStr += buildShapeString(pathNodes, pathNodes.i.length, true, matrixHelper); } } return shapeStr; }; ITextElement.prototype.updateDocumentData = function(newData, index22) { this.textProperty.updateDocumentData(newData, index22); }; 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; } 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() { }; var emptyShapeData = { shapes: [] }; function SVGTextLottieElement(data, globalData, comp) { this.textSpans = []; this.renderType = "svg"; this.initElement(data, globalData, comp); } 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 i4 = 0; var len = textArray.length; var textContents = []; var currentTextContent = ""; while (i4 < len) { if (textArray[i4] === String.fromCharCode(13) || textArray[i4] === String.fromCharCode(3)) { textContents.push(currentTextContent); currentTextContent = ""; } else { currentTextContent += textArray[i4]; } i4 += 1; } textContents.push(currentTextContent); return textContents; }; SVGTextLottieElement.prototype.buildShapeData = function(data, scale5) { if (data.shapes && data.shapes.length) { var shape = data.shapes[0]; if (shape.it) { var shapeItem = shape.it[shape.it.length - 1]; if (shapeItem.s) { shapeItem.s.k[0] = scale5; shapeItem.s.k[1] = scale5; } } } return data; }; SVGTextLottieElement.prototype.buildNewText = function() { this.addDynamicProperty(this); var i4; 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 (i4 = 0; i4 < len; i4 += 1) { tSpan = this.textSpans[i4].span || createNS("tspan"); tSpan.textContent = textContent[i4]; tSpan.setAttribute("x", 0); tSpan.setAttribute("y", yPos); tSpan.style.display = "inherit"; tElement.appendChild(tSpan); if (!this.textSpans[i4]) { this.textSpans[i4] = { span: null, glyph: null }; } this.textSpans[i4].span = tSpan; yPos += documentData.finalLineHeight; } this.layerElement.appendChild(tElement); } else { var cachedSpansLength = this.textSpans.length; var charData; for (i4 = 0; i4 < len; i4 += 1) { if (!this.textSpans[i4]) { this.textSpans[i4] = { span: null, childSpan: null, glyph: null }; } if (!usesGlyphs || !singleShape || i4 === 0) { tSpan = cachedSpansLength > i4 ? this.textSpans[i4].span : createNS(usesGlyphs ? "g" : "text"); if (cachedSpansLength <= i4) { tSpan.setAttribute("stroke-linecap", "butt"); tSpan.setAttribute("stroke-linejoin", "round"); tSpan.setAttribute("stroke-miterlimit", "4"); this.textSpans[i4].span = tSpan; if (usesGlyphs) { var childSpan = createNS("g"); tSpan.appendChild(childSpan); this.textSpans[i4].childSpan = childSpan; } this.textSpans[i4].span = tSpan; this.layerElement.appendChild(tSpan); } tSpan.style.display = "inherit"; } matrixHelper.reset(); if (singleShape) { if (letters[i4].n) { xPos = -trackingOffset; yPos += documentData.yOffset; yPos += firstLine ? 1 : 0; firstLine = false; } this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i4].line, xPos, yPos); xPos += letters[i4].l || 0; xPos += trackingOffset; } if (usesGlyphs) { charData = this.globalData.fontManager.getCharData( documentData.finalText[i4], 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 data = emptyShapeData; if (charData.data && charData.data.shapes) { data = this.buildShapeData(charData.data, documentData.finalSize); } glyphElement = new SVGShapeElement(data, this.globalData, this); } if (this.textSpans[i4].glyph) { var glyph = this.textSpans[i4].glyph; this.textSpans[i4].childSpan.removeChild(glyph.layerElement); glyph.destroy(); } this.textSpans[i4].glyph = glyphElement; glyphElement._debug = true; glyphElement.prepareFrame(0); glyphElement.renderFrame(); this.textSpans[i4].childSpan.appendChild(glyphElement.layerElement); if (charData.t === 1) { this.textSpans[i4].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[i4].val; tSpan.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve"); } } if (singleShape && tSpan) { tSpan.setAttribute("d", shapeStr); } } while (i4 < this.textSpans.length) { this.textSpans[i4].span.style.display = "none"; i4 += 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 i4; var len = this.textSpans.length; var glyphElement; this.renderedFrame = this.comp.renderedFrame; for (i4 = 0; i4 < len; i4 += 1) { glyphElement = this.textSpans[i4].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 i4; var len; var renderedLetters = this.textAnimator.renderedLetters; var letters = this.textProperty.currentData.l; len = letters.length; var renderedLetter; var textSpan; var glyphElement; for (i4 = 0; i4 < len; i4 += 1) { if (!letters[i4].n) { renderedLetter = renderedLetters[i4]; textSpan = this.textSpans[i4].span; glyphElement = this.textSpans[i4].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); } } } } } }; function ISolidElement(data, globalData, comp) { this.initElement(data, globalData, comp); } 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); }; function NullElement(data, globalData, comp) { this.initFrame(); this.initBaseData(data, globalData, comp); this.initFrame(); this.initTransform(data, globalData, comp); this.initHierarchy(); } 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); function SVGRendererBase() { } extendPrototype([BaseRenderer], SVGRendererBase); SVGRendererBase.prototype.createNull = function(data) { return new NullElement(data, this.globalData, this); }; SVGRendererBase.prototype.createShape = function(data) { return new SVGShapeElement(data, this.globalData, this); }; SVGRendererBase.prototype.createText = function(data) { return new SVGTextLottieElement(data, this.globalData, this); }; SVGRendererBase.prototype.createImage = function(data) { return new IImageElement(data, this.globalData, this); }; SVGRendererBase.prototype.createSolid = function(data) { return new ISolidElement(data, 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 i4; var len = this.layers ? this.layers.length : 0; for (i4 = 0; i4 < len; i4 += 1) { if (this.elements[i4]) { this.elements[i4].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 i4 = 0; var len = this.elements.length; while (i4 < len) { if (this.elements[i4] === element) { element.setMatte(this.elements[i4 - 1].layerId); break; } i4 += 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 i4; var len = this.layers.length; if (!this.completeLayers) { this.checkLayers(num); } for (i4 = len - 1; i4 >= 0; i4 -= 1) { if (this.completeLayers || this.elements[i4]) { this.elements[i4].prepareFrame(num - this.layers[i4].st); } } if (this.globalData._mdf) { for (i4 = 0; i4 < len; i4 += 1) { if (this.completeLayers || this.elements[i4]) { this.elements[i4].renderFrame(); } } } }; SVGRendererBase.prototype.appendElementInPos = function(element, pos) { var newElement = element.getBaseElement(); if (!newElement) { return; } var i4 = 0; var nextElement; while (i4 < pos) { if (this.elements[i4] && this.elements[i4] !== true && this.elements[i4].getBaseElement()) { nextElement = this.elements[i4].getBaseElement(); } i4 += 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"; }; function ICompElement() { } extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement, RenderableDOMElement], ICompElement); ICompElement.prototype.initElement = function(data, globalData, comp) { this.initFrame(); this.initBaseData(data, globalData, comp); this.initTransform(data, globalData, comp); this.initRenderable(); this.initHierarchy(); this.initRendererElement(); this.createContainerElements(); this.createRenderableComponents(); if (this.data.xt || !globalData.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 i4; var len = this.elements.length; if (!this.completeLayers) { this.checkLayers(this.renderedFrame); } for (i4 = len - 1; i4 >= 0; i4 -= 1) { if (this.completeLayers || this.elements[i4]) { this.elements[i4].prepareFrame(this.renderedFrame - this.layers[i4].st); if (this.elements[i4]._mdf) { this._mdf = true; } } } }; ICompElement.prototype.renderInnerContent = function() { var i4; var len = this.layers.length; for (i4 = 0; i4 < len; i4 += 1) { if (this.completeLayers || this.elements[i4]) { this.elements[i4].renderFrame(); } } }; ICompElement.prototype.setElements = function(elems) { this.elements = elems; }; ICompElement.prototype.getElements = function() { return this.elements; }; ICompElement.prototype.destroyElements = function() { var i4; var len = this.layers.length; for (i4 = 0; i4 < len; i4 += 1) { if (this.elements[i4]) { this.elements[i4].destroy(); } } }; ICompElement.prototype.destroy = function() { this.destroyElements(); this.destroyBaseElement(); }; function SVGCompElement(data, globalData, comp) { this.layers = data.layers; this.supports3d = true; this.completeLayers = false; this.pendingElements = []; this.elements = this.layers ? createSizedArray(this.layers.length) : []; this.initElement(data, globalData, comp); this.tm = data.tm ? PropertyFactory.getProp(this, data.tm, 0, globalData.frameRate, this) : { _placeholder: true }; } extendPrototype([SVGRendererBase, ICompElement, SVGBaseElement], SVGCompElement); SVGCompElement.prototype.createComp = function(data) { return new SVGCompElement(data, this.globalData, this); }; function SVGRenderer2(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"; } extendPrototype([SVGRendererBase], SVGRenderer2); SVGRenderer2.prototype.createComp = function(data) { return new SVGCompElement(data, this.globalData, this); }; function CVContextData() { this.saved = []; this.cArrPos = 0; this.cTr = new Matrix(); this.cO = 1; var i4; var len = 15; this.savedOp = createTypedArray("float32", len); for (i4 = 0; i4 < len; i4 += 1) { this.saved[i4] = createTypedArray("float32", 16); } this._length = len; } CVContextData.prototype.duplicate = function() { var newLength = this._length * 2; var currentSavedOp = this.savedOp; this.savedOp = createTypedArray("float32", newLength); this.savedOp.set(currentSavedOp); var i4 = 0; for (i4 = this._length; i4 < newLength; i4 += 1) { this.saved[i4] = createTypedArray("float32", 16); } this._length = newLength; }; CVContextData.prototype.reset = function() { this.cArrPos = 0; this.cTr.reset(); this.cO = 1; }; function ShapeTransformManager() { this.sequences = {}; this.sequenceList = []; this.transform_key_count = 0; } ShapeTransformManager.prototype = { addTransformSequence: function(transforms) { var i4; var len = transforms.length; var key = "_"; for (i4 = 0; i4 < len; i4 += 1) { key += transforms[i4].transform.key + "_"; } var sequence = this.sequences[key]; if (!sequence) { sequence = { transforms: [].concat(transforms), finalTransform: new Matrix(), _mdf: false }; this.sequences[key] = sequence; this.sequenceList.push(sequence); } return sequence; }, processSequence: function(sequence, isFirstFrame) { var i4 = 0; var len = sequence.transforms.length; var _mdf = isFirstFrame; while (i4 < len && !isFirstFrame) { if (sequence.transforms[i4].transform.mProps._mdf) { _mdf = true; break; } i4 += 1; } if (_mdf) { var props; sequence.finalTransform.reset(); for (i4 = len - 1; i4 >= 0; i4 -= 1) { props = sequence.transforms[i4].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 i4; var len = this.sequenceList.length; for (i4 = 0; i4 < len; i4 += 1) { this.processSequence(this.sequenceList[i4], isFirstFrame); } }, getNewKey: function() { this.transform_key_count += 1; return "_" + this.transform_key_count; } }; function CVEffects() { } CVEffects.prototype.renderFrame = function() { }; function CVMaskElement(data, element) { this.data = data; this.element = element; this.masksProperties = this.data.masksProperties || []; this.viewData = createSizedArray(this.masksProperties.length); var i4; var len = this.masksProperties.length; var hasMasks = false; for (i4 = 0; i4 < len; i4 += 1) { if (this.masksProperties[i4].mode !== "n") { hasMasks = true; } this.viewData[i4] = ShapePropertyFactory.getShapeProp(this.element, this.masksProperties[i4], 3); } this.hasMasks = hasMasks; if (hasMasks) { this.element.addRenderableComponent(this); } } CVMaskElement.prototype.renderFrame = function() { if (!this.hasMasks) { return; } var transform = this.element.finalTransform.mat; var ctx = this.element.canvasContext; var i4; var len = this.masksProperties.length; var pt; var pts; var data; ctx.beginPath(); for (i4 = 0; i4 < len; i4 += 1) { if (this.masksProperties[i4].mode !== "n") { if (this.masksProperties[i4].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); } data = this.viewData[i4].v; pt = transform.applyToPointArray(data.v[0][0], data.v[0][1], 0); ctx.moveTo(pt[0], pt[1]); var j; var jLen = data._length; for (j = 1; j < jLen; j += 1) { pts = transform.applyToTriplePoints(data.o[j - 1], data.i[j], data.v[j]); ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); } pts = transform.applyToTriplePoints(data.o[j - 1], data.i[0], data.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; }; function CVBaseElement() { } CVBaseElement.prototype = { createElements: function() { }, initRendererElement: function() { }, createContainerElements: function() { this.canvasContext = this.globalData.canvasContext; this.renderableEffectsManager = new CVEffects(); }, createContent: function() { }, setBlendMode: function() { var globalData = this.globalData; if (globalData.blendMode !== this.data.bm) { globalData.blendMode = this.data.bm; var blendModeValue = getBlendMode(this.data.bm); globalData.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; function CVShapeData(element, data, styles2, transformsManager) { this.styledShapes = []; this.tr = [0, 0, 0, 0, 0, 0]; var ty = 4; if (data.ty === "rc") { ty = 5; } else if (data.ty === "el") { ty = 6; } else if (data.ty === "sr") { ty = 7; } this.sh = ShapePropertyFactory.getShapeProp(element, data, ty, element); var i4; var len = styles2.length; var styledShape; for (i4 = 0; i4 < len; i4 += 1) { if (!styles2[i4].closed) { styledShape = { transforms: transformsManager.addTransformSequence(styles2[i4].transforms), trNodes: [] }; this.styledShapes.push(styledShape); styles2[i4].elements.push(styledShape); } } } CVShapeData.prototype.setAsAnimated = SVGShapeData.prototype.setAsAnimated; function CVShapeElement(data, globalData, comp) { this.shapes = []; this.shapesData = data.shapes; this.stylesList = []; this.itemsData = []; this.prevViewData = []; this.shapeModifiers = []; this.processedElements = []; this.transformsManager = new ShapeTransformManager(); this.initElement(data, globalData, comp); } 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(data, transforms) { var styleElem = { data, type: data.ty, preTransforms: this.transformsManager.addTransformSequence(transforms), transforms: [], elements: [], closed: data.hd === true }; var elementData = {}; if (data.ty === "fl" || data.ty === "st") { elementData.c = PropertyFactory.getProp(this, data.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 (data.ty === "gf" || data.ty === "gs") { elementData.s = PropertyFactory.getProp(this, data.s, 1, null, this); elementData.e = PropertyFactory.getProp(this, data.e, 1, null, this); elementData.h = PropertyFactory.getProp(this, data.h || { k: 0 }, 0, 0.01, this); elementData.a = PropertyFactory.getProp(this, data.a || { k: 0 }, 0, degToRads, this); elementData.g = new GradientProperty(this, data.g, this); } elementData.o = PropertyFactory.getProp(this, data.o, 0, 0.01, this); if (data.ty === "st" || data.ty === "gs") { styleElem.lc = lineCapEnum[data.lc || 2]; styleElem.lj = lineJoinEnum[data.lj || 2]; if (data.lj == 1) { styleElem.ml = data.ml; } elementData.w = PropertyFactory.getProp(this, data.w, 0, null, this); if (!elementData.w.k) { styleElem.wi = elementData.w.v; } if (data.d) { var d2 = new DashProperty(this, data.d, "canvas", this); elementData.d = d2; if (!elementData.d.k) { styleElem.da = elementData.d.dashArray; styleElem.do = elementData.d.dashoffset[0]; } } } else { styleElem.r = data.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(data) { var elementData = { transform: { opacity: 1, _opMdf: false, key: this.transformsManager.getNewKey(), op: PropertyFactory.getProp(this, data.o, 0, 0.01, this), mProps: TransformPropertyFactory.getTransformProperty(this, data, this) } }; return elementData; }; CVShapeElement.prototype.createShapeElement = function(data) { var elementData = new CVShapeData(this, data, this.stylesList, this.transformsManager); this.shapes.push(elementData); this.addShapeToModifiers(elementData); return elementData; }; CVShapeElement.prototype.reloadShapes = function() { this._isFirstFrame = true; var i4; var len = this.itemsData.length; for (i4 = 0; i4 < len; i4 += 1) { this.prevViewData[i4] = this.itemsData[i4]; } this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []); len = this.dynamicProperties.length; for (i4 = 0; i4 < len; i4 += 1) { this.dynamicProperties[i4].getValue(); } this.renderModifiers(); this.transformsManager.processSequences(this._isFirstFrame); }; CVShapeElement.prototype.addTransformToStyleList = function(transform) { var i4; var len = this.stylesList.length; for (i4 = 0; i4 < len; i4 += 1) { if (!this.stylesList[i4].closed) { this.stylesList[i4].transforms.push(transform); } } }; CVShapeElement.prototype.removeTransformFromStyleList = function() { var i4; var len = this.stylesList.length; for (i4 = 0; i4 < len; i4 += 1) { if (!this.stylesList[i4].closed) { this.stylesList[i4].transforms.pop(); } } }; CVShapeElement.prototype.closeStyles = function(styles2) { var i4; var len = styles2.length; for (i4 = 0; i4 < len; i4 += 1) { styles2[i4].closed = true; } }; CVShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, shouldRender, transforms) { var i4; var len = arr.length - 1; var j; var jLen; var ownStyles = []; var ownModifiers = []; var processedPos; var modifier; var currentTransform; var ownTransforms = [].concat(transforms); for (i4 = len; i4 >= 0; i4 -= 1) { processedPos = this.searchProcessedElement(arr[i4]); if (!processedPos) { arr[i4]._shouldRender = shouldRender; } else { itemsData[i4] = prevViewData[processedPos - 1]; } if (arr[i4].ty === "fl" || arr[i4].ty === "st" || arr[i4].ty === "gf" || arr[i4].ty === "gs") { if (!processedPos) { itemsData[i4] = this.createStyleElement(arr[i4], ownTransforms); } else { itemsData[i4].style.closed = false; } ownStyles.push(itemsData[i4].style); } else if (arr[i4].ty === "gr") { if (!processedPos) { itemsData[i4] = this.createGroupElement(arr[i4]); } else { jLen = itemsData[i4].it.length; for (j = 0; j < jLen; j += 1) { itemsData[i4].prevViewData[j] = itemsData[i4].it[j]; } } this.searchShapes(arr[i4].it, itemsData[i4].it, itemsData[i4].prevViewData, shouldRender, ownTransforms); } else if (arr[i4].ty === "tr") { if (!processedPos) { currentTransform = this.createTransformElement(arr[i4]); itemsData[i4] = currentTransform; } ownTransforms.push(itemsData[i4]); this.addTransformToStyleList(itemsData[i4]); } else if (arr[i4].ty === "sh" || arr[i4].ty === "rc" || arr[i4].ty === "el" || arr[i4].ty === "sr") { if (!processedPos) { itemsData[i4] = this.createShapeElement(arr[i4]); } } else if (arr[i4].ty === "tm" || arr[i4].ty === "rd" || arr[i4].ty === "pb") { if (!processedPos) { modifier = ShapeModifiers.getModifier(arr[i4].ty); modifier.init(this, arr[i4]); itemsData[i4] = modifier; this.shapeModifiers.push(modifier); } else { modifier = itemsData[i4]; modifier.closed = false; } ownModifiers.push(modifier); } else if (arr[i4].ty === "rp") { if (!processedPos) { modifier = ShapeModifiers.getModifier(arr[i4].ty); itemsData[i4] = modifier; modifier.init(this, arr, i4, itemsData); this.shapeModifiers.push(modifier); shouldRender = false; } else { modifier = itemsData[i4]; modifier.closed = true; } ownModifiers.push(modifier); } this.addProcessedElement(arr[i4], i4 + 1); } this.removeTransformFromStyleList(); this.closeStyles(ownStyles); len = ownModifiers.length; for (i4 = 0; i4 < len; i4 += 1) { ownModifiers[i4].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 i4; var len = this.stylesList.length; var j; var jLen; var k; var kLen; var elems; var nodes; var renderer = this.globalData.renderer; var ctx = this.globalData.canvasContext; var type; var currentStyle; for (i4 = 0; i4 < len; i4 += 1) { currentStyle = this.stylesList[i4]; type = currentStyle.type; if (!((type === "st" || type === "gs") && currentStyle.wi === 0 || !currentStyle.data._shouldRender || currentStyle.coOp === 0 || this.globalData.currentGlobalAlpha === 0)) { renderer.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; } renderer.ctxOpacity(currentStyle.coOp); if (type !== "st" && type !== "gs") { ctx.beginPath(); } renderer.ctxTransform(currentStyle.preTransforms.finalTransform.props); jLen = elems.length; for (j = 0; j < jLen; j += 1) { if (type === "st" || type === "gs") { ctx.beginPath(); if (currentStyle.da) { ctx.setLineDash(currentStyle.da); ctx.lineDashOffset = currentStyle.do; } } nodes = elems[j].trNodes; kLen = nodes.length; for (k = 0; k < kLen; k += 1) { if (nodes[k].t === "m") { ctx.moveTo(nodes[k].p[0], nodes[k].p[1]); } else if (nodes[k].t === "c") { ctx.bezierCurveTo( nodes[k].pts[0], nodes[k].pts[1], nodes[k].pts[2], nodes[k].pts[3], nodes[k].pts[4], nodes[k].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); } renderer.restore(); } } }; CVShapeElement.prototype.renderShape = function(parentTransform, items, data, isMain) { var i4; var len = items.length - 1; var groupTransform; groupTransform = parentTransform; for (i4 = len; i4 >= 0; i4 -= 1) { if (items[i4].ty === "tr") { groupTransform = data[i4].transform; this.renderShapeTransform(parentTransform, groupTransform); } else if (items[i4].ty === "sh" || items[i4].ty === "el" || items[i4].ty === "rc" || items[i4].ty === "sr") { this.renderPath(items[i4], data[i4]); } else if (items[i4].ty === "fl") { this.renderFill(items[i4], data[i4], groupTransform); } else if (items[i4].ty === "st") { this.renderStroke(items[i4], data[i4], groupTransform); } else if (items[i4].ty === "gf" || items[i4].ty === "gs") { this.renderGradientFill(items[i4], data[i4], groupTransform); } else if (items[i4].ty === "gr") { this.renderShape(groupTransform, items[i4].it, data[i4].it); } else if (items[i4].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 i4; var len; var j; var jLen = paths._length; shapeNodes.length = 0; var groupTransformMat = styledShape.transforms.finalTransform; for (j = 0; j < jLen; j += 1) { var pathNodes = paths.shapes[j]; if (pathNodes && pathNodes.v) { len = pathNodes._length; for (i4 = 1; i4 < len; i4 += 1) { if (i4 === 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[i4 - 1], pathNodes.i[i4], pathNodes.v[i4]) }); } 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[i4 - 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 i4; var len = itemData.styledShapes.length; for (i4 = 0; i4 < len; i4 += 1) { this.renderStyledShape(itemData.styledShapes[i4], 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 x = Math.cos(ang + itemData.a.v) * dist + pt1[0]; var y = Math.sin(ang + itemData.a.v) * dist + pt1[1]; grd = ctx.createRadialGradient(x, y, 0, pt1[0], pt1[1], rad); } var i4; var len = styleData.g.p; var cValues = itemData.g.c; var opacity = 1; for (i4 = 0; i4 < len; i4 += 1) { if (itemData.g._hasOpacity && itemData.g._collapsable) { opacity = itemData.g.o[i4 * 2 + 1]; } grd.addColorStop( cValues[i4 * 4] / 100, "rgba(" + cValues[i4 * 4 + 1] + "," + cValues[i4 * 4 + 2] + "," + cValues[i4 * 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 d2 = itemData.d; if (d2 && (d2._mdf || this._isFirstFrame)) { styleElem.da = d2.dashArray; styleElem.do = d2.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; }; function CVTextElement(data, globalData, comp) { 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(data, globalData, comp); } 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 i4; 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 k; var kLen; var shapes; var j; 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 (i4 = 0; i4 < len; i4 += 1) { charData = this.globalData.fontManager.getCharData( documentData.finalText[i4], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily ); shapeData = charData && charData.data || {}; matrixHelper.reset(); if (singleShape && letters[i4].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[i4].line, xPos, yPos); } commands = createSizedArray(jLen - 1); var commandsCounter = 0; for (j = 0; j < jLen; j += 1) { if (shapes[j].ty === "sh") { kLen = shapes[j].ks.k.i.length; pathNodes = shapes[j].ks.k; pathArr = []; for (k = 1; k < kLen; k += 1) { if (k === 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[k - 1][0], pathNodes.o[k - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k - 1][0], pathNodes.o[k - 1][1], 0), matrixHelper.applyToX(pathNodes.i[k][0], pathNodes.i[k][1], 0), matrixHelper.applyToY(pathNodes.i[k][0], pathNodes.i[k][1], 0), matrixHelper.applyToX(pathNodes.v[k][0], pathNodes.v[k][1], 0), matrixHelper.applyToY(pathNodes.v[k][0], pathNodes.v[k][1], 0) ); } pathArr.push( matrixHelper.applyToX(pathNodes.o[k - 1][0], pathNodes.o[k - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k - 1][0], pathNodes.o[k - 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[i4].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 i4; var len; var j; var jLen; var k; 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 (i4 = 0; i4 < len; i4 += 1) { if (!letters[i4].n) { renderedLetter = renderedLetters[i4]; 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[i4].elem; jLen = commands.length; this.globalData.canvasContext.beginPath(); for (j = 0; j < jLen; j += 1) { pathArr = commands[j]; kLen = pathArr.length; this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]); for (k = 2; k < kLen; k += 6) { this.globalData.canvasContext.bezierCurveTo( pathArr[k], pathArr[k + 1], pathArr[k + 2], pathArr[k + 3], pathArr[k + 4], pathArr[k + 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[i4].elem; jLen = commands.length; this.globalData.canvasContext.beginPath(); for (j = 0; j < jLen; j += 1) { pathArr = commands[j]; kLen = pathArr.length; this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]); for (k = 2; k < kLen; k += 6) { this.globalData.canvasContext.bezierCurveTo( pathArr[k], pathArr[k + 1], pathArr[k + 2], pathArr[k + 3], pathArr[k + 4], pathArr[k + 5] ); } } this.globalData.canvasContext.closePath(); this.globalData.canvasContext.stroke(); } if (renderedLetter) { this.globalData.renderer.restore(); } } } }; function CVImageElement(data, globalData, comp) { this.assetData = globalData.getAssetData(data.refId); this.img = globalData.imageLoader.getAsset(this.assetData); this.initElement(data, globalData, comp); } 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; }; function CVSolidElement(data, globalData, comp) { this.initElement(data, globalData, comp); } 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); }; 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"; } extendPrototype([BaseRenderer], CanvasRendererBase); CanvasRendererBase.prototype.createShape = function(data) { return new CVShapeElement(data, this.globalData, this); }; CanvasRendererBase.prototype.createText = function(data) { return new CVTextElement(data, this.globalData, this); }; CanvasRendererBase.prototype.createImage = function(data) { return new CVImageElement(data, this.globalData, this); }; CanvasRendererBase.prototype.createSolid = function(data) { return new CVSolidElement(data, this.globalData, this); }; CanvasRendererBase.prototype.createNull = SVGRenderer2.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 i4; var arr = this.contextData.saved[this.contextData.cArrPos]; for (i4 = 0; i4 < 16; i4 += 1) { arr[i4] = props[i4]; } 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 i4; var arr = this.contextData.cTr.props; for (i4 = 0; i4 < 16; i4 += 1) { arr[i4] = popped[i4]; } 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 origin2 = "0px 0px 0px"; containerStyle.transformOrigin = origin2; containerStyle.mozTransformOrigin = origin2; containerStyle.webkitTransformOrigin = origin2; containerStyle["-webkit-transform"] = origin2; 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 i4; var len = this.layers ? this.layers.length : 0; for (i4 = len - 1; i4 >= 0; i4 -= 1) { if (this.elements[i4]) { this.elements[i4].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 i4; var len = this.layers.length; if (!this.completeLayers) { this.checkLayers(num); } for (i4 = 0; i4 < len; i4 += 1) { if (this.completeLayers || this.elements[i4]) { this.elements[i4].prepareFrame(num - this.layers[i4].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 (i4 = len - 1; i4 >= 0; i4 -= 1) { if (this.completeLayers || this.elements[i4]) { this.elements[i4].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"; }; function CVCompElement(data, globalData, comp) { this.completeLayers = false; this.layers = data.layers; this.pendingElements = []; this.elements = createSizedArray(this.layers.length); this.initElement(data, globalData, comp); this.tm = data.tm ? PropertyFactory.getProp(this, data.tm, 0, globalData.frameRate, this) : { _placeholder: true }; } 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 i4; var len = this.layers.length; for (i4 = len - 1; i4 >= 0; i4 -= 1) { if (this.completeLayers || this.elements[i4]) { this.elements[i4].renderFrame(); } } }; CVCompElement.prototype.destroy = function() { var i4; var len = this.layers.length; for (i4 = len - 1; i4 >= 0; i4 -= 1) { if (this.elements[i4]) { this.elements[i4].destroy(); } } this.layers = null; this.elements = null; }; CVCompElement.prototype.createComp = function(data) { return new CVCompElement(data, this.globalData, this); }; 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"; } extendPrototype([CanvasRendererBase], CanvasRenderer); CanvasRenderer.prototype.createComp = function(data) { return new CVCompElement(data, 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 ob = {}; ob.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 i4; var len = registers.length; for (i4 = 0; i4 < len; i4 += 1) { registers[i4].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 ob; })(); function seedRandom(pool, math) { var global2 = this, width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto; function seedrandom(seed3, options, callback) { var key = []; options = options === true ? { entropy: true } : options || {}; var shortseed = mixkey( flatten(options.entropy ? [seed3, tostring(pool)] : seed3 === null ? autoseed() : seed3, 3), key ); var arc4 = new ARC4(key); var prng = function() { var n2 = arc4.g(chunks), d2 = startdenom, x = 0; while (n2 < significance) { n2 = (n2 + x) * width; d2 *= width; x = arc4.g(1); } while (n2 >= overflow) { n2 /= 2; d2 /= 2; x >>>= 1; } return (n2 + x) / d2; }; 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, seed22, 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 seed22; } else return prng2; })(prng, shortseed, "global" in options ? options.global : this == math, options.state); } math["seed" + rngname] = seedrandom; function ARC4(key) { var t3, keylen = key.length, me = this, i4 = 0, j = me.i = me.j = 0, s2 = me.S = []; if (!keylen) { key = [keylen++]; } while (i4 < width) { s2[i4] = i4++; } for (i4 = 0; i4 < width; i4++) { s2[i4] = s2[j = mask & j + key[i4 % keylen] + (t3 = s2[i4])]; s2[j] = t3; } me.g = function(count) { var t22, r2 = 0, i22 = me.i, j2 = me.j, s22 = me.S; while (count--) { t22 = s22[i22 = mask & i22 + 1]; r2 = r2 * width + s22[mask & (s22[i22] = s22[j2 = mask & j2 + t22]) + (s22[j2] = t22)]; } me.i = i22; me.j = j2; return r2; }; } function copy(f2, t3) { t3.i = f2.i; t3.j = f2.j; t3.S = f2.S.slice(); return t3; } function flatten(obj, depth) { var result = [], typ = typeof obj, prop; if (depth && typ == "object") { for (prop in obj) { try { result.push(flatten(obj[prop], depth - 1)); } catch (e2) { } } } return result.length ? result : typ == "string" ? obj : obj + "\0"; } function mixkey(seed3, key) { var stringseed = seed3 + "", smear, j = 0; while (j < stringseed.length) { key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++); } return tostring(key); } function autoseed() { try { if (nodecrypto) ; var out7 = new Uint8Array(width); (global2.crypto || global2.msCrypto).getRandomValues(out7); return tostring(out7); } catch (e2) { var browser = global2.navigator, plugins = browser && browser.plugins; return [+/* @__PURE__ */ new Date(), global2, plugins, global2.screen, tostring(pool)]; } } function tostring(a6) { return String.fromCharCode.apply(0, a6); } mixkey(math.random(), pool); } function initialize$2(BMMath2) { seedRandom([], BMMath2); } const ExpressionManager = (function() { var ob = {}; var Math2 = BMMath; var window2 = null; var document2 = null; var XMLHttpRequest2 = null; var fetch2 = null; var frames = null; initialize$2(BMMath); function $bm_isInstanceOfArray(arr) { return arr.constructor === Array || arr.constructor === Float32Array; } function isNumerable(tOfV, v5) { return tOfV === "number" || tOfV === "boolean" || tOfV === "string" || v5 instanceof Number; } function $bm_neg(a6) { var tOfA = typeof a6; if (tOfA === "number" || tOfA === "boolean" || a6 instanceof Number) { return -a6; } if ($bm_isInstanceOfArray(a6)) { var i4; var lenA = a6.length; var retArr = []; for (i4 = 0; i4 < lenA; i4 += 1) { retArr[i4] = -a6[i4]; } return retArr; } if (a6.propType) { return a6.v; } return -a6; } BezierFactory.getBezierEasing(0.333, 0, 0.833, 0.833, "easeIn").get; BezierFactory.getBezierEasing(0.167, 0.167, 0.667, 1, "easeOut").get; BezierFactory.getBezierEasing(0.33, 0, 0.667, 1, "easeInOut").get; function sum(a6, b5) { var tOfA = typeof a6; var tOfB = typeof b5; if (tOfA === "string" || tOfB === "string") { return a6 + b5; } if (isNumerable(tOfA, a6) && isNumerable(tOfB, b5)) { return a6 + b5; } if ($bm_isInstanceOfArray(a6) && isNumerable(tOfB, b5)) { a6 = a6.slice(0); a6[0] += b5; return a6; } if (isNumerable(tOfA, a6) && $bm_isInstanceOfArray(b5)) { b5 = b5.slice(0); b5[0] = a6 + b5[0]; return b5; } if ($bm_isInstanceOfArray(a6) && $bm_isInstanceOfArray(b5)) { var i4 = 0; var lenA = a6.length; var lenB = b5.length; var retArr = []; while (i4 < lenA || i4 < lenB) { if ((typeof a6[i4] === "number" || a6[i4] instanceof Number) && (typeof b5[i4] === "number" || b5[i4] instanceof Number)) { retArr[i4] = a6[i4] + b5[i4]; } else { retArr[i4] = b5[i4] === void 0 ? a6[i4] : a6[i4] || b5[i4]; } i4 += 1; } return retArr; } return 0; } var add3 = sum; function sub3(a6, b5) { var tOfA = typeof a6; var tOfB = typeof b5; if (isNumerable(tOfA, a6) && isNumerable(tOfB, b5)) { if (tOfA === "string") { a6 = parseInt(a6, 10); } if (tOfB === "string") { b5 = parseInt(b5, 10); } return a6 - b5; } if ($bm_isInstanceOfArray(a6) && isNumerable(tOfB, b5)) { a6 = a6.slice(0); a6[0] -= b5; return a6; } if (isNumerable(tOfA, a6) && $bm_isInstanceOfArray(b5)) { b5 = b5.slice(0); b5[0] = a6 - b5[0]; return b5; } if ($bm_isInstanceOfArray(a6) && $bm_isInstanceOfArray(b5)) { var i4 = 0; var lenA = a6.length; var lenB = b5.length; var retArr = []; while (i4 < lenA || i4 < lenB) { if ((typeof a6[i4] === "number" || a6[i4] instanceof Number) && (typeof b5[i4] === "number" || b5[i4] instanceof Number)) { retArr[i4] = a6[i4] - b5[i4]; } else { retArr[i4] = b5[i4] === void 0 ? a6[i4] : a6[i4] || b5[i4]; } i4 += 1; } return retArr; } return 0; } function mul(a6, b5) { var tOfA = typeof a6; var tOfB = typeof b5; var arr; if (isNumerable(tOfA, a6) && isNumerable(tOfB, b5)) { return a6 * b5; } var i4; var len; if ($bm_isInstanceOfArray(a6) && isNumerable(tOfB, b5)) { len = a6.length; arr = createTypedArray("float32", len); for (i4 = 0; i4 < len; i4 += 1) { arr[i4] = a6[i4] * b5; } return arr; } if (isNumerable(tOfA, a6) && $bm_isInstanceOfArray(b5)) { len = b5.length; arr = createTypedArray("float32", len); for (i4 = 0; i4 < len; i4 += 1) { arr[i4] = a6 * b5[i4]; } return arr; } return 0; } function div(a6, b5) { var tOfA = typeof a6; var tOfB = typeof b5; var arr; if (isNumerable(tOfA, a6) && isNumerable(tOfB, b5)) { return a6 / b5; } var i4; var len; if ($bm_isInstanceOfArray(a6) && isNumerable(tOfB, b5)) { len = a6.length; arr = createTypedArray("float32", len); for (i4 = 0; i4 < len; i4 += 1) { arr[i4] = a6[i4] / b5; } return arr; } if (isNumerable(tOfA, a6) && $bm_isInstanceOfArray(b5)) { len = b5.length; arr = createTypedArray("float32", len); for (i4 = 0; i4 < len; i4 += 1) { arr[i4] = a6 / b5[i4]; } return arr; } return 0; } function mod(a6, b5) { if (typeof a6 === "string") { a6 = parseInt(a6, 10); } if (typeof b5 === "string") { b5 = parseInt(b5, 10); } return a6 % b5; } var $bm_sum = sum; var $bm_sub = sub3; var $bm_mul = mul; var $bm_div = div; var $bm_mod = mod; function clamp4(num, min, max2) { if (min > max2) { var mm = max2; max2 = min; min = mm; } return Math2.min(Math2.max(num, min), max2); } function radiansToDegrees(val) { return val / degToRads; } var radians_to_degrees = radiansToDegrees; function degreesToRadians(val) { return val * degToRads; } var degrees_to_radians = radiansToDegrees; var helperLengthArray = [0, 0, 0, 0, 0, 0]; function length3(arr1, arr2) { if (typeof arr1 === "number" || arr1 instanceof Number) { arr2 = arr2 || 0; return Math2.abs(arr1 - arr2); } if (!arr2) { arr2 = helperLengthArray; } var i4; var len = Math2.min(arr1.length, arr2.length); var addedLength = 0; for (i4 = 0; i4 < len; i4 += 1) { addedLength += Math2.pow(arr2[i4] - arr1[i4], 2); } return Math2.sqrt(addedLength); } function normalize2(vec) { return div(vec, length3(vec)); } function rgbToHsl(val) { var r2 = val[0]; var g = val[1]; var b5 = val[2]; var max2 = Math2.max(r2, g, b5); var min = Math2.min(r2, g, b5); var h; var s2; var l2 = (max2 + min) / 2; if (max2 === min) { h = 0; s2 = 0; } else { var d2 = max2 - min; s2 = l2 > 0.5 ? d2 / (2 - max2 - min) : d2 / (max2 + min); switch (max2) { case r2: h = (g - b5) / d2 + (g < b5 ? 6 : 0); break; case g: h = (b5 - r2) / d2 + 2; break; case b5: h = (r2 - g) / d2 + 4; break; } h /= 6; } return [h, s2, l2, val[3]]; } function hue2rgb(p2, q, t3) { if (t3 < 0) t3 += 1; if (t3 > 1) t3 -= 1; if (t3 < 1 / 6) return p2 + (q - p2) * 6 * t3; if (t3 < 1 / 2) return q; if (t3 < 2 / 3) return p2 + (q - p2) * (2 / 3 - t3) * 6; return p2; } function hslToRgb(val) { var h = val[0]; var s2 = val[1]; var l2 = val[2]; var r2; var g; var b5; if (s2 === 0) { r2 = l2; b5 = l2; g = l2; } else { var q = l2 < 0.5 ? l2 * (1 + s2) : l2 + s2 - l2 * s2; var p2 = 2 * l2 - q; r2 = hue2rgb(p2, q, h + 1 / 3); g = hue2rgb(p2, q, h); b5 = hue2rgb(p2, q, h - 1 / 3); } return [r2, g, b5, val[3]]; } function linear3(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 i4; var len = value1.length; var arr = createTypedArray("float32", len); for (i4 = 0; i4 < len; i4 += 1) { arr[i4] = value1[i4] + (value2[i4] - value1[i4]) * 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 i4; var len = max2.length; if (!min) { min = createTypedArray("float32", len); } var arr = createTypedArray("float32", len); var rnd = BMMath.random(); for (i4 = 0; i4 < len; i4 += 1) { arr[i4] = min[i4] + rnd * (max2[i4] - min[i4]); } return arr; } if (min === void 0) { min = 0; } var rndm = BMMath.random(); return min + rndm * (max2 - min); } function createPath2(points, inTangents, outTangents, closed) { var i4; var len = points.length; var path = shapePool.newElement(); path.setPathData(!!closed, len); var arrPlaceholder = [0, 0]; var inVertexPoint; var outVertexPoint; for (i4 = 0; i4 < len; i4 += 1) { inVertexPoint = inTangents && inTangents[i4] ? inTangents[i4] : arrPlaceholder; outVertexPoint = outTangents && outTangents[i4] ? outTangents[i4] : arrPlaceholder; path.setTripleAt( points[i4][0], points[i4][1], outVertexPoint[0] + points[i4][0], outVertexPoint[1] + points[i4][1], inVertexPoint[0] + points[i4][0], inVertexPoint[1] + points[i4][1], i4, true ); } return path; } function noOp(_value) { return _value; } function initiateExpression(elem, data, property) { return noOp; } ob.initiateExpression = initiateExpression; ob.__preventDeadCodeRemoval = [ window2, document2, XMLHttpRequest2, fetch2, frames, $bm_neg, add3, $bm_sum, $bm_sub, $bm_mul, $bm_div, $bm_mod, clamp4, radians_to_degrees, degreesToRadians, degrees_to_radians, normalize2, rgbToHsl, hslToRgb, linear3, random, createPath2 ]; return ob; })(); const expressionHelpers = /* @__PURE__ */ (function() { function searchExpressions(elem, data, prop) { if (data.x) { prop.k = true; prop.x = true; prop.initiateExpression = ExpressionManager.initiateExpression; prop.effectsSequence.push(prop.initiateExpression(elem, data, 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 v13 = this.getValueAtTime(frameNum); var v22 = this.getValueAtTime(frameNum + delta); var speed = 0; if (v13.length) { var i4; for (i4 = 0; i4 < v13.length; i4 += 1) { speed += Math.pow(v22[i4] - v13[i4], 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 v13 = this.getValueAtTime(frameNum); var v22 = this.getValueAtTime(frameNum + delta); var velocity; if (v13.length) { velocity = createTypedArray("float32", v13.length); var i4; for (i4 = 0; i4 < v13.length; i4 += 1) { velocity[i4] = (v22[i4] - v13[i4]) / delta; } } else { velocity = (v22 - v13) / delta; } return velocity; } function getStaticValueAtTime() { return this.pv; } function setGroupProperty(propertyGroup) { this.propertyGroup = propertyGroup; } return { searchExpressions, getSpeedAtTime, getVelocityAtTime, getValueAtTime, getStaticValueAtTime, setGroupProperty }; })(); function addPropertyDecorator() { function loopOut(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 i4; 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 (i4 = 0; i4 < len; i4 += 1) { ret[i4] = (endV[i4] - initV[i4]) * repeats + current[i4]; } 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 (i4 = 0; i4 < len; i4 += 1) { ret[i4] = lastValue[i4] + (lastValue[i4] - nextLastValue[i4]) * ((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 loopIn(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 i4; 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 (i4 = 0; i4 < len; i4 += 1) { ret[i4] = current[i4] - (endV[i4] - initV[i4]) * 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 (i4 = 0; i4 < len; i4 += 1) { ret[i4] = firstValue[i4] + (firstValue[i4] - nextFirstValue[i4]) * (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 smooth(width, samples) { if (!this.k) { return this.pv; } width = (width || 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 - width; var endFrame = currentTime + width; var sampleFrequency = samples > 1 ? (endFrame - initFrame) / (samples - 1) : 1; var i4 = 0; var j = 0; var value; if (this.pv.length) { value = createTypedArray("float32", this.pv.length); } else { value = 0; } var sampleValue; while (i4 < samples) { sampleValue = this.getValueAtTime(initFrame + i4 * sampleFrequency); if (this.pv.length) { for (j = 0; j < this.pv.length; j += 1) { value[j] += sampleValue[j]; } } else { value += sampleValue; } i4 += 1; } if (this.pv.length) { for (j = 0; j < this.pv.length; j += 1) { value[j] /= samples; } } else { value /= samples; } return value; } function getTransformValueAtTime(time) { if (!this._transformCachingAtTime) { this._transformCachingAtTime = { v: new Matrix() }; } var matrix6 = this._transformCachingAtTime.v; matrix6.cloneFromProps(this.pre.props); if (this.appliedTransformations < 1) { var anchor = this.a.getValueAtTime(time); matrix6.translate(-anchor[0] * this.a.mult, -anchor[1] * this.a.mult, anchor[2] * this.a.mult); } if (this.appliedTransformations < 2) { var scale5 = this.s.getValueAtTime(time); matrix6.scale(scale5[0] * this.s.mult, scale5[1] * this.s.mult, scale5[2] * this.s.mult); } if (this.sk && this.appliedTransformations < 3) { var skew = this.sk.getValueAtTime(time); var skewAxis = this.sa.getValueAtTime(time); matrix6.skewFromAxis(-skew * this.sk.mult, skewAxis * this.sa.mult); } if (this.r && this.appliedTransformations < 4) { var rotation3 = this.r.getValueAtTime(time); matrix6.rotate(-rotation3 * this.r.mult); } else if (!this.r && this.appliedTransformations < 4) { var rotationZ = this.rz.getValueAtTime(time); var rotationY = this.ry.getValueAtTime(time); var rotationX = this.rx.getValueAtTime(time); var orientation = this.or.getValueAtTime(time); matrix6.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(time); var positionY = this.py.getValueAtTime(time); if (this.data.p.z) { var positionZ = this.pz.getValueAtTime(time); matrix6.translate(positionX * this.px.mult, positionY * this.py.mult, -positionZ * this.pz.mult); } else { matrix6.translate(positionX * this.px.mult, positionY * this.py.mult, 0); } } else { var position2 = this.p.getValueAtTime(time); matrix6.translate(position2[0] * this.p.mult, position2[1] * this.p.mult, -position2[2] * this.p.mult); } return matrix6; } function getTransformStaticValueAtTime() { return this.v.clone(new Matrix()); } var getTransformProperty = TransformPropertyFactory.getTransformProperty; TransformPropertyFactory.getTransformProperty = function(elem, data, container) { var prop = getTransformProperty(elem, data, 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(elem, data, type, mult, container) { var prop = propertyGetProp(elem, data, 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 = loopOut; prop.loopIn = loopIn; prop.smooth = smooth; prop.getVelocityAtTime = expressionHelpers.getVelocityAtTime.bind(prop); prop.getSpeedAtTime = expressionHelpers.getSpeedAtTime.bind(prop); prop.numKeys = data.a === 1 ? data.k.length : 0; prop.propertyIndex = data.ix; var value = 0; if (type !== 0) { value = createTypedArray("float32", data.a === 1 ? data.k[0].s.length : data.k.length); } prop._cachingAtTime = { lastFrame: initialDefaultFrame, lastIndex: 0, value }; expressionHelpers.searchExpressions(elem, data, 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, time) { if (this.k) { this.getValue(); } var shapePath = this.v; if (time !== void 0) { shapePath = this.getValueAtTime(time, 0); } var i4; var len = shapePath._length; var vertices = shapePath[prop]; var points = shapePath.v; var arr = createSizedArray(len); for (i4 = 0; i4 < len; i4 += 1) { if (prop === "i" || prop === "o") { arr[i4] = [vertices[i4][0] - points[i4][0], vertices[i4][1] - points[i4][1]]; } else { arr[i4] = [vertices[i4][0], vertices[i4][1]]; } } return arr; }, points: function(time) { return this.vertices("v", time); }, inTangents: function(time) { return this.vertices("i", time); }, outTangents: function(time) { return this.vertices("o", time); }, isClosed: function() { return this.v.c; }, pointOnPath: function(perc, time) { var shapePath = this.v; if (time !== void 0) { shapePath = this.getValueAtTime(time, 0); } if (!this._segmentsLength) { this._segmentsLength = bez.getSegmentsLength(shapePath); } var segmentsLength = this._segmentsLength; var lengths = segmentsLength.lengths; var lengthPos = segmentsLength.totalLength * perc; var i4 = 0; var len = lengths.length; var accumulatedLength = 0; var pt; while (i4 < len) { if (accumulatedLength + lengths[i4].addedLength > lengthPos) { var initIndex = i4; var endIndex = shapePath.c && i4 === len - 1 ? 0 : i4 + 1; var segmentPerc = (lengthPos - accumulatedLength) / lengths[i4].addedLength; pt = bez.getPointInSegment( shapePath.v[initIndex], shapePath.v[endIndex], shapePath.o[initIndex], shapePath.i[endIndex], segmentPerc, lengths[i4] ); break; } else { accumulatedLength += lengths[i4].addedLength; } i4 += 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, time, vectorType) { if (perc == 1) { perc = this.v.c; } else if (perc == 0) { perc = 0.999; } var pt1 = this.pointOnPath(perc, time); var pt2 = this.pointOnPath(perc + 1e-3, time); 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, time) { return this.vectorOnPath(perc, time, "tangent"); }, normalOnPath: function(perc, time) { return this.vectorOnPath(perc, time, "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(elem, data, type, arr, trims) { var prop = propertyGetShapeProp(elem, data, type, arr, trims); prop.propertyIndex = data.ix; prop.lock = false; if (type === 3) { expressionHelpers.searchExpressions(elem, data.pt, prop); } else if (type === 4) { expressionHelpers.searchExpressions(elem, data.ks, prop); } if (prop.k) { elem.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, text) { var newValue = this.calculateExpression(text); 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(); } setExpressionsPlugin(Expressions); initialize$1(); initialize(); return lottie2; })(); // node_modules/three-stdlib/libs/opentype.js var { parseBuffer } = (() => { 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 i4, sum; for (i4 = 0; i4 < delta; ++i4) { bits2[i4] = 0; } for (i4 = 0; i4 < 30 - delta; ++i4) { bits2[i4 + delta] = i4 / delta | 0; } for (sum = first2, i4 = 0; i4 < 30; ++i4) { base[i4] = sum; sum += 1 << bits2[i4]; } } function tinf_build_fixed_trees(lt, dt) { var i4; for (i4 = 0; i4 < 7; ++i4) { lt.table[i4] = 0; } lt.table[7] = 24; lt.table[8] = 152; lt.table[9] = 112; for (i4 = 0; i4 < 24; ++i4) { lt.trans[i4] = 256 + i4; } for (i4 = 0; i4 < 144; ++i4) { lt.trans[24 + i4] = i4; } for (i4 = 0; i4 < 8; ++i4) { lt.trans[24 + 144 + i4] = 280 + i4; } for (i4 = 0; i4 < 112; ++i4) { lt.trans[24 + 144 + 8 + i4] = 144 + i4; } for (i4 = 0; i4 < 5; ++i4) { dt.table[i4] = 0; } dt.table[5] = 32; for (i4 = 0; i4 < 32; ++i4) { dt.trans[i4] = i4; } } var offs = new Uint16Array(16); function tinf_build_tree(t3, lengths2, off, num) { var i4, sum; for (i4 = 0; i4 < 16; ++i4) { t3.table[i4] = 0; } for (i4 = 0; i4 < num; ++i4) { t3.table[lengths2[off + i4]]++; } t3.table[0] = 0; for (sum = 0, i4 = 0; i4 < 16; ++i4) { offs[i4] = sum; sum += t3.table[i4]; } for (i4 = 0; i4 < num; ++i4) { if (lengths2[off + i4]) { t3.trans[offs[lengths2[off + i4]]++] = i4; } } } function tinf_getbit(d2) { if (!d2.bitcount--) { d2.tag = d2.source[d2.sourceIndex++]; d2.bitcount = 7; } var bit = d2.tag & 1; d2.tag >>>= 1; return bit; } function tinf_read_bits(d2, num, base) { if (!num) { return base; } while (d2.bitcount < 24) { d2.tag |= d2.source[d2.sourceIndex++] << d2.bitcount; d2.bitcount += 8; } var val = d2.tag & 65535 >>> 16 - num; d2.tag >>>= num; d2.bitcount -= num; return val + base; } function tinf_decode_symbol(d2, t3) { while (d2.bitcount < 24) { d2.tag |= d2.source[d2.sourceIndex++] << d2.bitcount; d2.bitcount += 8; } var sum = 0, cur = 0, len = 0; var tag = d2.tag; do { cur = 2 * cur + (tag & 1); tag >>>= 1; ++len; sum += t3.table[len]; cur -= t3.table[len]; } while (cur >= 0); d2.tag = tag; d2.bitcount -= len; return t3.trans[sum + cur]; } function tinf_decode_trees(d2, lt, dt) { var hlit, hdist, hclen; var i4, num, length3; hlit = tinf_read_bits(d2, 5, 257); hdist = tinf_read_bits(d2, 5, 1); hclen = tinf_read_bits(d2, 4, 4); for (i4 = 0; i4 < 19; ++i4) { lengths[i4] = 0; } for (i4 = 0; i4 < hclen; ++i4) { var clen2 = tinf_read_bits(d2, 3, 0); lengths[clcidx[i4]] = clen2; } tinf_build_tree(code_tree, lengths, 0, 19); for (num = 0; num < hlit + hdist; ) { var sym = tinf_decode_symbol(d2, code_tree); switch (sym) { case 16: var prev = lengths[num - 1]; for (length3 = tinf_read_bits(d2, 2, 3); length3; --length3) { lengths[num++] = prev; } break; case 17: for (length3 = tinf_read_bits(d2, 3, 3); length3; --length3) { lengths[num++] = 0; } break; case 18: for (length3 = tinf_read_bits(d2, 7, 11); length3; --length3) { 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(d2, lt, dt) { while (1) { var sym = tinf_decode_symbol(d2, lt); if (sym === 256) { return TINF_OK; } if (sym < 256) { d2.dest[d2.destLen++] = sym; } else { var length3, dist, offs2; var i4; sym -= 257; length3 = tinf_read_bits(d2, length_bits[sym], length_base[sym]); dist = tinf_decode_symbol(d2, dt); offs2 = d2.destLen - tinf_read_bits(d2, dist_bits[dist], dist_base[dist]); for (i4 = offs2; i4 < offs2 + length3; ++i4) { d2.dest[d2.destLen++] = d2.dest[i4]; } } } } function tinf_inflate_uncompressed_block(d2) { var length3, invlength; var i4; while (d2.bitcount > 8) { d2.sourceIndex--; d2.bitcount -= 8; } length3 = d2.source[d2.sourceIndex + 1]; length3 = 256 * length3 + d2.source[d2.sourceIndex]; invlength = d2.source[d2.sourceIndex + 3]; invlength = 256 * invlength + d2.source[d2.sourceIndex + 2]; if (length3 !== (~invlength & 65535)) { return TINF_DATA_ERROR; } d2.sourceIndex += 4; for (i4 = length3; i4; --i4) { d2.dest[d2.destLen++] = d2.source[d2.sourceIndex++]; } d2.bitcount = 0; return TINF_OK; } function tinf_uncompress(source, dest) { var d2 = new Data(source, dest); var bfinal, btype, res; do { bfinal = tinf_getbit(d2); btype = tinf_read_bits(d2, 2, 0); switch (btype) { case 0: res = tinf_inflate_uncompressed_block(d2); break; case 1: res = tinf_inflate_block_data(d2, sltree, sdtree); break; case 2: tinf_decode_trees(d2, d2.ltree, d2.dtree); res = tinf_inflate_block_data(d2, d2.ltree, d2.dtree); break; default: res = TINF_DATA_ERROR; } if (res !== TINF_OK) { throw new Error("Data error"); } } while (!bfinal); if (d2.destLen < d2.dest.length) { if (typeof d2.dest.slice === "function") { return d2.dest.slice(0, d2.destLen); } else { return d2.dest.subarray(0, d2.destLen); } } return d2.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, v13, v22, v32, t3) { return Math.pow(1 - t3, 3) * v0 + 3 * Math.pow(1 - t3, 2) * t3 * v13 + 3 * (1 - t3) * Math.pow(t3, 2) * v22 + Math.pow(t3, 3) * v32; } 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(x, y) { if (typeof x === "number") { if (isNaN(this.x1) || isNaN(this.x2)) { this.x1 = x; this.x2 = x; } if (x < this.x1) { this.x1 = x; } if (x > this.x2) { this.x2 = x; } } 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(x) { this.addPoint(x, null); }; BoundingBox.prototype.addY = function(y) { this.addPoint(null, y); }; BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x, y) { var p0 = [x0, y0]; var p1 = [x1, y1]; var p2 = [x2, y2]; var p3 = [x, y]; this.addPoint(x0, y0); this.addPoint(x, y); for (var i4 = 0; i4 <= 1; i4++) { var b5 = 6 * p0[i4] - 12 * p1[i4] + 6 * p2[i4]; var a6 = -3 * p0[i4] + 9 * p1[i4] - 9 * p2[i4] + 3 * p3[i4]; var c2 = 3 * p1[i4] - 3 * p0[i4]; if (a6 === 0) { if (b5 === 0) { continue; } var t3 = -c2 / b5; if (0 < t3 && t3 < 1) { if (i4 === 0) { this.addX(derive(p0[i4], p1[i4], p2[i4], p3[i4], t3)); } if (i4 === 1) { this.addY(derive(p0[i4], p1[i4], p2[i4], p3[i4], t3)); } } continue; } var b2ac = Math.pow(b5, 2) - 4 * c2 * a6; if (b2ac < 0) { continue; } var t1 = (-b5 + Math.sqrt(b2ac)) / (2 * a6); if (0 < t1 && t1 < 1) { if (i4 === 0) { this.addX(derive(p0[i4], p1[i4], p2[i4], p3[i4], t1)); } if (i4 === 1) { this.addY(derive(p0[i4], p1[i4], p2[i4], p3[i4], t1)); } } var t22 = (-b5 - Math.sqrt(b2ac)) / (2 * a6); if (0 < t22 && t22 < 1) { if (i4 === 0) { this.addX(derive(p0[i4], p1[i4], p2[i4], p3[i4], t22)); } if (i4 === 1) { this.addY(derive(p0[i4], p1[i4], p2[i4], p3[i4], t22)); } } } }; BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x, y) { var cp1x = x0 + 2 / 3 * (x1 - x0); var cp1y = y0 + 2 / 3 * (y1 - y0); var cp2x = cp1x + 1 / 3 * (x - x0); var cp2y = cp1y + 1 / 3 * (y - y0); this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y); }; function Path2() { this.commands = []; this.fill = "black"; this.stroke = null; this.strokeWidth = 1; } Path2.prototype.moveTo = function(x, y) { this.commands.push({ type: "M", x, y }); }; Path2.prototype.lineTo = function(x, y) { this.commands.push({ type: "L", x, y }); }; Path2.prototype.curveTo = Path2.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) { this.commands.push({ type: "C", x1, y1, x2, y2, x, y }); }; Path2.prototype.quadTo = Path2.prototype.quadraticCurveTo = function(x1, y1, x, y) { this.commands.push({ type: "Q", x1, y1, x, 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 i4 = 0; i4 < this.commands.length; i4++) { var cmd = this.commands[i4]; 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 i4 = 0; i4 < this.commands.length; i4 += 1) { var cmd = this.commands[i4]; 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(v5) { if (Math.round(v5) === v5) { return "" + Math.round(v5); } else { return v5.toFixed(decimalPlaces); } } function packValues() { var arguments$1 = arguments; var s2 = ""; for (var i22 = 0; i22 < arguments.length; i22 += 1) { var v5 = arguments$1[i22]; if (v5 >= 0 && i22 > 0) { s2 += " "; } s2 += floatToString(v5); } return s2; } var d2 = ""; for (var i4 = 0; i4 < this.commands.length; i4 += 1) { var cmd = this.commands[i4]; if (cmd.type === "M") { d2 += "M" + packValues(cmd.x, cmd.y); } else if (cmd.type === "L") { d2 += "L" + packValues(cmd.x, cmd.y); } else if (cmd.type === "C") { d2 += "C" + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === "Q") { d2 += "Q" + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === "Z") { d2 += "Z"; } } return d2; }; Path2.prototype.toSVG = function(decimalPlaces) { var svg = '= 0 && v5 <= 255, "Byte value should be between 0 and 255."); return [v5]; }; sizeOf.BYTE = constant(1); encode.CHAR = function(v5) { return [v5.charCodeAt(0)]; }; sizeOf.CHAR = constant(1); encode.CHARARRAY = function(v5) { if (typeof v5 === "undefined") { v5 = ""; console.warn( "Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name." ); } var b5 = []; for (var i4 = 0; i4 < v5.length; i4 += 1) { b5[i4] = v5.charCodeAt(i4); } return b5; }; sizeOf.CHARARRAY = function(v5) { if (typeof v5 === "undefined") { return 0; } return v5.length; }; encode.USHORT = function(v5) { return [v5 >> 8 & 255, v5 & 255]; }; sizeOf.USHORT = constant(2); encode.SHORT = function(v5) { if (v5 >= LIMIT16) { v5 = -(2 * LIMIT16 - v5); } return [v5 >> 8 & 255, v5 & 255]; }; sizeOf.SHORT = constant(2); encode.UINT24 = function(v5) { return [v5 >> 16 & 255, v5 >> 8 & 255, v5 & 255]; }; sizeOf.UINT24 = constant(3); encode.ULONG = function(v5) { return [v5 >> 24 & 255, v5 >> 16 & 255, v5 >> 8 & 255, v5 & 255]; }; sizeOf.ULONG = constant(4); encode.LONG = function(v5) { if (v5 >= LIMIT32) { v5 = -(2 * LIMIT32 - v5); } return [v5 >> 24 & 255, v5 >> 16 & 255, v5 >> 8 & 255, v5 & 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(v5) { return [0, 0, 0, 0, v5 >> 24 & 255, v5 >> 16 & 255, v5 >> 8 & 255, v5 & 255]; }; sizeOf.LONGDATETIME = constant(8); encode.TAG = function(v5) { check.argument(v5.length === 4, "Tag should be exactly 4 ASCII characters."); return [v5.charCodeAt(0), v5.charCodeAt(1), v5.charCodeAt(2), v5.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(v5) { if (v5 >= -107 && v5 <= 107) { return [v5 + 139]; } else if (v5 >= 108 && v5 <= 1131) { v5 = v5 - 108; return [(v5 >> 8) + 247, v5 & 255]; } else if (v5 >= -1131 && v5 <= -108) { v5 = -v5 - 108; return [(v5 >> 8) + 251, v5 & 255]; } else if (v5 >= -32768 && v5 <= 32767) { return encode.NUMBER16(v5); } else { return encode.NUMBER32(v5); } }; sizeOf.NUMBER = function(v5) { return encode.NUMBER(v5).length; }; encode.NUMBER16 = function(v5) { return [28, v5 >> 8 & 255, v5 & 255]; }; sizeOf.NUMBER16 = constant(3); encode.NUMBER32 = function(v5) { return [29, v5 >> 24 & 255, v5 >> 16 & 255, v5 >> 8 & 255, v5 & 255]; }; sizeOf.NUMBER32 = constant(5); encode.REAL = function(v5) { var value = v5.toString(); var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); if (m) { var epsilon2 = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length)); value = (Math.round(v5 * epsilon2) / epsilon2).toString(); } var nibbles = ""; for (var i4 = 0, ii = value.length; i4 < ii; i4 += 1) { var c2 = value[i4]; if (c2 === "e") { nibbles += value[++i4] === "-" ? "c" : "b"; } else if (c2 === ".") { nibbles += "a"; } else if (c2 === "-") { nibbles += "e"; } else { nibbles += c2; } } nibbles += nibbles.length & 1 ? "f" : "ff"; var out7 = [30]; for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) { out7.push(parseInt(nibbles.substr(i$1, 2), 16)); } return out7; }; sizeOf.REAL = function(v5) { return encode.REAL(v5).length; }; encode.NAME = encode.CHARARRAY; sizeOf.NAME = sizeOf.CHARARRAY; encode.STRING = encode.CHARARRAY; sizeOf.STRING = sizeOf.CHARARRAY; decode.UTF8 = function(data, offset, numBytes) { var codePoints = []; var numChars = numBytes; for (var j = 0; j < numChars; j++, offset += 1) { codePoints[j] = data.getUint8(offset); } return String.fromCharCode.apply(null, codePoints); }; decode.UTF16 = function(data, offset, numBytes) { var codePoints = []; var numChars = numBytes / 2; for (var j = 0; j < numChars; j++, offset += 2) { codePoints[j] = data.getUint16(offset); } return String.fromCharCode.apply(null, codePoints); }; encode.UTF16 = function(v5) { var b5 = []; for (var i4 = 0; i4 < v5.length; i4 += 1) { var codepoint = v5.charCodeAt(i4); b5[b5.length] = codepoint >> 8 & 255; b5[b5.length] = codepoint & 255; } return b5; }; sizeOf.UTF16 = function(v5) { return v5.length * 2; }; var eightBitMacEncodings = { // Python: 'mac_croatian' "x-mac-croatian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ", // Python: 'mac_cyrillic' "x-mac-cyrillic": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю", // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT "x-mac-gaelic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ", // Python: 'mac_greek' "x-mac-greek": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­", // Python: 'mac_iceland' "x-mac-icelandic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT "x-mac-inuit": "ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł", // Python: 'mac_latin2' "x-mac-ce": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ", // Python: 'mac_roman' macintosh: "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", // Python: 'mac_romanian' "x-mac-romanian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", // Python: 'mac_turkish' "x-mac-turkish": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ" }; decode.MACSTRING = function(dataView, offset, dataLength, encoding) { var table2 = eightBitMacEncodings[encoding]; if (table2 === void 0) { return void 0; } var result = ""; for (var i4 = 0; i4 < dataLength; i4++) { var c2 = dataView.getUint8(offset + i4); 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 e2 in eightBitMacEncodings) { macEncodingCacheKeys[e2] = new String(e2); } } 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 i4 = 0; i4 < decodingTable.length; i4++) { encodingTable[decodingTable.charCodeAt(i4)] = i4 + 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 i4 = 0; i4 < str.length; i4++) { var c2 = str.charCodeAt(i4); if (c2 >= 128) { c2 = table2[c2]; if (c2 === void 0) { return void 0; } } result[i4] = c2; } return result; }; sizeOf.MACSTRING = function(str, encoding) { var b5 = encode.MACSTRING(str, encoding); if (b5 !== void 0) { return b5.length; } else { return 0; } }; function isByteEncodable(value) { return value >= -128 && value <= 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 value = deltas[pos]; if (!isByteEncodable(value)) { break; } if (value === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) { break; } ++pos; ++runLength; } result.push(runLength - 1); for (var i4 = offset; i4 < pos; ++i4) { result.push(deltas[i4] + 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 value = deltas[pos]; if (value === 0) { break; } if (isByteEncodable(value) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) { break; } ++pos; ++runLength; } result.push(64 | runLength - 1); for (var i4 = offset; i4 < pos; ++i4) { var val = deltas[i4]; result.push(val + 65536 >> 8 & 255, val + 256 & 255); } return pos; } encode.VARDELTAS = function(deltas) { var pos = 0; var result = []; while (pos < deltas.length) { var value = deltas[pos]; if (value === 0) { pos = encodeVarDeltaRunAsZeroes(deltas, pos, result); } else if (value >= -128 && value <= 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 data = []; for (var i4 = 0; i4 < l2.length; i4 += 1) { var v5 = encode.OBJECT(l2[i4]); Array.prototype.push.apply(data, v5); offset += v5.length; offsets.push(offset); } if (data.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, data); }; sizeOf.INDEX = function(v5) { return encode.INDEX(v5).length; }; encode.DICT = function(m) { var d2 = []; var keys = Object.keys(m); var length3 = keys.length; for (var i4 = 0; i4 < length3; i4 += 1) { var k = parseInt(keys[i4], 0); var v5 = m[k]; d2 = d2.concat(encode.OPERAND(v5.value, v5.type)); d2 = d2.concat(encode.OPERATOR(k)); } return d2; }; sizeOf.DICT = function(m) { return encode.DICT(m).length; }; encode.OPERATOR = function(v5) { if (v5 < 1200) { return [v5]; } else { return [12, v5 - 1200]; } }; encode.OPERAND = function(v5, type) { var d2 = []; if (Array.isArray(type)) { for (var i4 = 0; i4 < type.length; i4 += 1) { check.argument(v5.length === type.length, "Not enough arguments given for type" + type); d2 = d2.concat(encode.OPERAND(v5[i4], type[i4])); } } else { if (type === "SID") { d2 = d2.concat(encode.NUMBER(v5)); } else if (type === "offset") { d2 = d2.concat(encode.NUMBER32(v5)); } else if (type === "number") { d2 = d2.concat(encode.NUMBER(v5)); } else if (type === "real") { d2 = d2.concat(encode.REAL(v5)); } else { throw new Error("Unknown operand type " + type); } } return d2; }; 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 d2 = []; var length3 = ops.length; for (var i4 = 0; i4 < length3; i4 += 1) { var op = ops[i4]; d2 = d2.concat(encode[op.type](op.value)); } if (wmm) { wmm.set(ops, d2); } return d2; }; sizeOf.CHARSTRING = function(ops) { return encode.CHARSTRING(ops).length; }; encode.OBJECT = function(v5) { var encodingFunction = encode[v5.type]; check.argument(encodingFunction !== void 0, "No encoding function for type " + v5.type); return encodingFunction(v5.value); }; sizeOf.OBJECT = function(v5) { var sizeOfFunction = sizeOf[v5.type]; check.argument(sizeOfFunction !== void 0, "No sizeOf function for type " + v5.type); return sizeOfFunction(v5.value); }; encode.TABLE = function(table2) { var d2 = []; var length3 = table2.fields.length; var subtables = []; var subtableOffsets = []; for (var i4 = 0; i4 < length3; i4 += 1) { var field = table2.fields[i4]; var encodingFunction = encode[field.type]; check.argument( encodingFunction !== void 0, "No encoding function for field type " + field.type + " (" + field.name + ")" ); var value = table2[field.name]; if (value === void 0) { value = field.value; } var bytes = encodingFunction(value); if (field.type === "TABLE") { subtableOffsets.push(d2.length); d2 = d2.concat([0, 0]); subtables.push(bytes); } else { d2 = d2.concat(bytes); } } for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) { var o2 = subtableOffsets[i$1]; var offset = d2.length; check.argument(offset < 65536, "Table " + table2.tableName + " too big."); d2[o2] = offset >> 8; d2[o2 + 1] = offset & 255; d2 = d2.concat(subtables[i$1]); } return d2; }; sizeOf.TABLE = function(table2) { var numBytes = 0; var length3 = table2.fields.length; for (var i4 = 0; i4 < length3; i4 += 1) { var field = table2.fields[i4]; var sizeOfFunction = sizeOf[field.type]; check.argument( sizeOfFunction !== void 0, "No sizeOf function for field type " + field.type + " (" + field.name + ")" ); var value = table2[field.name]; if (value === void 0) { value = field.value; } numBytes += sizeOfFunction(value); if (field.type === "TABLE") { numBytes += 2; } } return numBytes; }; encode.RECORD = encode.TABLE; sizeOf.RECORD = sizeOf.TABLE; encode.LITERAL = function(v5) { return v5; }; sizeOf.LITERAL = function(v5) { return v5.length; }; function Table(tableName, fields, options) { if (fields.length && (fields[0].name !== "coverageFormat" || fields[0].value === 1)) { for (var i4 = 0; i4 < fields.length; i4 += 1) { var field = fields[i4]; 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 k = optionKeys[i$1]; var v5 = options[k]; if (this[k] !== void 0) { this[k] = v5; } } } } 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 i4 = 0; i4 < list.length; i4++) { fields[i4 + 1] = { name: itemName + i4, type: "USHORT", value: list[i4] }; } 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 i4 = 0; i4 < count; i4++) { fields[i4 + 1] = { name: itemName + i4, type: "TABLE", value: itemCallback(records[i4], i4) }; } return fields; } function recordList(itemName, records, itemCallback) { var count = records.length; var fields = []; fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; for (var i4 = 0; i4 < count; i4++) { fields = fields.concat(itemCallback(records[i4], i4)); } 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, i4) { 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" + i4, type: "TAG", value: scriptRecord.tag }, { name: "script" + i4, 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, i22) { var langSys = langSysRecord.langSys; return [ { name: "langSysTag" + i22, type: "TAG", value: langSysRecord.tag }, { name: "langSys" + i22, 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, i4) { var feature = featureRecord.feature; return [ { name: "featureTag" + i4, type: "TAG", value: featureRecord.tag }, { name: "feature" + i4, 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 i4 = offset; i4 < offset + 4; i4 += 1) { tag += String.fromCharCode(dataView.getInt8(i4)); } return tag; } function getOffset(dataView, offset, offSize) { var v5 = 0; for (var i4 = 0; i4 < offSize; i4 += 1) { v5 <<= 8; v5 += dataView.getUint8(offset + i4); } return v5; } function getBytes(dataView, startOffset, endOffset) { var bytes = []; for (var i4 = startOffset; i4 < endOffset; i4 += 1) { bytes.push(dataView.getUint8(i4)); } return bytes; } function bytesToString(bytes) { var s2 = ""; for (var i4 = 0; i4 < bytes.length; i4 += 1) { s2 += String.fromCharCode(bytes[i4]); } return s2; } var typeOffsets = { byte: 1, uShort: 2, short: 2, uLong: 4, fixed: 4, longDateTime: 8, tag: 4 }; function Parser2(data, offset) { this.data = data; this.offset = offset; this.relativeOffset = 0; } Parser2.prototype.parseByte = function() { var v5 = this.data.getUint8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v5; }; Parser2.prototype.parseChar = function() { var v5 = this.data.getInt8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v5; }; Parser2.prototype.parseCard8 = Parser2.prototype.parseByte; Parser2.prototype.parseUShort = function() { var v5 = this.data.getUint16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v5; }; Parser2.prototype.parseCard16 = Parser2.prototype.parseUShort; Parser2.prototype.parseSID = Parser2.prototype.parseUShort; Parser2.prototype.parseOffset16 = Parser2.prototype.parseUShort; Parser2.prototype.parseShort = function() { var v5 = this.data.getInt16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v5; }; Parser2.prototype.parseF2Dot14 = function() { var v5 = this.data.getInt16(this.offset + this.relativeOffset) / 16384; this.relativeOffset += 2; return v5; }; Parser2.prototype.parseULong = function() { var v5 = getULong(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v5; }; Parser2.prototype.parseOffset32 = Parser2.prototype.parseULong; Parser2.prototype.parseFixed = function() { var v5 = getFixed(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v5; }; Parser2.prototype.parseString = function(length3) { var dataView = this.data; var offset = this.offset + this.relativeOffset; var string = ""; this.relativeOffset += length3; for (var i4 = 0; i4 < length3; i4++) { string += String.fromCharCode(dataView.getUint8(offset + i4)); } return string; }; Parser2.prototype.parseTag = function() { return this.parseString(4); }; Parser2.prototype.parseLongDateTime = function() { var v5 = getULong(this.data, this.offset + this.relativeOffset + 4); v5 -= 2082844800; this.relativeOffset += 8; return v5; }; Parser2.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; }; Parser2.prototype.skip = function(type, amount) { if (amount === void 0) { amount = 1; } this.relativeOffset += typeOffsets[type] * amount; }; Parser2.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 i4 = 0; i4 < count; i4++) { offsets[i4] = dataView.getUint32(offset); offset += 4; } this.relativeOffset += count * 4; return offsets; }; Parser2.prototype.parseOffset16List = Parser2.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 i4 = 0; i4 < count; i4++) { offsets[i4] = dataView.getUint16(offset); offset += 2; } this.relativeOffset += count * 2; return offsets; }; Parser2.prototype.parseShortList = function(count) { var list = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i4 = 0; i4 < count; i4++) { list[i4] = dataView.getInt16(offset); offset += 2; } this.relativeOffset += count * 2; return list; }; Parser2.prototype.parseByteList = function(count) { var list = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i4 = 0; i4 < count; i4++) { list[i4] = dataView.getUint8(offset++); } this.relativeOffset += count; return list; }; Parser2.prototype.parseList = function(count, itemCallback) { if (!itemCallback) { itemCallback = count; count = this.parseUShort(); } var list = new Array(count); for (var i4 = 0; i4 < count; i4++) { list[i4] = itemCallback.call(this); } return list; }; Parser2.prototype.parseList32 = function(count, itemCallback) { if (!itemCallback) { itemCallback = count; count = this.parseULong(); } var list = new Array(count); for (var i4 = 0; i4 < count; i4++) { list[i4] = itemCallback.call(this); } return list; }; Parser2.prototype.parseRecordList = function(count, recordDescription) { if (!recordDescription) { recordDescription = count; count = this.parseUShort(); } var records = new Array(count); var fields = Object.keys(recordDescription); for (var i4 = 0; i4 < count; i4++) { var rec = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; var fieldType = recordDescription[fieldName]; rec[fieldName] = fieldType.call(this); } records[i4] = rec; } return records; }; Parser2.prototype.parseRecordList32 = function(count, recordDescription) { if (!recordDescription) { recordDescription = count; count = this.parseULong(); } var records = new Array(count); var fields = Object.keys(recordDescription); for (var i4 = 0; i4 < count; i4++) { var rec = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; var fieldType = recordDescription[fieldName]; rec[fieldName] = fieldType.call(this); } records[i4] = rec; } return records; }; Parser2.prototype.parseStruct = function(description) { if (typeof description === "function") { return description.call(this); } else { var fields = Object.keys(description); var struct = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; var fieldType = description[fieldName]; struct[fieldName] = fieldType.call(this); } return struct; } }; Parser2.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; }; Parser2.prototype.parseValueRecordList = function() { var valueFormat = this.parseUShort(); var valueCount = this.parseUShort(); var values = new Array(valueCount); for (var i4 = 0; i4 < valueCount; i4++) { values[i4] = this.parseValueRecord(valueFormat); } return values; }; Parser2.prototype.parsePointer = function(description) { var structOffset = this.parseOffset16(); if (structOffset > 0) { return new Parser2(this.data, this.offset + structOffset).parseStruct(description); } return void 0; }; Parser2.prototype.parsePointer32 = function(description) { var structOffset = this.parseOffset32(); if (structOffset > 0) { return new Parser2(this.data, this.offset + structOffset).parseStruct(description); } return void 0; }; Parser2.prototype.parseListOfLists = function(itemCallback) { var offsets = this.parseOffset16List(); var count = offsets.length; var relativeOffset = this.relativeOffset; var list = new Array(count); for (var i4 = 0; i4 < count; i4++) { var start = offsets[i4]; if (start === 0) { list[i4] = void 0; continue; } this.relativeOffset = start; if (itemCallback) { var subOffsets = this.parseOffset16List(); var subList = new Array(subOffsets.length); for (var j = 0; j < subOffsets.length; j++) { this.relativeOffset = start + subOffsets[j]; subList[j] = itemCallback.call(this); } list[i4] = subList; } else { list[i4] = this.parseUShortList(); } } this.relativeOffset = relativeOffset; return list; }; Parser2.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 i4 = 0; i4 < count; i4++) { ranges[i4] = { 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."); }; Parser2.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: Parser2.uShort, end: Parser2.uShort, classId: Parser2.uShort }) }; } throw new Error("0x" + startOffset.toString(16) + ": ClassDef format must be 1 or 2."); }; Parser2.list = function(count, itemCallback) { return function() { return this.parseList(count, itemCallback); }; }; Parser2.list32 = function(count, itemCallback) { return function() { return this.parseList32(count, itemCallback); }; }; Parser2.recordList = function(count, recordDescription) { return function() { return this.parseRecordList(count, recordDescription); }; }; Parser2.recordList32 = function(count, recordDescription) { return function() { return this.parseRecordList32(count, recordDescription); }; }; Parser2.pointer = function(description) { return function() { return this.parsePointer(description); }; }; Parser2.pointer32 = function(description) { return function() { return this.parsePointer32(description); }; }; Parser2.tag = Parser2.prototype.parseTag; Parser2.byte = Parser2.prototype.parseByte; Parser2.uShort = Parser2.offset16 = Parser2.prototype.parseUShort; Parser2.uShortList = Parser2.prototype.parseUShortList; Parser2.uLong = Parser2.offset32 = Parser2.prototype.parseULong; Parser2.uLongList = Parser2.prototype.parseULongList; Parser2.struct = Parser2.prototype.parseStruct; Parser2.coverage = Parser2.prototype.parseCoverage; Parser2.classDef = Parser2.prototype.parseClassDef; var langSysTable = { reserved: Parser2.uShort, reqFeatureIndex: Parser2.uShort, featureIndexes: Parser2.uShortList }; Parser2.prototype.parseScriptList = function() { return this.parsePointer( Parser2.recordList({ tag: Parser2.tag, script: Parser2.pointer({ defaultLangSys: Parser2.pointer(langSysTable), langSysRecords: Parser2.recordList({ tag: Parser2.tag, langSys: Parser2.pointer(langSysTable) }) }) }) ) || []; }; Parser2.prototype.parseFeatureList = function() { return this.parsePointer( Parser2.recordList({ tag: Parser2.tag, feature: Parser2.pointer({ featureParams: Parser2.offset16, lookupListIndexes: Parser2.uShortList }) }) ) || []; }; Parser2.prototype.parseLookupList = function(lookupTableParsers) { return this.parsePointer( Parser2.list( Parser2.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(Parser2.pointer(lookupTableParsers[lookupType])), markFilteringSet: useMarkFilteringSet ? this.parseUShort() : void 0 }; }) ) ) || []; }; Parser2.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: Parser2.offset32, featureTableSubstitutionOffset: Parser2.offset32 }); return featureVariations; }) || []; }; var parse2 = { getByte, getCard8: getByte, getUShort, getCard16: getUShort, getShort, getULong, getFixed, getTag, getOffset, getBytes, bytesToString, Parser: Parser2 }; function parseCmapTableFormat12(cmap2, p2) { p2.parseUShort(); cmap2.length = p2.parseULong(); cmap2.language = p2.parseULong(); var groupCount; cmap2.groupCount = groupCount = p2.parseULong(); cmap2.glyphIndexMap = {}; for (var i4 = 0; i4 < groupCount; i4 += 1) { var startCharCode = p2.parseULong(); var endCharCode = p2.parseULong(); var startGlyphId = p2.parseULong(); for (var c2 = startCharCode; c2 <= endCharCode; c2 += 1) { cmap2.glyphIndexMap[c2] = startGlyphId; startGlyphId++; } } } function parseCmapTableFormat4(cmap2, p2, data, start, offset) { cmap2.length = p2.parseUShort(); cmap2.language = p2.parseUShort(); var segCount; cmap2.segCount = segCount = p2.parseUShort() >> 1; p2.skip("uShort", 3); cmap2.glyphIndexMap = {}; var endCountParser = new parse2.Parser(data, start + offset + 14); var startCountParser = new parse2.Parser(data, start + offset + 16 + segCount * 2); var idDeltaParser = new parse2.Parser(data, start + offset + 16 + segCount * 4); var idRangeOffsetParser = new parse2.Parser(data, start + offset + 16 + segCount * 6); var glyphIndexOffset = start + offset + 16 + segCount * 8; for (var i4 = 0; i4 < segCount - 1; i4 += 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 = parse2.getUShort(data, glyphIndexOffset); if (glyphIndex !== 0) { glyphIndex = glyphIndex + idDelta & 65535; } } else { glyphIndex = c2 + idDelta & 65535; } cmap2.glyphIndexMap[c2] = glyphIndex; } } } function parseCmapTable(data, start) { var cmap2 = {}; cmap2.version = parse2.getUShort(data, start); check.argument(cmap2.version === 0, "cmap table version should be 0."); cmap2.numTables = parse2.getUShort(data, start + 2); var offset = -1; for (var i4 = cmap2.numTables - 1; i4 >= 0; i4 -= 1) { var platformId = parse2.getUShort(data, start + 4 + i4 * 8); var encodingId = parse2.getUShort(data, start + 4 + i4 * 8 + 2); if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10) || platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4)) { offset = parse2.getULong(data, start + 4 + i4 * 8 + 4); break; } } if (offset === -1) { throw new Error("No valid cmap sub-tables found."); } var p2 = new parse2.Parser(data, start + offset); cmap2.format = p2.parseUShort(); if (cmap2.format === 12) { parseCmapTableFormat12(cmap2, p2); } else if (cmap2.format === 4) { parseCmapTableFormat4(cmap2, p2, data, 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 i4; for (i4 = glyphs.length - 1; i4 > 0; i4 -= 1) { var g = glyphs.get(i4); if (g.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 (i4 = 0; i4 < glyphs.length; i4 += 1) { var glyph = glyphs.get(i4); for (var j = 0; j < glyph.unicodes.length; j += 1) { addSegment(t3, glyph.unicodes[j], i4); } t3.segments = t3.segments.sort(function(a6, b5) { return a6.start - b5.start; }); } addTerminatorSegment(t3); var segCount = t3.segments.length; var segCountToRemove = 0; var endCounts = []; var startCounts = []; var idDeltas = []; var idRangeOffsets = []; var glyphIds = []; var cmap12Groups = []; for (i4 = 0; i4 < segCount; i4 += 1) { var segment = t3.segments[i4]; if (segment.end <= 65535 && segment.start <= 65535) { endCounts = endCounts.concat({ name: "end_" + i4, type: "USHORT", value: segment.end }); startCounts = startCounts.concat({ name: "start_" + i4, type: "USHORT", value: segment.start }); idDeltas = idDeltas.concat({ name: "idDelta_" + i4, type: "SHORT", value: segment.delta }); idRangeOffsets = idRangeOffsets.concat({ name: "idRangeOffset_" + i4, type: "USHORT", value: segment.offset }); if (segment.glyphId !== void 0) { glyphIds = glyphIds.concat({ name: "glyph_" + i4, type: "USHORT", value: segment.glyphId }); } } else { segCountToRemove += 1; } if (!isPlan0Only && segment.glyphIndex !== void 0) { cmap12Groups = cmap12Groups.concat({ name: "cmap12Start_" + i4, type: "ULONG", value: segment.start }); cmap12Groups = cmap12Groups.concat({ name: "cmap12End_" + i4, type: "ULONG", value: segment.end }); cmap12Groups = cmap12Groups.concat({ name: "cmap12Glyph_" + i4, 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 i4 = 0; i4 < glyphs.length; i4 += 1) { var glyph = glyphs.get(i4); for (var j = 0; j < glyph.unicodes.length; j += 1) { if (glyph.unicodes[j] === code) { return i4; } } } } 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(s2) { var code = s2.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 i4 = 0; i4 < post2.numberOfGlyphs; i4++) { if (post2.glyphNameIndex[i4] < standardNames.length) { this.names[i4] = standardNames[post2.glyphNameIndex[i4]]; } else { this.names[i4] = post2.names[post2.glyphNameIndex[i4] - 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(name) { return this.names.indexOf(name); }; 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 i4 = 0; i4 < charCodes.length; i4 += 1) { var c2 = charCodes[i4]; 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 i4 = 0; i4 < charCodes.length; i4 += 1) { var c2 = charCodes[i4]; 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(p2) { _path = p2; } }; } 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(x, y, fontSize, options, font) { x = x !== void 0 ? x : 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); x = Math.round(x); y = Math.round(y); xScale = yScale = 1; } else { commands = this.path.commands; var scale5 = 1 / (this.path.unitsPerEm || 1e3) * fontSize; if (xScale === void 0) { xScale = scale5; } if (yScale === void 0) { yScale = scale5; } } var p2 = new Path2(); for (var i4 = 0; i4 < commands.length; i4 += 1) { var cmd = commands[i4]; if (cmd.type === "M") { p2.moveTo(x + cmd.x * xScale, y + -cmd.y * yScale); } else if (cmd.type === "L") { p2.lineTo(x + cmd.x * xScale, y + -cmd.y * yScale); } else if (cmd.type === "Q") { p2.quadraticCurveTo(x + cmd.x1 * xScale, y + -cmd.y1 * yScale, x + cmd.x * xScale, y + -cmd.y * yScale); } else if (cmd.type === "C") { p2.curveTo( x + cmd.x1 * xScale, y + -cmd.y1 * yScale, x + cmd.x2 * xScale, y + -cmd.y2 * yScale, x + cmd.x * xScale, y + -cmd.y * yScale ); } else if (cmd.type === "Z") { p2.closePath(); } } return p2; }; Glyph.prototype.getContours = function() { if (this.points === void 0) { return []; } var contours = []; var currentContour = []; for (var i4 = 0; i4 < this.points.length; i4 += 1) { var pt = this.points[i4]; 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 i4 = 0; i4 < commands.length; i4 += 1) { var cmd = commands[i4]; 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, x, y, fontSize, options) { this.getPath(x, y, fontSize, options).draw(ctx); }; Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) { function drawCircles(l2, x2, y2, scale22) { ctx.beginPath(); for (var j = 0; j < l2.length; j += 1) { ctx.moveTo(x2 + l2[j].x * scale22, y2 + l2[j].y * scale22); ctx.arc(x2 + l2[j].x * scale22, y2 + l2[j].y * scale22, 2, 0, Math.PI * 2, false); } ctx.closePath(); ctx.fill(); } x = x !== void 0 ? x : 0; y = y !== void 0 ? y : 0; fontSize = fontSize !== void 0 ? fontSize : 24; var scale5 = 1 / this.path.unitsPerEm * fontSize; var blueCircles = []; var redCircles = []; var path = this.path; for (var i4 = 0; i4 < path.commands.length; i4 += 1) { var cmd = path.commands[i4]; 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, x, y, scale5); ctx.fillStyle = "red"; drawCircles(redCircles, x, y, scale5); }; Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) { var scale5; x = x !== void 0 ? x : 0; y = y !== void 0 ? y : 0; fontSize = fontSize !== void 0 ? fontSize : 24; scale5 = 1 / this.path.unitsPerEm * fontSize; ctx.lineWidth = 1; ctx.strokeStyle = "black"; draw.line(ctx, x, -1e4, x, 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, x + xMin * scale5, -1e4, x + xMin * scale5, 1e4); draw.line(ctx, x + xMax * scale5, -1e4, x + xMax * scale5, 1e4); draw.line(ctx, -1e4, y + -yMin * scale5, 1e4, y + -yMin * scale5); draw.line(ctx, -1e4, y + -yMax * scale5, 1e4, y + -yMax * scale5); ctx.strokeStyle = "green"; draw.line(ctx, x + advanceWidth * scale5, -1e4, x + advanceWidth * scale5, 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 i4 = 0; i4 < glyphs.length; i4++) { var glyph = glyphs[i4]; glyph.path.unitsPerEm = font.unitsPerEm; this.glyphs[i4] = 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 j = 0; j < unicodeObj.unicodes.length; j++) { glyph.addUnicode(unicodeObj.unicodes[j]); } } 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, loader2) { this.glyphs[index2] = loader2; this.length++; }; function glyphLoader(font, index2) { return new Glyph({ index: index2, font }); } function ttfGlyphLoader(font, index2, parseGlyph2, data, position2, buildPath2) { return function() { var glyph = new Glyph({ index: index2, font }); glyph.path = function() { parseGlyph2(glyph, data, 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(a6, b5) { if (a6 === b5) { return true; } else if (Array.isArray(a6) && Array.isArray(b5)) { if (a6.length !== b5.length) { return false; } for (var i4 = 0; i4 < a6.length; i4 += 1) { if (!equals(a6[i4], b5[i4])) { 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(data, start, conversionFn) { var offsets = []; var objects = []; var count = parse2.getCard16(data, start); var objectOffset; var endOffset; if (count !== 0) { var offsetSize = parse2.getByte(data, start + 2); objectOffset = start + (count + 1) * offsetSize + 2; var pos = start + 3; for (var i4 = 0; i4 < count + 1; i4 += 1) { offsets.push(parse2.getOffset(data, 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 value = parse2.getBytes(data, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]); if (conversionFn) { value = conversionFn(value); } objects.push(value); } return { objects, startOffset: start, endOffset }; } function parseCFFIndexLowMemory(data, start) { var offsets = []; var count = parse2.getCard16(data, start); var objectOffset; var endOffset; if (count !== 0) { var offsetSize = parse2.getByte(data, start + 2); objectOffset = start + (count + 1) * offsetSize + 2; var pos = start + 3; for (var i4 = 0; i4 < count + 1; i4 += 1) { offsets.push(parse2.getOffset(data, pos, offsetSize)); pos += offsetSize; } endOffset = objectOffset + offsets[count]; } else { endOffset = start + 2; } return { offsets, startOffset: start, endOffset }; } function getCffIndexObject(i4, offsets, data, start, conversionFn) { var count = parse2.getCard16(data, start); var objectOffset = 0; if (count !== 0) { var offsetSize = parse2.getByte(data, start + 2); objectOffset = start + (count + 1) * offsetSize + 2; } var value = parse2.getBytes(data, objectOffset + offsets[i4], objectOffset + offsets[i4 + 1]); if (conversionFn) { value = conversionFn(value); } return value; } function parseFloatOperand(parser) { var s2 = ""; var eof = 15; var lookup = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "E", "E-", null, "-"]; while (true) { var b5 = parser.parseByte(); var n1 = b5 >> 4; var n2 = b5 & 15; if (n1 === eof) { break; } s2 += lookup[n1]; if (n2 === eof) { break; } s2 += lookup[n2]; } return parseFloat(s2); } function parseOperand(parser, b0) { var b1; var b23; var b32; var b43; if (b0 === 28) { b1 = parser.parseByte(); b23 = parser.parseByte(); return b1 << 8 | b23; } if (b0 === 29) { b1 = parser.parseByte(); b23 = parser.parseByte(); b32 = parser.parseByte(); b43 = parser.parseByte(); return b1 << 24 | b23 << 16 | b32 << 8 | b43; } 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 o2 = {}; for (var i4 = 0; i4 < entries.length; i4 += 1) { var key = entries[i4][0]; var values = entries[i4][1]; var value = void 0; if (values.length === 1) { value = values[0]; } else { value = values; } if (o2.hasOwnProperty(key) && !isNaN(o2[key])) { throw new Error("Object " + o2 + " already has key " + key); } o2[key] = value; } return o2; } function parseCFFDict(data, start, size2) { start = start !== void 0 ? start : 0; var parser = new parse2.Parser(data, start); var entries = []; var operands = []; size2 = size2 !== void 0 ? size2 : data.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 value; for (var i4 = 0; i4 < meta2.length; i4 += 1) { var m = meta2[i4]; if (Array.isArray(m.type)) { var values = []; values.length = m.type.length; for (var j = 0; j < m.type.length; j++) { value = dict[m.op] !== void 0 ? dict[m.op][j] : void 0; if (value === void 0) { value = m.value !== void 0 && m.value[j] !== void 0 ? m.value[j] : null; } if (m.type[j] === "SID") { value = getCFFString(strings, value); } values[j] = value; } newDict[m.name] = values; } else { value = dict[m.op]; if (value === void 0) { value = m.value !== void 0 ? m.value : null; } if (m.type === "SID") { value = getCFFString(strings, value); } newDict[m.name] = value; } } return newDict; } function parseCFFHeader(data, start) { var header = {}; header.formatMajor = parse2.getCard8(data, start); header.formatMinor = parse2.getCard8(data, start + 1); header.size = parse2.getCard8(data, start + 2); header.offsetSize = parse2.getCard8(data, 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(data, strings) { var dict = parseCFFDict(data, 0, data.byteLength); return interpretDict(dict, TOP_DICT_META, strings); } function parseCFFPrivateDict(data, start, size2, strings) { var dict = parseCFFDict(data, start, size2); return interpretDict(dict, PRIVATE_DICT_META, strings); } function gatherCFFTopDicts(data, 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(data, privateOffset + start, privateSize, strings); topDict._defaultWidthX = privateDict.defaultWidthX; topDict._nominalWidthX = privateDict.nominalWidthX; if (privateDict.subrs !== 0) { var subrOffset = privateOffset + privateDict.subrs; var subrIndex = parseCFFIndex(data, subrOffset + start); topDict._subrs = subrIndex.objects; topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs); } topDict._privateDict = privateDict; } topDictArray.push(topDict); } return topDictArray; } function parseCFFCharset(data, start, nGlyphs, strings) { var sid; var count; var parser = new parse2.Parser(data, start); nGlyphs -= 1; var charset = [".notdef"]; var format = parser.parseCard8(); if (format === 0) { for (var i4 = 0; i4 < nGlyphs; i4 += 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(data, start, charset) { var code; var enc = {}; var parser = new parse2.Parser(data, start); var format = parser.parseCard8(); if (format === 0) { var nCodes = parser.parseCard8(); for (var i4 = 0; i4 < nCodes; i4 += 1) { code = parser.parseCard8(); enc[code] = i4; } } 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 j = first2; j <= first2 + nLeft; j += 1) { enc[j] = 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 p2 = new Path2(); var stack = []; var nStems = 0; var haveWidth = false; var open = false; var x = 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 width = defaultWidthX; function newContour(x2, y2) { if (open) { p2.closePath(); } p2.moveTo(x2, y2); open = true; } function parseStems() { var hasWidthArg; hasWidthArg = stack.length % 2 !== 0; if (hasWidthArg && !haveWidth) { width = stack.shift() + nominalWidthX; } nStems += stack.length >> 1; stack.length = 0; haveWidth = true; } function parse22(code2) { var b1; var b23; var b32; var b43; var codeIndex; var subrCode; var jpx; var jpy; var c3x; var c3y; var c4x; var c4y; var i4 = 0; while (i4 < code2.length) { var v5 = code2[i4]; i4 += 1; switch (v5) { case 1: parseStems(); break; case 3: parseStems(); break; case 4: if (stack.length > 1 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } y += stack.pop(); newContour(x, y); break; case 5: while (stack.length > 0) { x += stack.shift(); y += stack.shift(); p2.lineTo(x, y); } break; case 6: while (stack.length > 0) { x += stack.shift(); p2.lineTo(x, y); if (stack.length === 0) { break; } y += stack.shift(); p2.lineTo(x, y); } break; case 7: while (stack.length > 0) { y += stack.shift(); p2.lineTo(x, y); if (stack.length === 0) { break; } x += stack.shift(); p2.lineTo(x, y); } break; case 8: while (stack.length > 0) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p2.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 10: codeIndex = stack.pop() + subrsBias; subrCode = subrs[codeIndex]; if (subrCode) { parse22(subrCode); } break; case 11: return; case 12: v5 = code2[i4]; i4 += 1; switch (v5) { case 35: c1x = x + 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(); x = c4x + stack.shift(); y = c4y + stack.shift(); stack.shift(); p2.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p2.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 34: c1x = x + 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; x = c4x + stack.shift(); p2.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p2.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 36: c1x = x + 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(); x = c4x + stack.shift(); p2.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p2.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 37: c1x = x + 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 - x) > Math.abs(c4y - y)) { x = c4x + stack.shift(); } else { y = c4y + stack.shift(); } p2.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p2.curveTo(c3x, c3y, c4x, c4y, x, y); break; default: console.log("Glyph " + glyph.index + ": unknown operator 1200" + v5); stack.length = 0; } break; case 14: if (stack.length > 0 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } if (open) { p2.closePath(); open = false; } break; case 18: parseStems(); break; case 19: case 20: parseStems(); i4 += nStems + 7 >> 3; break; case 21: if (stack.length > 2 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } y += stack.pop(); x += stack.pop(); newContour(x, y); break; case 22: if (stack.length > 1 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } x += stack.pop(); newContour(x, y); break; case 23: parseStems(); break; case 24: while (stack.length > 2) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p2.curveTo(c1x, c1y, c2x, c2y, x, y); } x += stack.shift(); y += stack.shift(); p2.lineTo(x, y); break; case 25: while (stack.length > 6) { x += stack.shift(); y += stack.shift(); p2.lineTo(x, y); } c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p2.curveTo(c1x, c1y, c2x, c2y, x, y); break; case 26: if (stack.length % 2) { x += stack.shift(); } while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x; y = c2y + stack.shift(); p2.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 27: if (stack.length % 2) { y += stack.shift(); } while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y; p2.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 28: b1 = code2[i4]; b23 = code2[i4 + 1]; stack.push((b1 << 24 | b23 << 16) >> 16); i4 += 2; break; case 29: codeIndex = stack.pop() + font.gsubrsBias; subrCode = font.gsubrs[codeIndex]; if (subrCode) { parse22(subrCode); } break; case 30: while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); p2.curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); p2.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 31: while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); p2.curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); p2.curveTo(c1x, c1y, c2x, c2y, x, y); } break; default: if (v5 < 32) { console.log("Glyph " + glyph.index + ": unknown operator " + v5); } else if (v5 < 247) { stack.push(v5 - 139); } else if (v5 < 251) { b1 = code2[i4]; i4 += 1; stack.push((v5 - 247) * 256 + b1 + 108); } else if (v5 < 255) { b1 = code2[i4]; i4 += 1; stack.push(-(v5 - 251) * 256 - b1 - 108); } else { b1 = code2[i4]; b23 = code2[i4 + 1]; b32 = code2[i4 + 2]; b43 = code2[i4 + 3]; i4 += 4; stack.push((b1 << 24 | b23 << 16 | b32 << 8 | b43) / 65536); } } } } parse22(code); glyph.advanceWidth = width; return p2; } function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) { var fdSelect = []; var fdIndex; var parser = new parse2.Parser(data, 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(data, start, font, opt) { font.tables.cff = {}; var header = parseCFFHeader(data, start); var nameIndex = parseCFFIndex(data, header.endOffset, parse2.bytesToString); var topDictIndex = parseCFFIndex(data, nameIndex.endOffset); var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse2.bytesToString); var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset); font.gsubrs = globalSubrIndex.objects; font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); var topDictArray = gatherCFFTopDicts(data, 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(data, fdArrayOffset); var fdArray = gatherCFFTopDicts(data, start, fdArrayIndex.objects, stringIndex.objects); topDict._fdArray = fdArray; fdSelectOffset += start; topDict._fdSelect = parseCFFFDSelect(data, fdSelectOffset, font.numGlyphs, fdArray.length); } var privateDictOffset = start + topDict.private[1]; var privateDict = parseCFFPrivateDict(data, 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(data, subrOffset); font.subrs = subrIndex.objects; font.subrsBias = calcCFFSubroutineBias(font.subrs); } else { font.subrs = []; font.subrsBias = 0; } var charStringsIndex; if (opt.lowMemory) { charStringsIndex = parseCFFIndexLowMemory(data, start + topDict.charStrings); font.nGlyphs = charStringsIndex.offsets.length; } else { charStringsIndex = parseCFFIndex(data, start + topDict.charStrings); font.nGlyphs = charStringsIndex.objects.length; } var charset = parseCFFCharset(data, 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(data, start + topDict.encoding, charset); } font.encoding = font.encoding || font.cffEncoding; font.glyphs = new glyphset.GlyphSet(font); if (opt.lowMemory) { font._push = function(i22) { var charString2 = getCffIndexObject(i22, charStringsIndex.offsets, data, start + topDict.charStrings); font.glyphs.push(i22, glyphset.cffGlyphLoader(font, i22, parseCFFCharstring, charString2)); }; } else { for (var i4 = 0; i4 < font.nGlyphs; i4 += 1) { var charString = charStringsIndex.objects[i4]; font.glyphs.push(i4, glyphset.cffGlyphLoader(font, i4, parseCFFCharstring, charString)); } } } function encodeString(s2, strings) { var sid; var i4 = cffStandardStrings.indexOf(s2); if (i4 >= 0) { sid = i4; } i4 = strings.indexOf(s2); if (i4 >= 0) { sid = i4 + cffStandardStrings.length; } else { sid = cffStandardStrings.length + strings.length; strings.push(s2); } 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 i4 = 0; i4 < fontNames.length; i4 += 1) { t3.names.push({ name: "name_" + i4, type: "NAME", value: fontNames[i4] }); } return t3; } function makeDict(meta2, attrs, strings) { var m = {}; for (var i4 = 0; i4 < meta2.length; i4 += 1) { var entry = meta2[i4]; var value = attrs[entry.name]; if (value !== void 0 && !equals(value, entry.value)) { if (entry.type === "SID") { value = encodeString(value, strings); } m[entry.op] = { name: entry.name, type: entry.type, value }; } } 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 i4 = 0; i4 < strings.length; i4 += 1) { t3.strings.push({ name: "string_" + i4, type: "STRING", value: strings[i4] }); } 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 i4 = 0; i4 < glyphNames.length; i4 += 1) { var glyphName = glyphNames[i4]; var glyphSID = encodeString(glyphName, strings); t3.fields.push({ name: "glyph_" + i4, 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 x = 0; var y = 0; for (var i4 = 0; i4 < path.commands.length; i4 += 1) { var dx = void 0; var dy = void 0; var cmd = path.commands[i4]; 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 * x + _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 - x); 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 }); x = Math.round(cmd.x); y = Math.round(cmd.y); } else if (cmd.type === "L") { dx = Math.round(cmd.x - x); 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 }); x = Math.round(cmd.x); y = Math.round(cmd.y); } else if (cmd.type === "C") { var dx1 = Math.round(cmd.x1 - x); 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 }); x = 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 i4 = 0; i4 < glyphs.length; i4 += 1) { var glyph = glyphs.get(i4); 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 i4 = 1; i4 < glyphs.length; i4 += 1) { glyph = glyphs.get(i4); 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(data, start) { var head2 = {}; var p2 = new parse2.Parser(data, start); head2.version = p2.parseVersion(); head2.fontRevision = Math.round(p2.parseFixed() * 1e3) / 1e3; head2.checkSumAdjustment = p2.parseULong(); head2.magicNumber = p2.parseULong(); check.argument(head2.magicNumber === 1594834165, "Font header has wrong magic number."); head2.flags = p2.parseUShort(); head2.unitsPerEm = p2.parseUShort(); head2.created = p2.parseLongDateTime(); head2.modified = p2.parseLongDateTime(); head2.xMin = p2.parseShort(); head2.yMin = p2.parseShort(); head2.xMax = p2.parseShort(); head2.yMax = p2.parseShort(); head2.macStyle = p2.parseUShort(); head2.lowestRecPPEM = p2.parseUShort(); head2.fontDirectionHint = p2.parseShort(); head2.indexToLocFormat = p2.parseShort(); head2.glyphDataFormat = p2.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(data, start) { var hhea2 = {}; var p2 = new parse2.Parser(data, start); hhea2.version = p2.parseVersion(); hhea2.ascender = p2.parseShort(); hhea2.descender = p2.parseShort(); hhea2.lineGap = p2.parseShort(); hhea2.advanceWidthMax = p2.parseUShort(); hhea2.minLeftSideBearing = p2.parseShort(); hhea2.minRightSideBearing = p2.parseShort(); hhea2.xMaxExtent = p2.parseShort(); hhea2.caretSlopeRise = p2.parseShort(); hhea2.caretSlopeRun = p2.parseShort(); hhea2.caretOffset = p2.parseShort(); p2.relativeOffset += 8; hhea2.metricDataFormat = p2.parseShort(); hhea2.numberOfHMetrics = p2.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(data, start, numMetrics, numGlyphs, glyphs) { var advanceWidth; var leftSideBearing; var p2 = new parse2.Parser(data, start); for (var i4 = 0; i4 < numGlyphs; i4 += 1) { if (i4 < numMetrics) { advanceWidth = p2.parseUShort(); leftSideBearing = p2.parseShort(); } var glyph = glyphs.get(i4); glyph.advanceWidth = advanceWidth; glyph.leftSideBearing = leftSideBearing; } } function parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs) { font._hmtxTableData = {}; var advanceWidth; var leftSideBearing; var p2 = new parse2.Parser(data, start); for (var i4 = 0; i4 < numGlyphs; i4 += 1) { if (i4 < numMetrics) { advanceWidth = p2.parseUShort(); leftSideBearing = p2.parseShort(); } font._hmtxTableData[i4] = { advanceWidth, leftSideBearing }; } } function parseHmtxTable(font, data, start, numMetrics, numGlyphs, glyphs, opt) { if (opt.lowMemory) { parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs); } else { parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs); } } function makeHmtxTable(glyphs) { var t3 = new table.Table("hmtx", []); for (var i4 = 0; i4 < glyphs.length; i4 += 1) { var glyph = glyphs.get(i4); var advanceWidth = glyph.advanceWidth || 0; var leftSideBearing = glyph.leftSideBearing || 0; t3.fields.push({ name: "advanceWidth_" + i4, type: "USHORT", value: advanceWidth }); t3.fields.push({ name: "leftSideBearing_" + i4, 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 i4 = 0; i4 < tags.length; ++i4) { var pos = stringPool.indexOf(tags[i4]); if (pos < 0) { pos = stringPool.length; stringPool += tags[i4]; } result.fields.push({ name: "offset " + i4, type: "USHORT", value: stringPoolOffset + pos }); result.fields.push({ name: "length " + i4, type: "USHORT", value: tags[i4].length }); } result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool }); return result; } function parseLtagTable(data, start) { var p2 = new parse2.Parser(data, start); var tableVersion = p2.parseULong(); check.argument(tableVersion === 1, "Unsupported ltag table version."); p2.skip("uLong", 1); var numTags = p2.parseULong(); var tags = []; for (var i4 = 0; i4 < numTags; i4++) { var tag = ""; var offset = start + p2.parseUShort(); var length3 = p2.parseUShort(); for (var j = offset; j < offset + length3; ++j) { tag += String.fromCharCode(data.getInt8(j)); } tags.push(tag); } return tags; } var ltag = { make: makeLtagTable, parse: parseLtagTable }; function parseMaxpTable(data, start) { var maxp2 = {}; var p2 = new parse2.Parser(data, start); maxp2.version = p2.parseVersion(); maxp2.numGlyphs = p2.parseUShort(); if (maxp2.version === 1) { maxp2.maxPoints = p2.parseUShort(); maxp2.maxContours = p2.parseUShort(); maxp2.maxCompositePoints = p2.parseUShort(); maxp2.maxCompositeContours = p2.parseUShort(); maxp2.maxZones = p2.parseUShort(); maxp2.maxTwilightPoints = p2.parseUShort(); maxp2.maxStorage = p2.parseUShort(); maxp2.maxFunctionDefs = p2.parseUShort(); maxp2.maxInstructionDefs = p2.parseUShort(); maxp2.maxStackElements = p2.parseUShort(); maxp2.maxSizeOfInstructions = p2.parseUShort(); maxp2.maxComponentElements = p2.parseUShort(); maxp2.maxComponentDepth = p2.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(data, start, ltag2) { var name = {}; var p2 = new parse2.Parser(data, start); var format = p2.parseUShort(); var count = p2.parseUShort(); var stringOffset = p2.offset + p2.parseUShort(); for (var i4 = 0; i4 < count; i4++) { var platformID = p2.parseUShort(); var encodingID = p2.parseUShort(); var languageID = p2.parseUShort(); var nameID = p2.parseUShort(); var property = nameTableNames[nameID] || nameID; var byteLength = p2.parseUShort(); var offset = p2.parseUShort(); var language = getLanguageCode(platformID, languageID, ltag2); var encoding = getEncoding(platformID, encodingID, languageID); if (encoding !== void 0 && language !== void 0) { var text = void 0; if (encoding === utf16) { text = decode.UTF16(data, stringOffset + offset, byteLength); } else { text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding); } if (text) { var translations = name[property]; if (translations === void 0) { translations = name[property] = {}; } translations[language] = text; } } } if (format === 1) { p2.parseUShort(); } return name; } function reverseDict(dict) { var result = {}; for (var key in dict) { result[dict[key]] = parseInt(key); } return result; } function makeNameRecord(platformID, encodingID, languageID, nameID, length3, 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: length3 }, { 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 k = 0; k < needleLength; k++) { if (haystack[pos + k] !== needle[k]) { continue loop; } } return pos; } } return -1; } function addStringToPool(s2, pool) { var offset = findSubArray(s2, pool); if (offset < 0) { offset = pool.length; var i4 = 0; var len = s2.length; for (; i4 < len; ++i4) { pool.push(s2[i4]); } } return offset; } function makeNameTable(names, ltag2) { var nameID; var nameIDs = []; var namesWithNumericKeys = {}; var nameTableIds = reverseDict(nameTableNames); for (var key in names) { var id = nameTableIds[key]; if (id === void 0) { id = key; } nameID = parseInt(id); if (isNaN(nameID)) { throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.'); } namesWithNumericKeys[nameID] = names[key]; nameIDs.push(nameID); } var macLanguageIds = reverseDict(macLanguages); var windowsLanguageIds = reverseDict(windowsLanguages); var nameRecords = []; var stringPool = []; for (var i4 = 0; i4 < nameIDs.length; i4++) { nameID = nameIDs[i4]; var translations = namesWithNumericKeys[nameID]; for (var lang in translations) { var text = translations[lang]; var macPlatform = 1; var macLanguage = macLanguageIds[lang]; var macScript = macLanguageToScript[macLanguage]; var macEncoding = getEncoding(macPlatform, macScript, macLanguage); var macName = encode.MACSTRING(text, 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(text); } 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(text); var winNameOffset = addStringToPool(winName, stringPool); nameRecords.push(makeNameRecord(3, 1, winLanguage, nameID, winName.length, winNameOffset)); } } } nameRecords.sort(function(a6, b5) { return a6.platformID - b5.platformID || a6.encodingID - b5.encodingID || a6.languageID - b5.languageID || a6.nameID - b5.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 r2 = 0; r2 < nameRecords.length; r2++) { t3.fields.push({ name: "record_" + r2, type: "RECORD", value: nameRecords[r2] }); } 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 i4 = 0; i4 < unicodeRanges.length; i4 += 1) { var range = unicodeRanges[i4]; if (unicode >= range.begin && unicode < range.end) { return i4; } } return -1; } function parseOS2Table(data, start) { var os22 = {}; var p2 = new parse2.Parser(data, start); os22.version = p2.parseUShort(); os22.xAvgCharWidth = p2.parseShort(); os22.usWeightClass = p2.parseUShort(); os22.usWidthClass = p2.parseUShort(); os22.fsType = p2.parseUShort(); os22.ySubscriptXSize = p2.parseShort(); os22.ySubscriptYSize = p2.parseShort(); os22.ySubscriptXOffset = p2.parseShort(); os22.ySubscriptYOffset = p2.parseShort(); os22.ySuperscriptXSize = p2.parseShort(); os22.ySuperscriptYSize = p2.parseShort(); os22.ySuperscriptXOffset = p2.parseShort(); os22.ySuperscriptYOffset = p2.parseShort(); os22.yStrikeoutSize = p2.parseShort(); os22.yStrikeoutPosition = p2.parseShort(); os22.sFamilyClass = p2.parseShort(); os22.panose = []; for (var i4 = 0; i4 < 10; i4++) { os22.panose[i4] = p2.parseByte(); } os22.ulUnicodeRange1 = p2.parseULong(); os22.ulUnicodeRange2 = p2.parseULong(); os22.ulUnicodeRange3 = p2.parseULong(); os22.ulUnicodeRange4 = p2.parseULong(); os22.achVendID = String.fromCharCode(p2.parseByte(), p2.parseByte(), p2.parseByte(), p2.parseByte()); os22.fsSelection = p2.parseUShort(); os22.usFirstCharIndex = p2.parseUShort(); os22.usLastCharIndex = p2.parseUShort(); os22.sTypoAscender = p2.parseShort(); os22.sTypoDescender = p2.parseShort(); os22.sTypoLineGap = p2.parseShort(); os22.usWinAscent = p2.parseUShort(); os22.usWinDescent = p2.parseUShort(); if (os22.version >= 1) { os22.ulCodePageRange1 = p2.parseULong(); os22.ulCodePageRange2 = p2.parseULong(); } if (os22.version >= 2) { os22.sxHeight = p2.parseShort(); os22.sCapHeight = p2.parseShort(); os22.usDefaultChar = p2.parseUShort(); os22.usBreakChar = p2.parseUShort(); os22.usMaxContent = p2.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(data, start) { var post2 = {}; var p2 = new parse2.Parser(data, start); post2.version = p2.parseVersion(); post2.italicAngle = p2.parseFixed(); post2.underlinePosition = p2.parseShort(); post2.underlineThickness = p2.parseShort(); post2.isFixedPitch = p2.parseULong(); post2.minMemType42 = p2.parseULong(); post2.maxMemType42 = p2.parseULong(); post2.minMemType1 = p2.parseULong(); post2.maxMemType1 = p2.parseULong(); switch (post2.version) { case 1: post2.names = standardNames.slice(); break; case 2: post2.numberOfGlyphs = p2.parseUShort(); post2.glyphNameIndex = new Array(post2.numberOfGlyphs); for (var i4 = 0; i4 < post2.numberOfGlyphs; i4++) { post2.glyphNameIndex[i4] = p2.parseUShort(); } post2.names = []; for (var i$1 = 0; i$1 < post2.numberOfGlyphs; i$1++) { if (post2.glyphNameIndex[i$1] >= standardNames.length) { var nameLength = p2.parseChar(); post2.names.push(p2.parseString(nameLength)); } } break; case 2.5: post2.numberOfGlyphs = p2.parseUShort(); post2.offset = new Array(post2.numberOfGlyphs); for (var i$2 = 0; i$2 < post2.numberOfGlyphs; i$2++) { post2.offset[i$2] = p2.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(Parser2.coverage), deltaGlyphId: this.parseUShort() }; } else if (substFormat === 2) { return { substFormat: 2, coverage: this.parsePointer(Parser2.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(Parser2.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(Parser2.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(Parser2.coverage), ligatureSets: this.parseListOfLists(function() { return { ligGlyph: this.parseUShort(), components: this.parseUShortList(this.parseUShort() - 1) }; }) }; }; var lookupRecordDesc = { sequenceIndex: Parser2.uShort, lookupListIndex: Parser2.uShort }; subtableParsers[5] = function parseLookup5() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat, coverage: this.parsePointer(Parser2.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(Parser2.coverage), classDef: this.parsePointer(Parser2.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, Parser2.pointer(Parser2.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(Parser2.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(Parser2.coverage), backtrackClassDef: this.parsePointer(Parser2.classDef), inputClassDef: this.parsePointer(Parser2.classDef), lookaheadClassDef: this.parsePointer(Parser2.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(Parser2.pointer(Parser2.coverage)), inputCoverage: this.parseList(Parser2.pointer(Parser2.coverage)), lookaheadCoverage: this.parseList(Parser2.pointer(Parser2.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 Parser2(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(Parser2.coverage), backtrackCoverage: this.parseList(Parser2.pointer(Parser2.coverage)), lookaheadCoverage: this.parseList(Parser2.pointer(Parser2.coverage)), substitutes: this.parseUShortList() }; }; function parseGsubTable(data, start) { start = start || 0; var p2 = new Parser2(data, start); var tableVersion = p2.parseVersion(1); check.argument(tableVersion === 1 || tableVersion === 1.1, "Unsupported GSUB table version."); if (tableVersion === 1) { return { version: tableVersion, scripts: p2.parseScriptList(), features: p2.parseFeatureList(), lookups: p2.parseLookupList(subtableParsers) }; } else { return { version: tableVersion, scripts: p2.parseScriptList(), features: p2.parseFeatureList(), lookups: p2.parseLookupList(subtableParsers), variations: p2.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, i4) { tableData2 = tableData2.concat({ name: "sequenceIndex" + i4, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i4, 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, i4) { tableData.push({ name: "backtrackCoverage" + i4, type: "TABLE", value: new table.Coverage(coverage) }); }); tableData.push({ name: "inputGlyphCount", type: "USHORT", value: subtable.inputCoverage.length }); subtable.inputCoverage.forEach(function(coverage, i4) { tableData.push({ name: "inputCoverage" + i4, type: "TABLE", value: new table.Coverage(coverage) }); }); tableData.push({ name: "lookaheadGlyphCount", type: "USHORT", value: subtable.lookaheadCoverage.length }); subtable.lookaheadCoverage.forEach(function(coverage, i4) { tableData.push({ name: "lookaheadCoverage" + i4, type: "TABLE", value: new table.Coverage(coverage) }); }); tableData.push({ name: "substitutionCount", type: "USHORT", value: subtable.lookupRecords.length }); subtable.lookupRecords.forEach(function(record, i4) { tableData = tableData.concat({ name: "sequenceIndex" + i4, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i4, 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(data, start) { var p2 = new parse2.Parser(data, start); var tableVersion = p2.parseULong(); check.argument(tableVersion === 1, "Unsupported META table version."); p2.parseULong(); p2.parseULong(); var numDataMaps = p2.parseULong(); var tags = {}; for (var i4 = 0; i4 < numDataMaps; i4++) { var tag = p2.parseTag(); var dataOffset = p2.parseULong(); var dataLength = p2.parseULong(); var text = decode.UTF8(data, start + dataOffset, dataLength); tags[tag] = text; } 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 log2(v5) { return Math.log(v5) / Math.log(2) | 0; } function computeCheckSum(bytes) { while (bytes.length % 4 !== 0) { bytes.push(0); } var sum = 0; for (var i4 = 0; i4 < bytes.length; i4 += 4) { sum += (bytes[i4] << 24) + (bytes[i4 + 1] << 16) + (bytes[i4 + 2] << 8) + bytes[i4 + 3]; } sum %= Math.pow(2, 32); return sum; } function makeTableRecord(tag, checkSum, offset, length3) { 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: length3 !== void 0 ? length3 : 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 i4 = 0; i4 < tables.length; i4 += 1) { var t3 = tables[i4]; 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 i4 = 0; i4 < chars.length; i4 += 1) { var glyphIndex = font.charToGlyphIndex(chars[i4]); if (glyphIndex > 0) { var glyph = font.glyphs.get(glyphIndex); return glyph.getMetrics(); } } return notFoundMetrics; } function average(vs) { var sum = 0; for (var i4 = 0; i4 < vs.length; i4 += 1) { sum += vs[i4]; } return sum / 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 i4 = 0; i4 < font.glyphs.length; i4 += 1) { var glyph = font.glyphs.get(i4); var unicode = glyph.unicode | 0; if (isNaN(glyph.advanceWidth)) { throw new Error("Glyph " + glyph.name + " (" + i4 + "): 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 (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 val = arr[imid].tag; if (val === tag) { return imid; } else if (val < tag) { imin = imid + 1; } else { imax = imid - 1; } } return -imin - 1; } function binSearch(arr, value) { var imin = 0; var imax = arr.length - 1; while (imin <= imax) { var imid = imin + imax >>> 1; var val = arr[imid]; if (val === value) { return imid; } else if (val < value) { imin = imid + 1; } else { imax = imid - 1; } } return -imin - 1; } function searchRange(ranges, value) { 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 === value) { return range; } else if (start < value) { imin = imid + 1; } else { imax = imid - 1; } } if (imin > 0) { range = ranges[imin - 1]; if (value > 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(create4) { var layout = this.font.tables[this.tableName]; if (!layout && create4) { 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 i4 = 0; i4 < layout.scripts.length; i4++) { var name = layout.scripts[i4].tag; if (name === "DFLT") { return name; } if (name === "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, create4) { var layout = this.getTable(create4); if (layout) { script = script || "DFLT"; var scripts = layout.scripts; var pos = searchTag(layout.scripts, script); if (pos >= 0) { return scripts[pos].script; } else if (create4) { 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, create4) { var scriptTable = this.getScriptTable(script, create4); 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 (create4) { 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, create4) { var langSysTable2 = this.getLangSysTable(script, language, create4); if (langSysTable2) { var featureRecord; var featIndexes = langSysTable2.featureIndexes; var allFeatures = this.font.tables[this.tableName].features; for (var i4 = 0; i4 < featIndexes.length; i4++) { featureRecord = allFeatures[featIndexes[i4]]; if (featureRecord.tag === feature) { return featureRecord.feature; } } if (create4) { 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, create4) { var featureTable = this.getFeatureTable(script, language, feature, create4); var tables = []; if (featureTable) { var lookupTable; var lookupListIndexes = featureTable.lookupListIndexes; var allLookups = this.font.tables[this.tableName].lookups; for (var i4 = 0; i4 < lookupListIndexes.length; i4++) { lookupTable = allLookups[lookupListIndexes[i4]]; if (lookupTable.lookupType === lookupType) { tables.push(lookupTable); } } if (tables.length === 0 && create4) { 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 i4 = 0; i4 < ranges.length; i4++) { var range = ranges[i4]; var start = range.start; var end = range.end; for (var j = start; j <= end; j++) { glyphs.push(j); } } 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 i4 = 0; i4 < kerningLookups.length; i4++) { var subtables = kerningLookups[i4].subtables; for (var j = 0; j < subtables.length; j++) { var subtable = subtables[j]; var covIndex = this.getCoverageIndex(subtable.coverage, leftIndex); if (covIndex < 0) { continue; } switch (subtable.posFormat) { case 1: var pairSet = subtable.pairSets[covIndex]; for (var k = 0; k < pairSet.length; k++) { var pair = pairSet[k]; if (pair.secondGlyph === rightIndex) { return pair.value1 && pair.value1.xAdvance || 0; } } break; 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 i4 = 0; i4 < n2; i4++) { if (ar1[i4] !== ar2[i4]) { return false; } } return true; } function getSubstFormat(lookupTable, format, defaultSubtable) { var subtables = lookupTable.subtables; for (var i4 = 0; i4 < subtables.length; i4++) { var subtable = subtables[i4]; 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 i4 = 0; i4 < subtables.length; i4++) { var subtable = subtables[i4]; var glyphs = this.expandCoverage(subtable.coverage); var j = void 0; if (subtable.substFormat === 1) { var delta = subtable.deltaGlyphId; for (j = 0; j < glyphs.length; j++) { var glyph = glyphs[j]; substitutions.push({ sub: glyph, by: glyph + delta }); } } else { var substitute = subtable.substitute; for (j = 0; j < glyphs.length; j++) { substitutions.push({ sub: glyphs[j], by: substitute[j] }); } } } } 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 i4 = 0; i4 < subtables.length; i4++) { var subtable = subtables[i4]; var glyphs = this.expandCoverage(subtable.coverage); var j = void 0; for (j = 0; j < glyphs.length; j++) { var glyph = glyphs[j]; var replacements = subtable.sequences[j]; 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 i4 = 0; i4 < subtables.length; i4++) { var subtable = subtables[i4]; var glyphs = this.expandCoverage(subtable.coverage); var alternateSets = subtable.alternateSets; for (var j = 0; j < glyphs.length; j++) { alternates.push({ sub: glyphs[j], by: alternateSets[j] }); } } } 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 i4 = 0; i4 < subtables.length; i4++) { var subtable = subtables[i4]; var glyphs = this.expandCoverage(subtable.coverage); var ligatureSets = subtable.ligatureSets; for (var j = 0; j < glyphs.length; j++) { var startGlyph = glyphs[j]; var ligSet = ligatureSets[j]; for (var k = 0; k < ligSet.length; k++) { var lig = ligSet[k]; 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 i4 = 0; i4 < ligatureSet.length; i4++) { if (arraysEqual(ligatureSet[i4].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, sub3, script, language) { if (/ss\d\d/.test(feature)) { return this.addSingle(feature, sub3, script, language); } switch (feature) { case "aalt": case "salt": if (typeof sub3.by === "number") { return this.addSingle(feature, sub3, script, language); } return this.addAlternate(feature, sub3, script, language); case "dlig": case "liga": case "rlig": return this.addLigature(feature, sub3, script, language); case "ccmp": if (sub3.by instanceof Array) { return this.addMultiple(feature, sub3, script, language); } return this.addLigature(feature, sub3, script, language); } return void 0; }; function checkArgument(expression, message) { if (!expression) { throw message; } } function parseGlyphCoordinate(p2, flag, previousValue, shortVectorBitMask, sameBitMask) { var v5; if ((flag & shortVectorBitMask) > 0) { v5 = p2.parseByte(); if ((flag & sameBitMask) === 0) { v5 = -v5; } v5 = previousValue + v5; } else { if ((flag & sameBitMask) > 0) { v5 = previousValue; } else { v5 = previousValue + p2.parseShort(); } } return v5; } function parseGlyph(glyph, data, start) { var p2 = new parse2.Parser(data, start); glyph.numberOfContours = p2.parseShort(); glyph._xMin = p2.parseShort(); glyph._yMin = p2.parseShort(); glyph._xMax = p2.parseShort(); glyph._yMax = p2.parseShort(); var flags; var flag; if (glyph.numberOfContours > 0) { var endPointIndices = glyph.endPointIndices = []; for (var i4 = 0; i4 < glyph.numberOfContours; i4 += 1) { endPointIndices.push(p2.parseUShort()); } glyph.instructionLength = p2.parseUShort(); glyph.instructions = []; for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) { glyph.instructions.push(p2.parseByte()); } var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; flags = []; for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) { flag = p2.parseByte(); flags.push(flag); if ((flag & 8) > 0) { var repeatCount = p2.parseByte(); for (var j = 0; j < repeatCount; j += 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(p2, 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(p2, 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 = p2.parseUShort(); var component = { glyphIndex: p2.parseUShort(), xScale: 1, scale01: 0, scale10: 0, yScale: 1, dx: 0, dy: 0 }; if ((flags & 1) > 0) { if ((flags & 2) > 0) { component.dx = p2.parseShort(); component.dy = p2.parseShort(); } else { component.matchedPoints = [p2.parseUShort(), p2.parseUShort()]; } } else { if ((flags & 2) > 0) { component.dx = p2.parseChar(); component.dy = p2.parseChar(); } else { component.matchedPoints = [p2.parseByte(), p2.parseByte()]; } } if ((flags & 8) > 0) { component.xScale = component.yScale = p2.parseF2Dot14(); } else if ((flags & 64) > 0) { component.xScale = p2.parseF2Dot14(); component.yScale = p2.parseF2Dot14(); } else if ((flags & 128) > 0) { component.xScale = p2.parseF2Dot14(); component.scale01 = p2.parseF2Dot14(); component.scale10 = p2.parseF2Dot14(); component.yScale = p2.parseF2Dot14(); } glyph.components.push(component); moreComponents = !!(flags & 32); } if (flags & 256) { glyph.instructionLength = p2.parseUShort(); glyph.instructions = []; for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) { glyph.instructions.push(p2.parseByte()); } } } } function transformPoints(points, transform) { var newPoints = []; for (var i4 = 0; i4 < points.length; i4 += 1) { var pt = points[i4]; var newPt = { x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, onCurve: pt.onCurve, lastPointOfContour: pt.lastPointOfContour }; newPoints.push(newPt); } return newPoints; } function getContours(points) { var contours = []; var currentContour = []; for (var i4 = 0; i4 < points.length; i4 += 1) { var pt = points[i4]; 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 p2 = new Path2(); if (!points) { return p2; } 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) { p2.moveTo(curr.x, curr.y); } else { if (next.onCurve) { p2.moveTo(next.x, next.y); } else { var start = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; p2.moveTo(start.x, start.y); } } for (var i4 = 0; i4 < contour.length; ++i4) { prev = curr; curr = next; next = contour[(i4 + 1) % contour.length]; if (curr.onCurve) { p2.lineTo(curr.x, curr.y); } else { var next2 = next; if (!prev.onCurve) { ({ 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 }; } p2.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); } } p2.closePath(); } return p2; } function buildPath(glyphs, glyph) { if (glyph.isComposite) { for (var j = 0; j < glyph.components.length; j += 1) { var component = glyph.components[j]; 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 transform = { xScale: component.xScale, scale01: component.scale01, scale10: component.scale10, yScale: component.yScale, dx: 0, dy: 0 }; secondPt = transformPoints([secondPt], transform)[0]; transform.dx = firstPt.x - secondPt.x; transform.dy = firstPt.y - secondPt.y; transformedPoints = transformPoints(componentGlyph.points, transform); } glyph.points = glyph.points.concat(transformedPoints); } } } return getPath(glyph.points); } function parseGlyfTableAll(data, start, loca2, font) { var glyphs = new glyphset.GlyphSet(font); for (var i4 = 0; i4 < loca2.length - 1; i4 += 1) { var offset = loca2[i4]; var nextOffset = loca2[i4 + 1]; if (offset !== nextOffset) { glyphs.push(i4, glyphset.ttfGlyphLoader(font, i4, parseGlyph, data, start + offset, buildPath)); } else { glyphs.push(i4, glyphset.glyphLoader(font, i4)); } } return glyphs; } function parseGlyfTableOnLowMemory(data, start, loca2, font) { var glyphs = new glyphset.GlyphSet(font); font._push = function(i4) { var offset = loca2[i4]; var nextOffset = loca2[i4 + 1]; if (offset !== nextOffset) { glyphs.push(i4, glyphset.ttfGlyphLoader(font, i4, parseGlyph, data, start + offset, buildPath)); } else { glyphs.push(i4, glyphset.glyphLoader(font, i4)); } }; return glyphs; } function parseGlyfTable(data, start, loca2, font, opt) { if (opt.lowMemory) { return parseGlyfTableOnLowMemory(data, start, loca2, font); } else { return parseGlyfTableAll(data, 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(v5) { return v5; } function roundToGrid(v5) { return Math.sign(v5) * Math.round(Math.abs(v5)); } function roundToDoubleGrid(v5) { return Math.sign(v5) * Math.round(Math.abs(v5 * 2)) / 2; } function roundToHalfGrid(v5) { return Math.sign(v5) * (Math.round(Math.abs(v5) + 0.5) - 0.5); } function roundUpToGrid(v5) { return Math.sign(v5) * Math.ceil(Math.abs(v5)); } function roundDownToGrid(v5) { return Math.sign(v5) * Math.floor(Math.abs(v5)); } var roundSuper = function(v5) { var period = this.srPeriod; var phase = this.srPhase; var threshold = this.srThreshold; var sign = 1; if (v5 < 0) { v5 = -v5; sign = -1; } v5 += threshold - phase; v5 = Math.trunc(v5 / period) * period; v5 += phase; if (v5 < 0) { return phase * sign; } return v5 * 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(p2, rp1, rp2, pv) { var do1; var do2; var doa1; var doa2; var dm1; var dm2; var dt; if (!pv || pv === this) { do1 = p2.xo - rp1.xo; do2 = p2.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) { p2.x = p2.xo + (dm1 + dm2) / 2; return; } p2.x = p2.xo + (dm1 * doa2 + dm2 * doa1) / dt; return; } do1 = pv.distance(p2, rp1, true, true); do2 = pv.distance(p2, 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(p2, p2, (dm1 + dm2) / 2, pv, true); return; } xUnitVector.setRelative(p2, p2, (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(p2, rp, d2, pv, org) { if (!pv || pv === this) { p2.x = (org ? rp.xo : rp.x) + d2; return; } var rpx = org ? rp.xo : rp.x; var rpy = org ? rp.yo : rp.y; var rpdx = rpx + d2 * pv.x; var rpdy = rpy + d2 * pv.y; p2.x = rpdx + (p2.y - rpdy) / pv.normalSlope; }, // Slope of vector line. slope: 0, // Touches the point p. touch: function(p2) { p2.xTouched = true; }, // Tests if a point p is touched. touched: function(p2) { return p2.xTouched; }, // Untouches the point p. untouch: function(p2) { p2.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(p2, rp1, rp2, pv) { var do1; var do2; var doa1; var doa2; var dm1; var dm2; var dt; if (!pv || pv === this) { do1 = p2.yo - rp1.yo; do2 = p2.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) { p2.y = p2.yo + (dm1 + dm2) / 2; return; } p2.y = p2.yo + (dm1 * doa2 + dm2 * doa1) / dt; return; } do1 = pv.distance(p2, rp1, true, true); do2 = pv.distance(p2, 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(p2, p2, (dm1 + dm2) / 2, pv, true); return; } yUnitVector.setRelative(p2, p2, (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(p2, rp, d2, pv, org) { if (!pv || pv === this) { p2.y = (org ? rp.yo : rp.y) + d2; return; } var rpx = org ? rp.xo : rp.x; var rpy = org ? rp.yo : rp.y; var rpdx = rpx + d2 * pv.x; var rpdy = rpy + d2 * pv.y; p2.y = rpdy + pv.normalSlope * (p2.x - rpdx); }, // Slope of vector line. slope: Number.POSITIVE_INFINITY, // Touches the point p. touch: function(p2) { p2.yTouched = true; }, // Tests if a point p is touched. touched: function(p2) { return p2.yTouched; }, // Untouches the point p. untouch: function(p2) { p2.yTouched = false; } }; Object.freeze(xUnitVector); Object.freeze(yUnitVector); function UnitVector(x, y) { this.x = x; this.y = y; this.axis = void 0; this.slope = y / x; this.normalSlope = -x / 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(p2, rp1, rp2, pv) { var dm1; var dm2; var do1; var do2; var doa1; var doa2; var dt; do1 = pv.distance(p2, rp1, true, true); do2 = pv.distance(p2, 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(p2, p2, (dm1 + dm2) / 2, pv, true); return; } this.setRelative(p2, p2, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); }; UnitVector.prototype.setRelative = function(p2, rp, d2, pv, org) { pv = pv || this; var rpx = org ? rp.xo : rp.x; var rpy = org ? rp.yo : rp.y; var rpdx = rpx + d2 * pv.x; var rpdy = rpy + d2 * pv.y; var pvns = pv.normalSlope; var fvs = this.slope; var px = p2.x; var py = p2.y; p2.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns); p2.y = fvs * (p2.x - px) + py; }; UnitVector.prototype.touch = function(p2) { p2.xTouched = true; p2.yTouched = true; }; function getUnitVector(x, y) { var d2 = Math.sqrt(x * x + y * y); x /= d2; y /= d2; if (x === 1 && y === 0) { return xUnitVector; } else if (x === 0 && y === 1) { return yUnitVector; } else { return new UnitVector(x, y); } } function HPoint(x, y, lastPointOfContour, onCurve) { this.x = this.xo = Math.round(x * 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(v5) { var p2 = this.nextPointOnContour; while (!v5.touched(p2) && p2 !== this) { p2 = p2.nextPointOnContour; } return p2; }; HPoint.prototype.prevTouched = function(v5) { var p2 = this.prevPointOnContour; while (!v5.touched(p2) && p2 !== this) { p2 = p2.prevPointOnContour; } return p2; }; 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; 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 (e2) { console.log("Hinting error in FPGM:" + e2); 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 scale5 = ppem / font.unitsPerEm; for (var c2 = 0; c2 < oCvt.length; c2++) { cvt[c2] = oCvt[c2] * scale5; } } else { prepState.cvt = []; } if (exports.DEBUG) { console.log("---EXEC PREP---"); prepState.step = -1; } try { exec(prepState); } catch (e2) { if (this._errorState < 2) { console.log("Hinting error in PREP:" + e2); } this._errorState = 2; } } if (this._errorState > 1) { return; } try { return execGlyph(glyph, prepState); } catch (e2) { if (this._errorState < 1) { console.log("Hinting error:" + e2); 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 i4 = 0; i4 < components.length; i4++) { var c2 = components[i4]; var cg = font.glyphs.get(c2.glyphIndex); state = new State("glyf", cg.instructions); if (exports.DEBUG) { console.log("---EXEC COMP " + i4 + "---"); 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 pi = 0; pi < gz.length; pi++) { var p2 = gz[pi]; p2.xTouched = p2.yTouched = false; p2.xo = p2.x = p2.x + dx; p2.yo = p2.y = p2.y + dy; } var gLen = gZone.length; gZone.push.apply(gZone, gz); for (var j = 0; j < cc.length; j++) { contours.push(cc[j] + 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 i4 = 0; i4 < pLen; i4++) { cp = points[i4]; gZone[i4] = 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 i4 = 0; i4 < tZone.length; i4++) { tZone[i4] = 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(v5, state) { if (exports.DEBUG) { console.log(state.step, "SVTCA[" + v5.axis + "]"); } state.fv = state.pv = state.dpv = v5; } function SPVTCA(v5, state) { if (exports.DEBUG) { console.log(state.step, "SPVTCA[" + v5.axis + "]"); } state.pv = state.dpv = v5; } function SFVTCA(v5, state) { if (exports.DEBUG) { console.log(state.step, "SFVTCA[" + v5.axis + "]"); } state.fv = v5; } function SPVTL(a6, 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[" + a6 + "]", p2i, p1i); } var dx; var dy; if (!a6) { 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(a6, 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[" + a6 + "]", p2i, p1i); } var dx; var dy; if (!a6) { 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 x = stack.pop(); if (exports.DEBUG) { console.log(state.step, "SPVFS[]", y, x); } state.pv = state.dpv = getUnitVector(x, y); } function SFVFS(state) { var stack = state.stack; var y = stack.pop(); var x = stack.pop(); if (exports.DEBUG) { console.log(state.step, "SPVFS[]", y, x); } state.fv = getUnitVector(x, 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 pi = 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 p2 = state.z2[pi]; if (exports.DEBUG) { console.log("ISECT[], ", pa0i, pa1i, pb0i, pb1i, pi); } 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 div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); var f1 = x1 * y2 - y1 * x2; var f2 = x3 * y4 - y3 * x4; p2.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div; p2.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div; } 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 d2 = state.stack.pop(); if (exports.DEBUG) { console.log(state.step, "SMD[]", d2); } state.minDis = d2 / 64; } function ELSE(state) { if (exports.DEBUG) { console.log(state.step, "ELSE[]"); } skip(state, false); } function JMPR(state) { var o2 = state.stack.pop(); if (exports.DEBUG) { console.log(state.step, "JMPR[]", o2); } state.ip += o2 - 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 a6 = stack.pop(); var b5 = stack.pop(); if (exports.DEBUG) { console.log(state.step, "SWAP[]"); } stack.push(a6); stack.push(b5); } 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 i4 = 0; i4 < c2; i4++) { exec(state); if (exports.DEBUG) { console.log(++state.step, i4 + 1 < c2 ? "next loopcall" : "done loopcall", i4); } } 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 k = stack.pop(); if (exports.DEBUG) { console.log(state.step, "CINDEX[]", k); } stack.push(stack[stack.length - k]); } function MINDEX(state) { var stack = state.stack; var k = stack.pop(); if (exports.DEBUG) { console.log(state.step, "MINDEX[]", k); } stack.push(stack.splice(stack.length - k, 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 pi = state.stack.pop(); var p2 = state.z0[pi]; var fv = state.fv; var pv = state.pv; if (exports.DEBUG) { console.log(state.step, "MDAP[" + round + "]", pi); } var d2 = pv.distance(p2, HPZero); if (round) { d2 = state.round(d2); } fv.setRelative(p2, HPZero, d2, pv); fv.touch(p2); state.rp0 = state.rp1 = pi; } function IUP(v5, state) { var z2 = state.z2; var pLen = z2.length - 2; var cp; var pp; var np; if (exports.DEBUG) { console.log(state.step, "IUP[" + v5.axis + "]"); } for (var i4 = 0; i4 < pLen; i4++) { cp = z2[i4]; if (v5.touched(cp)) { continue; } pp = cp.prevTouched(v5); if (pp === cp) { continue; } np = cp.nextTouched(v5); if (pp === np) { v5.setRelative(cp, cp, v5.distance(pp, pp, false, true), v5, true); } v5.interpolate(cp, pp, np, v5); } } function SHP(a6, state) { var stack = state.stack; var rpi = a6 ? state.rp1 : state.rp2; var rp = (a6 ? state.z0 : state.z1)[rpi]; var fv = state.fv; var pv = state.pv; var loop = state.loop; var z2 = state.z2; while (loop--) { var pi = stack.pop(); var p2 = z2[pi]; var d2 = pv.distance(rp, rp, false, true); fv.setRelative(p2, p2, d2, pv); fv.touch(p2); if (exports.DEBUG) { console.log( state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHP[" + (a6 ? "rp1" : "rp2") + "]", pi ); } } state.loop = 1; } function SHC(a6, state) { var stack = state.stack; var rpi = a6 ? state.rp1 : state.rp2; var rp = (a6 ? 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 p2 = sp; if (exports.DEBUG) { console.log(state.step, "SHC[" + a6 + "]", ci); } var d2 = pv.distance(rp, rp, false, true); do { if (p2 !== rp) { fv.setRelative(p2, p2, d2, pv); } p2 = p2.nextPointOnContour; } while (p2 !== sp); } function SHZ(a6, state) { var stack = state.stack; var rpi = a6 ? state.rp1 : state.rp2; var rp = (a6 ? state.z0 : state.z1)[rpi]; var fv = state.fv; var pv = state.pv; var e2 = stack.pop(); if (exports.DEBUG) { console.log(state.step, "SHZ[" + a6 + "]", e2); } var z; switch (e2) { case 0: z = state.tZone; break; case 1: z = state.gZone; break; default: throw new Error("Invalid zone"); } var p2; var d2 = pv.distance(rp, rp, false, true); var pLen = z.length - 2; for (var i4 = 0; i4 < pLen; i4++) { p2 = z[i4]; fv.setRelative(p2, p2, d2, pv); } } function SHPIX(state) { var stack = state.stack; var loop = state.loop; var fv = state.fv; var d2 = stack.pop() / 64; var z2 = state.z2; while (loop--) { var pi = stack.pop(); var p2 = z2[pi]; if (exports.DEBUG) { console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHPIX[]", pi, d2); } fv.setRelative(p2, p2, d2); fv.touch(p2); } 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 pi = stack.pop(); var p2 = z2[pi]; if (exports.DEBUG) { console.log( state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "IP[]", pi, rp1i, "<->", rp2i ); } fv.interpolate(p2, rp1, rp2, pv); fv.touch(p2); } state.loop = 1; } function MSIRP(a6, state) { var stack = state.stack; var d2 = stack.pop() / 64; var pi = stack.pop(); var p2 = state.z1[pi]; var rp0 = state.z0[state.rp0]; var fv = state.fv; var pv = state.pv; fv.setRelative(p2, rp0, d2, pv); fv.touch(p2); if (exports.DEBUG) { console.log(state.step, "MSIRP[" + a6 + "]", d2, pi); } state.rp1 = state.rp0; state.rp2 = pi; if (a6) { state.rp0 = pi; } } 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 pi = stack.pop(); var p2 = z1[pi]; if (exports.DEBUG) { console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "ALIGNRP[]", pi); } fv.setRelative(p2, rp0, 0, pv); fv.touch(p2); } 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 pi = stack.pop(); var p2 = state.z0[pi]; var fv = state.fv; var pv = state.pv; var cv = state.cvt[n2]; if (exports.DEBUG) { console.log(state.step, "MIAP[" + round + "]", n2, "(", cv, ")", pi); } var d2 = pv.distance(p2, HPZero); if (round) { if (Math.abs(d2 - cv) < state.cvCutIn) { d2 = cv; } d2 = state.round(d2); } fv.setRelative(p2, HPZero, d2, pv); if (state.zp0 === 0) { p2.xo = p2.x; p2.yo = p2.y; } fv.touch(p2); state.rp0 = state.rp1 = pi; } 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 i4 = 0; i4 < n2; i4++) { 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 i4 = 0; i4 < n2; i4++) { 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 v5 = stack.pop(); var l2 = stack.pop(); if (exports.DEBUG) { console.log(state.step, "WS", v5, l2); } store[l2] = v5; } 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 v5 = store && store[l2] || 0; stack.push(v5); } function WCVTP(state) { var stack = state.stack; var v5 = stack.pop(); var l2 = stack.pop(); if (exports.DEBUG) { console.log(state.step, "WCVTP", v5, l2); } state.cvt[l2] = v5 / 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(a6, state) { var stack = state.stack; var pi = stack.pop(); var p2 = state.z2[pi]; if (exports.DEBUG) { console.log(state.step, "GC[" + a6 + "]", pi); } stack.push(state.dpv.distance(p2, HPZero, a6, false) * 64); } function MD(a6, state) { var stack = state.stack; var pi2 = stack.pop(); var pi1 = stack.pop(); var p2 = state.z1[pi2]; var p1 = state.z0[pi1]; var d2 = state.dpv.distance(p1, p2, a6, a6); if (exports.DEBUG) { console.log(state.step, "MD[" + a6 + "]", pi2, pi1, "->", d2); } state.stack.push(Math.round(d2 * 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 e2 = stack.pop(); if (exports.DEBUG) { console.log(state.step, "NOT[]", e2); } stack.push(e2 ? 0 : 1); } function DELTAP123(b5, 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 + (b5 - 1) * 16; var ds = state.deltaShift; var z0 = state.z0; if (exports.DEBUG) { console.log(state.step, "DELTAP[" + b5 + "]", n2, stack); } for (var i4 = 0; i4 < n2; i4++) { var pi = 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", pi, "by", mag * ds); } var p2 = z0[pi]; fv.setRelative(p2, p2, 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 v5 = stack.pop(); var l2 = stack.pop(); if (exports.DEBUG) { console.log(state.step, "WCVTF[]", v5, l2); } state.cvt[l2] = v5 * state.ppem / state.font.unitsPerEm; } function DELTAC123(b5, state) { var stack = state.stack; var n2 = stack.pop(); var ppem = state.ppem; var base = state.deltaBase + (b5 - 1) * 16; var ds = state.deltaShift; if (exports.DEBUG) { console.log(state.step, "DELTAC[" + b5 + "]", n2, stack); } for (var i4 = 0; i4 < n2; i4++) { 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(a6, 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[" + a6 + "]", p2i, p1i); } var dx; var dy; if (!a6) { 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 r2 = 0; if (exports.DEBUG) { console.log(state.step, "GETINFO[]", sel); } if (sel & 1) { r2 = 35; } if (sel & 32) { r2 |= 4096; } stack.push(r2); } function ROLL(state) { var stack = state.stack; var a6 = stack.pop(); var b5 = stack.pop(); var c2 = stack.pop(); if (exports.DEBUG) { console.log(state.step, "ROLL[]"); } stack.push(b5); stack.push(a6); 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 s2 = state.stack.pop(); var v5 = state.stack.pop(); if (exports.DEBUG) { console.log(state.step, "INSTCTRL[]", s2, v5); } switch (s2) { case 1: state.inhibitGridFit = !!v5; return; case 2: state.ignoreCvt = !!v5; 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 i4 = 0; i4 < n2; i4++) { 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 i4 = 0; i4 < n2; i4++) { 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 pi = stack.pop(); var rp0i = state.rp0; var rp = state.z0[rp0i]; var p2 = state.z1[pi]; var md = state.minDis; var fv = state.fv; var pv = state.dpv; var od; var d2; var sign; var cv; d2 = od = pv.distance(p2, rp, true, true); sign = d2 >= 0 ? 1 : -1; d2 = Math.abs(d2); if (indirect) { cv = state.cvt[cvte]; if (ro && Math.abs(d2 - cv) < state.cvCutIn) { d2 = cv; } } if (keepD && d2 < md) { d2 = md; } if (ro) { d2 = state.round(d2); } fv.setRelative(p2, rp, sign * d2, pv); fv.touch(p2); 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 + ")" : "", pi, "(d =", od, "->", sign * d2, ")" ); } state.rp1 = state.rp0; state.rp2 = pi; if (setRp0) { state.rp0 = pi; } } 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(context12, currentIndex) { this.context = context12; this.index = currentIndex; this.length = context12.length; this.current = context12[currentIndex]; this.backtrack = context12.slice(0, currentIndex); this.lookahead = context12.slice(currentIndex + 1); } function Event(eventId) { this.eventId = eventId; this.subscribers = []; } function initializeCoreEvents(events) { var this$1$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$1.events, eventId, { value: new Event(eventId) }); }); if (!!events) { coreEvents.forEach(function(eventId) { var event = events[eventId]; if (typeof event === "function") { this$1$1.events[eventId].subscribe(event); } }); } var requiresContextUpdate = [ "insertToken", "removeToken", "removeRange", "replaceToken", "replaceRange", "composeRUD" ]; requiresContextUpdate.forEach(function(eventId) { this$1$1.events[eventId].subscribe(this$1$1.updateContextsRanges); }); } function Tokenizer(events) { this.tokens = []; this.registeredContexts = {}; this.contextCheckers = []; this.events = {}; this.registeredModifiers = []; initializeCoreEvents.call(this, events); } Token.prototype.setState = function(key, value) { this.state[key] = value; this.activeState = { key, value: this.state[key] }; 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$1 = this; var silent = true; var state = RUDs.map(function(RUD) { return this$1$1[RUD[0]].apply(this$1$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 context12 = this.registeredContexts[contextName]; return !!context12 ? context12 : 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$1 = this; var event = this.events[eventName]; if (event instanceof Event) { event.subscribers.forEach(function(subscriber) { subscriber.apply(this$1$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 context12 = this.getContext(contextName); if (!!context12) { return context12.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 context12 = registeredContexts[contextName]; context12.ranges = []; } } }; Tokenizer.prototype.updateContextsRanges = function() { this.resetContextsRanges(); var chars = this.tokens.map(function(token) { return token.char; }); for (var i4 = 0; i4 < chars.length; i4++) { var contextParams = new ContextParams(chars, i4); 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$1 = this; var index2 = contextParams.index; this.contextCheckers.forEach(function(contextChecker) { var contextName = contextChecker.contextName; var openRange = this$1$1.getContext(contextName).openRange; if (!openRange && contextChecker.checkStart(contextParams)) { openRange = new ContextRange(index2, null, contextName); this$1$1.getContext(contextName).openRange = openRange; this$1$1.dispatch("contextStart", [contextName, index2]); } if (!!openRange && contextChecker.checkEnd(contextParams)) { var offset = index2 - openRange.startIndex + 1; var range = this$1$1.setEndOffset(offset, contextName); this$1$1.dispatch("contextEnd", [contextName, range]); } }); }; Tokenizer.prototype.tokenize = function(text) { this.tokens = []; this.resetContextsRanges(); var chars = Array.from(text); this.dispatch("start"); for (var i4 = 0; i4 < chars.length; i4++) { var char = chars[i4]; var contextParams = new ContextParams(chars, i4); 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 i4 = 0; i4 < ranges.length; i4++) { var range = ranges[i4]; 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 i4 = 0; i4 < coverageList.length; i4++) { var coverage = coverageList[i4]; 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 i4 = 0; i4 < subtable.lookupRecords.length; i4++) { var lookupRecord = subtable.lookupRecords[i4]; var lookupListIndex = lookupRecord.lookupListIndex; var lookupTable = this.getLookupByIndex(lookupListIndex); for (var s2 = 0; s2 < lookupTable.subtables.length; s2++) { var subtable$1 = lookupTable.subtables[s2]; 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 s2 = 0; s2 < ligatureSet.length; s2++) { ligature = ligatureSet[s2]; 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 s2 = 0; s2 < scripts.length; s2++) { var script = scripts[s2]; 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 i4 = 0; i4 < scripts.length; i4++) { var script = scripts[i4]; if (script.tag === scriptTag && script.script.defaultLangSys) { return script.script.defaultLangSys.featureIndexes; } else { var langSysRecords = script.langSysRecords; if (!!langSysRecords) { for (var j = 0; j < langSysRecords.length; j++) { var langSysRecord = langSysRecords[j]; if (langSysRecord.tag === scriptTag) { var langSys = langSysRecord.langSys; return langSys.featureIndexes; } } } } } return this.getDefaultScriptFeaturesIndexes(); }; FeatureQuery.prototype.mapTagsToFeatures = function(features, scriptTag) { var tags = {}; for (var i4 = 0; i4 < features.length; i4++) { var tag = features[i4].tag; var feature = features[i4].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$1 = this; var substitutionType = this.getSubstitutionType(lookupTable, subtable); switch (substitutionType) { case "11": return function(glyphIndex) { return singleSubstitutionFormat1.apply(this$1$1, [glyphIndex, subtable]); }; case "12": return function(glyphIndex) { return singleSubstitutionFormat2.apply(this$1$1, [glyphIndex, subtable]); }; case "63": return function(contextParams) { return chainingSubstitutionFormat3.apply(this$1$1, [contextParams, subtable]); }; case "41": return function(contextParams) { return ligatureSubstitutionFormat1.apply(this$1$1, [contextParams, subtable]); }; case "21": return function(glyphIndex) { return decompositionSubstitutionFormat1.apply(this$1$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 s2 = 0; s2 < subtables.length; s2++) { var subtable = subtables[s2]; 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 i4 = 0; i4 < compsCount; i4++) { token = tokens[index2 + i4 + 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 i4 = backtrack.length - 1; i4 >= 0; i4--) { var prevChar = backtrack[i4]; 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 i4 = 0; i4 < charContextParams.lookahead.length; i4++) { var nextChar = charContextParams.lookahead[i4]; var tashkeel = isTashkeelArabicChar(nextChar); if (!tashkeel) { return true; } } return false; } function arabicPresentationForms(range) { var this$1$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$1.query.lookupFeature({ tag, script, contextParams }); if (substitutions instanceof Error) { return console.info(substitutions.message); } substitutions.forEach(function(action, index22) { if (action instanceof SubstitutionAction) { applySubstitution(action, tokens, index22); contextParams.context[index22] = action.substitution; } }); }); } function getContextParams(tokens, index2) { var context12 = tokens.map(function(token) { return token.activeState.value; }); return new ContextParams(context12, index2 || 0); } function arabicRequiredLigatures(range) { var this$1$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$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 context12 = tokens.map(function(token) { return token.activeState.value; }); return new ContextParams(context12, index2 || 0); } function latinLigature(range) { var this$1$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$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(text) { this.text = text; }; 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$1 = this; var ranges = this.tokenizer.getContextRanges("arabicSentence"); ranges.forEach(function(range) { var rangeTokens = this$1$1.tokenizer.getRangeTokens(range); this$1$1.tokenizer.replaceRange(range.startIndex, range.endOffset, rangeTokens.reverse()); }); } Bidi.prototype.registerFeatures = function(script, tags) { var this$1$1 = this; var supportedTags = tags.filter(function(tag) { return this$1$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 f2 = 0; f2 < features.length; f2++) { var feature = features[f2]; 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$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$1, range); }); } function applyArabicRequireLigatures() { var this$1$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$1, range); }); } function applyLatinLigatures() { var this$1$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$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(text) { if (!this.text || this.text !== text) { this.setText(text); tokenizeText.call(this); this.applyFeaturesToContexts(); } }; Bidi.prototype.getBidiText = function(text) { this.processText(text); return this.tokenizer.getText(); }; Bidi.prototype.getTextGlyphs = function(text) { this.processText(text); var indexes = []; for (var i4 = 0; i4 < this.tokenizer.tokens.length; i4++) { var token = this.tokenizer.tokens[i4]; 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(s2) { return this.encoding.charToGlyphIndex(s2); }; 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(s2, options) { var this$1$1 = this; var bidi = new Bidi(); var charToGlyphIndexMod = function(token) { return this$1$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(s2); var length3 = indexes.length; var glyphs = new Array(length3); var notdef = this.glyphs.get(0); for (var i4 = 0; i4 < length3; i4 += 1) { glyphs[i4] = this.glyphs.get(indexes[i4]) || notdef; } return glyphs; }; Font2.prototype.nameToGlyphIndex = function(name) { return this.glyphNames.nameToGlyphIndex(name); }; Font2.prototype.nameToGlyph = function(name) { var glyphIndex = this.nameToGlyphIndex(name); 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(text, x, y, fontSize, options, callback) { x = x !== void 0 ? x : 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(text, options); var kerningLookups; if (options.kerning) { var script = options.script || this.position.getDefaultScriptName(); kerningLookups = this.position.getKerningTables(script, options.language); } for (var i4 = 0; i4 < glyphs.length; i4 += 1) { var glyph = glyphs[i4]; callback.call(this, glyph, x, y, fontSize, options); if (glyph.advanceWidth) { x += glyph.advanceWidth * fontScale; } if (options.kerning && i4 < glyphs.length - 1) { var kerningValue = kerningLookups ? this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i4 + 1].index) : this.getKerningValue(glyph, glyphs[i4 + 1]); x += kerningValue * fontScale; } if (options.letterSpacing) { x += options.letterSpacing * fontSize; } else if (options.tracking) { x += options.tracking / 1e3 * fontSize; } } return x; }; Font2.prototype.getPath = function(text, x, y, fontSize, options) { var fullPath = new Path2(); this.forEachGlyph(text, x, 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(text, x, y, fontSize, options) { var glyphPaths = []; this.forEachGlyph(text, x, 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(text, fontSize, options) { return this.forEachGlyph(text, 0, 0, fontSize, options, function() { }); }; Font2.prototype.draw = function(ctx, text, x, y, fontSize, options) { this.getPath(text, x, y, fontSize, options).draw(ctx); }; Font2.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawPoints(ctx, gX, gY, gFontSize); }); }; Font2.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawMetrics(ctx, gX, gY, gFontSize); }); }; Font2.prototype.getEnglishName = function(name) { var translations = this.names[name]; if (translations) { return translations.en; } }; Font2.prototype.validate = function() { var _this = this; function assert(predicate) { } function assertNamePresent(name) { var englishName = _this.getEnglishName(name); 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 buffer2 = new ArrayBuffer(bytes.length); var intArray = new Uint8Array(buffer2); for (var i4 = 0; i4 < bytes.length; i4++) { intArray[i4] = bytes[i4]; } return buffer2; }; 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(name, names) { var nameString = JSON.stringify(name); 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] = name; 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(data, start, names) { var axis = {}; var p2 = new parse2.Parser(data, start); axis.tag = p2.parseTag(); axis.minValue = p2.parseFixed(); axis.defaultValue = p2.parseFixed(); axis.maxValue = p2.parseFixed(); p2.skip("uShort", 1); axis.name = names[p2.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 i4 = 0; i4 < axes.length; ++i4) { var axisTag = axes[i4].tag; fields.push({ name: "axis_" + n2 + " " + axisTag, type: "FIXED", value: inst.coordinates[axisTag] << 16 }); } return fields; } function parseFvarInstance(data, start, axes, names) { var inst = {}; var p2 = new parse2.Parser(data, start); inst.name = names[p2.parseUShort()] || {}; p2.skip("uShort", 1); inst.coordinates = {}; for (var i4 = 0; i4 < axes.length; ++i4) { inst.coordinates[axes[i4].tag] = p2.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 i4 = 0; i4 < fvar2.axes.length; i4++) { result.fields = result.fields.concat(makeFvarAxis(i4, fvar2.axes[i4], names)); } for (var j = 0; j < fvar2.instances.length; j++) { result.fields = result.fields.concat(makeFvarInstance(j, fvar2.instances[j], fvar2.axes, names)); } return result; } function parseFvarTable(data, start, names) { var p2 = new parse2.Parser(data, start); var tableVersion = p2.parseULong(); check.argument(tableVersion === 65536, "Unsupported fvar table version."); var offsetToData = p2.parseOffset16(); p2.skip("uShort", 1); var axisCount = p2.parseUShort(); var axisSize = p2.parseUShort(); var instanceCount = p2.parseUShort(); var instanceSize = p2.parseUShort(); var axes = []; for (var i4 = 0; i4 < axisCount; i4++) { axes.push(parseFvarAxis(data, start + offsetToData + i4 * axisSize, names)); } var instances = []; var instanceStart = start + offsetToData + axisCount * axisSize; for (var j = 0; j < instanceCount; j++) { instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names)); } return { axes, instances }; } var fvar = { make: makeFvarTable, parse: parseFvarTable }; var attachList = function() { return { coverage: this.parsePointer(Parser2.coverage), attachPoints: this.parseList(Parser2.pointer(Parser2.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(Parser2.pointer(caretValue)); }; var ligCaretList = function() { return { coverage: this.parsePointer(Parser2.coverage), ligGlyphs: this.parseList(Parser2.pointer(ligGlyph)) }; }; var markGlyphSets = function() { this.parseUShort(); return this.parseList(Parser2.pointer(Parser2.coverage)); }; function parseGDEFTable(data, start) { start = start || 0; var p2 = new Parser2(data, start); var tableVersion = p2.parseVersion(1); check.argument( tableVersion === 1 || tableVersion === 1.2 || tableVersion === 1.3, "Unsupported GDEF table version." ); var gdef2 = { version: tableVersion, classDef: p2.parsePointer(Parser2.classDef), attachList: p2.parsePointer(attachList), ligCaretList: p2.parsePointer(ligCaretList), markAttachClassDef: p2.parsePointer(Parser2.classDef) }; if (tableVersion >= 1.2) { gdef2.markGlyphSets = p2.parsePointer(markGlyphSets); } return gdef2; } var gdef = { parse: parseGDEFTable }; var subtableParsers$1 = new Array(10); subtableParsers$1[1] = function parseLookup1() { var start = this.offset + this.relativeOffset; var posformat = this.parseUShort(); if (posformat === 1) { return { posFormat: 1, coverage: this.parsePointer(Parser2.coverage), value: this.parseValueRecord() }; } else if (posformat === 2) { return { posFormat: 2, coverage: this.parsePointer(Parser2.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 parseLookup2() { 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(Parser2.coverage); var valueFormat1 = this.parseUShort(); var valueFormat2 = this.parseUShort(); if (posFormat === 1) { return { posFormat, coverage, valueFormat1, valueFormat2, pairSets: this.parseList( Parser2.pointer( Parser2.list(function() { return { // pairValueRecord secondGlyph: this.parseUShort(), value1: this.parseValueRecord(valueFormat1), value2: this.parseValueRecord(valueFormat2) }; }) ) ) }; } else if (posFormat === 2) { var classDef1 = this.parsePointer(Parser2.classDef); var classDef2 = this.parsePointer(Parser2.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, Parser2.list(class2Count, function() { return { value1: this.parseValueRecord(valueFormat1), value2: this.parseValueRecord(valueFormat2) }; }) ) }; } }; subtableParsers$1[3] = function parseLookup3() { return { error: "GPOS Lookup 3 not supported" }; }; subtableParsers$1[4] = function parseLookup4() { return { error: "GPOS Lookup 4 not supported" }; }; subtableParsers$1[5] = function parseLookup5() { return { error: "GPOS Lookup 5 not supported" }; }; subtableParsers$1[6] = function parseLookup6() { return { error: "GPOS Lookup 6 not supported" }; }; subtableParsers$1[7] = function parseLookup7() { return { error: "GPOS Lookup 7 not supported" }; }; subtableParsers$1[8] = function parseLookup8() { return { error: "GPOS Lookup 8 not supported" }; }; subtableParsers$1[9] = function parseLookup9() { return { error: "GPOS Lookup 9 not supported" }; }; function parseGposTable(data, start) { start = start || 0; var p2 = new Parser2(data, start); var tableVersion = p2.parseVersion(1); check.argument(tableVersion === 1 || tableVersion === 1.1, "Unsupported GPOS table version " + tableVersion); if (tableVersion === 1) { return { version: tableVersion, scripts: p2.parseScriptList(), features: p2.parseFeatureList(), lookups: p2.parseLookupList(subtableParsers$1) }; } else { return { version: tableVersion, scripts: p2.parseScriptList(), features: p2.parseFeatureList(), lookups: p2.parseLookupList(subtableParsers$1), variations: p2.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(p2) { var pairs = {}; p2.skip("uShort"); var subtableVersion = p2.parseUShort(); check.argument(subtableVersion === 0, "Unsupported kern sub-table version."); p2.skip("uShort", 2); var nPairs = p2.parseUShort(); p2.skip("uShort", 3); for (var i4 = 0; i4 < nPairs; i4 += 1) { var leftIndex = p2.parseUShort(); var rightIndex = p2.parseUShort(); var value = p2.parseShort(); pairs[leftIndex + "," + rightIndex] = value; } return pairs; } function parseMacKernTable(p2) { var pairs = {}; p2.skip("uShort"); var nTables = p2.parseULong(); if (nTables > 1) { console.warn("Only the first kern subtable is supported."); } p2.skip("uLong"); var coverage = p2.parseUShort(); var subtableVersion = coverage & 255; p2.skip("uShort"); if (subtableVersion === 0) { var nPairs = p2.parseUShort(); p2.skip("uShort", 3); for (var i4 = 0; i4 < nPairs; i4 += 1) { var leftIndex = p2.parseUShort(); var rightIndex = p2.parseUShort(); var value = p2.parseShort(); pairs[leftIndex + "," + rightIndex] = value; } } return pairs; } function parseKernTable(data, start) { var p2 = new parse2.Parser(data, start); var tableVersion = p2.parseUShort(); if (tableVersion === 0) { return parseWindowsKernTable(p2); } else if (tableVersion === 1) { return parseMacKernTable(p2); } else { throw new Error("Unsupported kern table version (" + tableVersion + ")."); } } var kern = { parse: parseKernTable }; function parseLocaTable(data, start, numGlyphs, shortVersion) { var p2 = new parse2.Parser(data, start); var parseFn = shortVersion ? p2.parseUShort : p2.parseULong; var glyphOffsets = []; for (var i4 = 0; i4 < numGlyphs + 1; i4 += 1) { var glyphOffset = parseFn.call(p2); if (shortVersion) { glyphOffset *= 2; } glyphOffsets.push(glyphOffset); } return glyphOffsets; } var loca = { parse: parseLocaTable }; function parseOpenTypeTableEntries(data, numTables) { var tableEntries = []; var p2 = 12; for (var i4 = 0; i4 < numTables; i4 += 1) { var tag = parse2.getTag(data, p2); var checksum = parse2.getULong(data, p2 + 4); var offset = parse2.getULong(data, p2 + 8); var length3 = parse2.getULong(data, p2 + 12); tableEntries.push({ tag, checksum, offset, length: length3, compression: false }); p2 += 16; } return tableEntries; } function parseWOFFTableEntries(data, numTables) { var tableEntries = []; var p2 = 44; for (var i4 = 0; i4 < numTables; i4 += 1) { var tag = parse2.getTag(data, p2); var offset = parse2.getULong(data, p2 + 4); var compLength = parse2.getULong(data, p2 + 8); var origLength = parse2.getULong(data, p2 + 12); var compression = void 0; if (compLength < origLength) { compression = "WOFF"; } else { compression = false; } tableEntries.push({ tag, offset, compression, compressedLength: compLength, length: origLength }); p2 += 20; } return tableEntries; } function uncompressTable(data, tableEntry) { if (tableEntry.compression === "WOFF") { var inBuffer = new Uint8Array(data.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, offset: tableEntry.offset }; } } function parseBuffer2(buffer2, opt) { opt = opt === void 0 || opt === null ? {} : opt; var indexToLocFormat; var ltagTable; var font = new Font2({ empty: true }); var data = new DataView(buffer2, 0); var numTables; var tableEntries = []; var signature = parse2.getTag(data, 0); if (signature === String.fromCharCode(0, 1, 0, 0) || signature === "true" || signature === "typ1") { font.outlinesFormat = "truetype"; numTables = parse2.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === "OTTO") { font.outlinesFormat = "cff"; numTables = parse2.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === "wOFF") { var flavor = parse2.getTag(data, 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 = parse2.getUShort(data, 12); tableEntries = parseWOFFTableEntries(data, 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 p2; for (var i4 = 0; i4 < numTables; i4 += 1) { var tableEntry = tableEntries[i4]; var table2 = void 0; switch (tableEntry.tag) { case "cmap": table2 = uncompressTable(data, tableEntry); font.tables.cmap = cmap.parse(table2.data, table2.offset); font.encoding = new CmapEncoding(font.tables.cmap); break; case "cvt ": table2 = uncompressTable(data, tableEntry); p2 = new parse2.Parser(table2.data, table2.offset); font.tables.cvt = p2.parseShortList(tableEntry.length / 2); break; case "fvar": fvarTableEntry = tableEntry; break; case "fpgm": table2 = uncompressTable(data, tableEntry); p2 = new parse2.Parser(table2.data, table2.offset); font.tables.fpgm = p2.parseByteList(tableEntry.length); break; case "head": table2 = uncompressTable(data, 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(data, 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(data, tableEntry); ltagTable = ltag.parse(table2.data, table2.offset); break; case "maxp": table2 = uncompressTable(data, 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(data, tableEntry); font.tables.os2 = os2.parse(table2.data, table2.offset); break; case "post": table2 = uncompressTable(data, tableEntry); font.tables.post = post.parse(table2.data, table2.offset); font.glyphNames = new GlyphNames(font.tables.post); break; case "prep": table2 = uncompressTable(data, tableEntry); p2 = new parse2.Parser(table2.data, table2.offset); font.tables.prep = p2.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(data, 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(data, locaTableEntry); var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion); var glyfTable = uncompressTable(data, glyfTableEntry); font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font, opt); } else if (cffTableEntry) { var cffTable = uncompressTable(data, cffTableEntry); cff.parse(cffTable.data, cffTable.offset, font, opt); } else { throw new Error("Font doesn't contain TrueType or CFF outlines."); } var hmtxTable = uncompressTable(data, hmtxTableEntry); hmtx.parse(font, hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs, opt); addGlyphNames(font, opt); if (kernTableEntry) { var kernTable = uncompressTable(data, kernTableEntry); font.kerningPairs = kern.parse(kernTable.data, kernTable.offset); } else { font.kerningPairs = {}; } if (gdefTableEntry) { var gdefTable = uncompressTable(data, gdefTableEntry); font.tables.gdef = gdef.parse(gdefTable.data, gdefTable.offset); } if (gposTableEntry) { var gposTable = uncompressTable(data, gposTableEntry); font.tables.gpos = gpos.parse(gposTable.data, gposTable.offset); font.position.init(); } if (gsubTableEntry) { var gsubTable = uncompressTable(data, gsubTableEntry); font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset); } if (fvarTableEntry) { var fvarTable = uncompressTable(data, fvarTableEntry); font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names); } if (metaTableEntry) { var metaTable = uncompressTable(data, metaTableEntry); font.tables.meta = meta.parse(metaTable.data, metaTable.offset); font.metas = font.tables.meta; } return font; } return { parseBuffer: parseBuffer2 }; })(); // node_modules/three-stdlib/loaders/RGBELoader.js var RGBELoader = class extends DataTextureLoader { constructor(manager) { super(manager); this.type = HalfFloatType; } // adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html parse(buffer2) { 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(buffer22, lineLimit, consume) { const chunkSize = 128; lineLimit = !lineLimit ? 1024 : lineLimit; let p2 = buffer22.pos, i4 = -1, len = 0, s2 = "", chunk = String.fromCharCode.apply(null, new Uint16Array(buffer22.subarray(p2, p2 + chunkSize))); while (0 > (i4 = chunk.indexOf(NEWLINE)) && len < lineLimit && p2 < buffer22.byteLength) { s2 += chunk; len += chunk.length; p2 += chunkSize; chunk += String.fromCharCode.apply(null, new Uint16Array(buffer22.subarray(p2, p2 + chunkSize))); } if (-1 < i4) { if (false !== consume) buffer22.pos += len + i4 + 1; return s2 + chunk.slice(0, i4); } return false; }, RGBE_ReadHeader = function(buffer22) { 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, string: "", comments: "", programtype: "RGBE", format: "", gamma: 1, exposure: 1, width: 0, height: 0 }; let line, match; if (buffer22.pos >= buffer22.byteLength || !(line = fgets(buffer22))) { rgbe_error(rgbe_read_error, "no header found"); } if (!(match = line.match(magic_token_re))) { rgbe_error(rgbe_format_error, "bad initial token"); } header.valid |= RGBE_VALID_PROGRAMTYPE; header.programtype = match[1]; header.string += line + "\n"; while (true) { line = fgets(buffer22); if (false === line) break; header.string += line + "\n"; if ("#" === line.charAt(0)) { header.comments += line + "\n"; continue; } if (match = line.match(gamma_re)) { header.gamma = parseFloat(match[1]); } if (match = line.match(exposure_re)) { header.exposure = parseFloat(match[1]); } if (match = line.match(format_re)) { header.valid |= RGBE_VALID_FORMAT; header.format = match[1]; } if (match = line.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(buffer22, 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 !== buffer22[0] || 2 !== buffer22[1] || buffer22[2] & 128 ) { return new Uint8Array(buffer22); } if (scanline_width !== (buffer22[2] << 8 | buffer22[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 < buffer22.byteLength) { if (pos + 4 > buffer22.byteLength) { rgbe_error(rgbe_read_error); } rgbeStart[0] = buffer22[pos++]; rgbeStart[1] = buffer22[pos++]; rgbeStart[2] = buffer22[pos++]; rgbeStart[3] = buffer22[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 < buffer22.byteLength) { count = buffer22[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 = buffer22[pos++]; for (let i4 = 0; i4 < count; i4++) { scanline_buffer[ptr++] = byteValue; } } else { scanline_buffer.set(buffer22.subarray(pos, pos + count), ptr); ptr += count; pos += count; } } const l2 = scanline_width; for (let i4 = 0; i4 < l2; i4++) { let off = 0; data_rgba[offset] = scanline_buffer[i4 + off]; off += scanline_width; data_rgba[offset + 1] = scanline_buffer[i4 + off]; off += scanline_width; data_rgba[offset + 2] = scanline_buffer[i4 + off]; off += scanline_width; data_rgba[offset + 3] = scanline_buffer[i4 + off]; offset += 4; } num_scanlines--; } return data_rgba; }; const RGBEByteToRGBFloat = function(sourceArray, sourceOffset, destArray, destOffset) { const e2 = sourceArray[sourceOffset + 3]; const scale5 = Math.pow(2, e2 - 128) / 255; destArray[destOffset + 0] = sourceArray[sourceOffset + 0] * scale5; destArray[destOffset + 1] = sourceArray[sourceOffset + 1] * scale5; destArray[destOffset + 2] = sourceArray[sourceOffset + 2] * scale5; destArray[destOffset + 3] = 1; }; const RGBEByteToRGBHalf = function(sourceArray, sourceOffset, destArray, destOffset) { const e2 = sourceArray[sourceOffset + 3]; const scale5 = Math.pow(2, e2 - 128) / 255; destArray[destOffset + 0] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 0] * scale5, 65504)); destArray[destOffset + 1] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 1] * scale5, 65504)); destArray[destOffset + 2] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 2] * scale5, 65504)); destArray[destOffset + 3] = DataUtils.toHalfFloat(1); }; const byteArray = new Uint8Array(buffer2); 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 data, type; let numElements; switch (this.type) { case FloatType: numElements = image_rgba_data.length / 4; const floatArray = new Float32Array(numElements * 4); for (let j = 0; j < numElements; j++) { RGBEByteToRGBFloat(image_rgba_data, j * 4, floatArray, j * 4); } data = floatArray; type = FloatType; break; case HalfFloatType: numElements = image_rgba_data.length / 4; const halfArray = new Uint16Array(numElements * 4); for (let j = 0; j < numElements; j++) { RGBEByteToRGBHalf(image_rgba_data, j * 4, halfArray, j * 4); } data = halfArray; type = HalfFloatType; break; default: throw new Error("THREE.RGBELoader: Unsupported type: " + this.type); } return { width: w, height: h, data, header: rgbe_header_info.string, gamma: rgbe_header_info.gamma, exposure: rgbe_header_info.exposure, type }; } setDataType(value) { this.type = value; return this; } load(url, onLoad, onProgress, onError) { function onLoadCallback(texture, texData) { switch (texture.type) { case FloatType: case HalfFloatType: if ("colorSpace" in texture) texture.colorSpace = "srgb-linear"; else texture.encoding = 3e3; 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-stdlib/loaders/EXRLoader.js var hasColorSpace = version >= 152; var EXRLoader = class extends DataTextureLoader { constructor(manager) { super(manager); this.type = HalfFloatType; } parse(buffer2) { 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) { var k = 0; for (var i4 = 0; i4 < USHORT_RANGE; ++i4) { if (i4 == 0 || bitmap[i4 >> 3] & 1 << (i4 & 7)) { lut[k++] = i4; } } var n2 = k - 1; while (k < USHORT_RANGE) lut[k++] = 0; return n2; } function hufClearDecTable(hdec) { for (var i4 = 0; i4 < HUF_DECSIZE; i4++) { hdec[i4] = {}; hdec[i4].len = 0; hdec[i4].lit = 0; hdec[i4].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 (var i4 = 0; i4 <= 58; ++i4) hufTableBuffer[i4] = 0; for (var i4 = 0; i4 < HUF_ENCSIZE; ++i4) hufTableBuffer[hcode[i4]] += 1; var c2 = 0; for (var i4 = 58; i4 > 0; --i4) { var nc = c2 + hufTableBuffer[i4] >> 1; hufTableBuffer[i4] = c2; c2 = nc; } for (var i4 = 0; i4 < HUF_ENCSIZE; ++i4) { var l2 = hcode[i4]; if (l2 > 0) hcode[i4] = l2 | hufTableBuffer[l2]++ << 6; } } function hufUnpackEncTable(uInt8Array2, inDataView, inOffset, ni, im, iM, hcode) { var p2 = inOffset; var c2 = 0; var lc2 = 0; for (; im <= iM; im++) { if (p2.value - inOffset.value > ni) return false; getBits(6, c2, lc2, uInt8Array2, p2); var l2 = getBitsReturn.l; c2 = getBitsReturn.c; lc2 = getBitsReturn.lc; hcode[im] = l2; if (l2 == LONG_ZEROCODE_RUN) { if (p2.value - inOffset.value > ni) { throw "Something wrong with hufUnpackEncTable"; } getBits(8, c2, lc2, uInt8Array2, p2); var zerun = getBitsReturn.l + SHORTEST_LONG_RUN; c2 = getBitsReturn.c; lc2 = getBitsReturn.lc; if (im + zerun > iM + 1) { throw "Something wrong with hufUnpackEncTable"; } while (zerun--) hcode[im++] = 0; im--; } else if (l2 >= SHORT_ZEROCODE_RUN) { var zerun = l2 - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) { throw "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++) { var c2 = hufCode(hcode[im]); var l2 = hufLength(hcode[im]); if (c2 >> l2) { throw "Invalid table entry"; } if (l2 > HUF_DECBITS) { var pl = hdecod[c2 >> l2 - HUF_DECBITS]; if (pl.len) { throw "Invalid table entry"; } pl.lit++; if (pl.p) { var p2 = pl.p; pl.p = new Array(pl.lit); for (var i4 = 0; i4 < pl.lit - 1; ++i4) { pl.p[i4] = p2[i4]; } } else { pl.p = new Array(1); } pl.p[pl.lit - 1] = im; } else if (l2) { var plOffset = 0; for (var i4 = 1 << HUF_DECBITS - l2; i4 > 0; i4--) { var pl = hdecod[(c2 << HUF_DECBITS - l2) + plOffset]; if (pl.len || pl.p) { throw "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, inDataView, inOffset, outBuffer, outBufferOffset, outBufferEndOffset) { if (po == rlc) { if (lc2 < 8) { getChar(c2, lc2, uInt8Array2, inOffset); c2 = getCharReturn.c; lc2 = getCharReturn.lc; } lc2 -= 8; var cs = c2 >> lc2; var cs = new Uint8Array([cs])[0]; if (outBufferOffset.value + cs > outBufferEndOffset) { return false; } var s2 = outBuffer[outBufferOffset.value - 1]; while (cs-- > 0) { outBuffer[outBufferOffset.value++] = s2; } } else if (outBufferOffset.value < outBufferEndOffset) { outBuffer[outBufferOffset.value++] = po; } else { return false; } getCodeReturn.c = c2; getCodeReturn.lc = lc2; } function UInt16(value) { return value & 65535; } function Int16(value) { var ref = UInt16(value); return ref > 32767 ? ref - 65536 : ref; } const wdec14Return = { a: 0, b: 0 }; function wdec14(l2, h) { var ls = Int16(l2); var hs = Int16(h); var hi = hs; var ai = ls + (hi & 1) + (hi >> 1); var as = ai; var bs = ai - hi; wdec14Return.a = as; wdec14Return.b = bs; } function wdec16(l2, h) { var m = UInt16(l2); var d2 = UInt16(h); var bb2 = m - (d2 >> 1) & MOD_MASK; var aa = d2 + bb2 - A_OFFSET & MOD_MASK; wdec14Return.a = aa; wdec14Return.b = bb2; } function wav2Decode(buffer22, j, nx, ox, ny, oy, mx) { var w14 = mx < 1 << 14; var n2 = nx > ny ? ny : nx; var p2 = 1; var p22; while (p2 <= n2) p2 <<= 1; p2 >>= 1; p22 = p2; p2 >>= 1; while (p2 >= 1) { var py = 0; var ey = py + oy * (ny - p22); var oy1 = oy * p2; var oy2 = oy * p22; var ox1 = ox * p2; var ox2 = ox * p22; var i00, i01, i10, i11; for (; py <= ey; py += oy2) { var px = py; var ex = py + ox * (nx - p22); for (; px <= ex; px += ox2) { var p01 = px + ox1; var p10 = px + oy1; var p11 = p10 + ox1; if (w14) { wdec14(buffer22[px + j], buffer22[p10 + j]); i00 = wdec14Return.a; i10 = wdec14Return.b; wdec14(buffer22[p01 + j], buffer22[p11 + j]); i01 = wdec14Return.a; i11 = wdec14Return.b; wdec14(i00, i01); buffer22[px + j] = wdec14Return.a; buffer22[p01 + j] = wdec14Return.b; wdec14(i10, i11); buffer22[p10 + j] = wdec14Return.a; buffer22[p11 + j] = wdec14Return.b; } else { wdec16(buffer22[px + j], buffer22[p10 + j]); i00 = wdec14Return.a; i10 = wdec14Return.b; wdec16(buffer22[p01 + j], buffer22[p11 + j]); i01 = wdec14Return.a; i11 = wdec14Return.b; wdec16(i00, i01); buffer22[px + j] = wdec14Return.a; buffer22[p01 + j] = wdec14Return.b; wdec16(i10, i11); buffer22[p10 + j] = wdec14Return.a; buffer22[p11 + j] = wdec14Return.b; } } if (nx & p2) { var p10 = px + oy1; if (w14) wdec14(buffer22[px + j], buffer22[p10 + j]); else wdec16(buffer22[px + j], buffer22[p10 + j]); i00 = wdec14Return.a; buffer22[p10 + j] = wdec14Return.b; buffer22[px + j] = i00; } } if (ny & p2) { var px = py; var ex = py + ox * (nx - p22); for (; px <= ex; px += ox2) { var p01 = px + ox1; if (w14) wdec14(buffer22[px + j], buffer22[p01 + j]); else wdec16(buffer22[px + j], buffer22[p01 + j]); i00 = wdec14Return.a; buffer22[p01 + j] = wdec14Return.b; buffer22[px + j] = i00; } } p22 = p2; p2 >>= 1; } return py; } function hufDecode(encodingTable, decodingTable, uInt8Array2, inDataView, inOffset, ni, rlc, no, outBuffer, outOffset) { var c2 = 0; var lc2 = 0; var outBufferEndOffset = no; var 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) { var index2 = c2 >> lc2 - HUF_DECBITS & HUF_DECMASK; var pl = decodingTable[index2]; if (pl.len) { lc2 -= pl.len; getCode(pl.lit, rlc, c2, lc2, uInt8Array2, inDataView, inOffset, outBuffer, outOffset, outBufferEndOffset); c2 = getCodeReturn.c; lc2 = getCodeReturn.lc; } else { if (!pl.p) { throw "hufDecode issues"; } var j; for (j = 0; j < pl.lit; j++) { var l2 = hufLength(encodingTable[pl.p[j]]); 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[j]]) == (c2 >> lc2 - l2 & (1 << l2) - 1)) { lc2 -= l2; getCode( pl.p[j], rlc, c2, lc2, uInt8Array2, inDataView, inOffset, outBuffer, outOffset, outBufferEndOffset ); c2 = getCodeReturn.c; lc2 = getCodeReturn.lc; break; } } } if (j == pl.lit) { throw "hufDecode issues"; } } } } var i4 = 8 - ni & 7; c2 >>= i4; lc2 -= i4; while (lc2 > 0) { var pl = decodingTable[c2 << HUF_DECBITS - lc2 & HUF_DECMASK]; if (pl.len) { lc2 -= pl.len; getCode(pl.lit, rlc, c2, lc2, uInt8Array2, inDataView, inOffset, outBuffer, outOffset, outBufferEndOffset); c2 = getCodeReturn.c; lc2 = getCodeReturn.lc; } else { throw "hufDecode issues"; } } return true; } function hufUncompress(uInt8Array2, inDataView, inOffset, nCompressed, outBuffer, nRaw) { var outOffset = { value: 0 }; var initialInOffset = inOffset.value; var im = parseUint32(inDataView, inOffset); var iM = parseUint32(inDataView, inOffset); inOffset.value += 4; var nBits = parseUint32(inDataView, inOffset); inOffset.value += 4; if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) { throw "Something wrong with HUF_ENCSIZE"; } var freq = new Array(HUF_ENCSIZE); var hdec = new Array(HUF_DECSIZE); hufClearDecTable(hdec); var ni = nCompressed - (inOffset.value - initialInOffset); hufUnpackEncTable(uInt8Array2, inDataView, inOffset, ni, im, iM, freq); if (nBits > 8 * (nCompressed - (inOffset.value - initialInOffset))) { throw "Something wrong with hufUncompress"; } hufBuildDecTable(freq, im, iM, hdec); hufDecode(freq, hdec, uInt8Array2, inDataView, inOffset, nBits, iM, nRaw, outBuffer, outOffset); } function applyLut(lut, data, nData) { for (var i4 = 0; i4 < nData; ++i4) { data[i4] = lut[data[i4]]; } } function predictor(source) { for (var t3 = 1; t3 < source.length; t3++) { var d2 = source[t3 - 1] + source[t3] - 128; source[t3] = d2; } } function interleaveScalar(source, out7) { var t1 = 0; var t22 = Math.floor((source.length + 1) / 2); var s2 = 0; var stop = source.length - 1; while (true) { if (s2 > stop) break; out7[s2++] = source[t1++]; if (s2 > stop) break; out7[s2++] = source[t22++]; } } function decodeRunLength(source) { var size2 = source.byteLength; var out7 = new Array(); var p2 = 0; var reader = new DataView(source); while (size2 > 0) { var l2 = reader.getInt8(p2++); if (l2 < 0) { var count = -l2; size2 -= count + 1; for (var i4 = 0; i4 < count; i4++) { out7.push(reader.getUint8(p2++)); } } else { var count = l2; size2 -= 2; var value = reader.getUint8(p2++); for (var i4 = 0; i4 < count + 1; i4++) { out7.push(value); } } } return out7; } function lossyDctDecode(cscSet, rowPtrs, channelData, acBuffer, dcBuffer, outBuffer) { var dataView = new DataView(outBuffer.buffer); var width = channelData[cscSet.idx[0]].width; var height = channelData[cscSet.idx[0]].height; var numComp = 3; var numFullBlocksX = Math.floor(width / 8); var numBlocksX = Math.ceil(width / 8); var numBlocksY = Math.ceil(height / 8); var leftoverX = width - (numBlocksX - 1) * 8; var leftoverY = height - (numBlocksY - 1) * 8; var currAcComp = { value: 0 }; var currDcComp = new Array(numComp); var dctData = new Array(numComp); var halfZigBlock = new Array(numComp); var rowBlock = new Array(numComp); var 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) { var maxY = 8; if (blocky == numBlocksY - 1) maxY = leftoverY; var 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]); } { 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 type2 = channelData[cscSet.idx[comp2]].type; for (let y2 = 8 * blocky; y2 < 8 * blocky + maxY; ++y2) { offset2 = rowOffsets[comp2][y2]; for (let blockx = 0; blockx < numFullBlocksX; ++blockx) { const src = blockx * 64 + (y2 & 7) * 8; dataView.setUint16(offset2 + 0 * INT16_SIZE * type2, rowBlock[comp2][src + 0], true); dataView.setUint16(offset2 + 1 * INT16_SIZE * type2, rowBlock[comp2][src + 1], true); dataView.setUint16(offset2 + 2 * INT16_SIZE * type2, rowBlock[comp2][src + 2], true); dataView.setUint16(offset2 + 3 * INT16_SIZE * type2, rowBlock[comp2][src + 3], true); dataView.setUint16(offset2 + 4 * INT16_SIZE * type2, rowBlock[comp2][src + 4], true); dataView.setUint16(offset2 + 5 * INT16_SIZE * type2, rowBlock[comp2][src + 5], true); dataView.setUint16(offset2 + 6 * INT16_SIZE * type2, rowBlock[comp2][src + 6], true); dataView.setUint16(offset2 + 7 * INT16_SIZE * type2, rowBlock[comp2][src + 7], true); offset2 += 8 * INT16_SIZE * type2; } } if (numFullBlocksX != numBlocksX) { for (let y2 = 8 * blocky; y2 < 8 * blocky + maxY; ++y2) { const offset3 = rowOffsets[comp2][y2] + 8 * numFullBlocksX * INT16_SIZE * type2; const src = numFullBlocksX * 64 + (y2 & 7) * 8; for (let x2 = 0; x2 < maxX; ++x2) { dataView.setUint16(offset3 + x2 * INT16_SIZE * type2, rowBlock[comp2][src + x2], true); } } } } } var halfRow = new Uint16Array(width); var dataView = new DataView(outBuffer.buffer); for (var comp = 0; comp < numComp; ++comp) { channelData[cscSet.idx[comp]].decoded = true; var type = channelData[cscSet.idx[comp]].type; if (channelData[comp].type != 2) continue; for (var y = 0; y < height; ++y) { const offset2 = rowOffsets[comp][y]; for (var x = 0; x < width; ++x) { halfRow[x] = dataView.getUint16(offset2 + x * INT16_SIZE * type, true); } for (var x = 0; x < width; ++x) { dataView.setFloat32(offset2 + x * INT16_SIZE * type, decodeFloat16(halfRow[x]), true); } } } } function unRleAC(currAcComp, acBuffer, halfZigBlock) { var acValue; var 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] = decodeFloat16(src[0]); dst[1] = decodeFloat16(src[1]); dst[2] = decodeFloat16(src[5]); dst[3] = decodeFloat16(src[6]); dst[4] = decodeFloat16(src[14]); dst[5] = decodeFloat16(src[15]); dst[6] = decodeFloat16(src[27]); dst[7] = decodeFloat16(src[28]); dst[8] = decodeFloat16(src[2]); dst[9] = decodeFloat16(src[4]); dst[10] = decodeFloat16(src[7]); dst[11] = decodeFloat16(src[13]); dst[12] = decodeFloat16(src[16]); dst[13] = decodeFloat16(src[26]); dst[14] = decodeFloat16(src[29]); dst[15] = decodeFloat16(src[42]); dst[16] = decodeFloat16(src[3]); dst[17] = decodeFloat16(src[8]); dst[18] = decodeFloat16(src[12]); dst[19] = decodeFloat16(src[17]); dst[20] = decodeFloat16(src[25]); dst[21] = decodeFloat16(src[30]); dst[22] = decodeFloat16(src[41]); dst[23] = decodeFloat16(src[43]); dst[24] = decodeFloat16(src[9]); dst[25] = decodeFloat16(src[11]); dst[26] = decodeFloat16(src[18]); dst[27] = decodeFloat16(src[24]); dst[28] = decodeFloat16(src[31]); dst[29] = decodeFloat16(src[40]); dst[30] = decodeFloat16(src[44]); dst[31] = decodeFloat16(src[53]); dst[32] = decodeFloat16(src[10]); dst[33] = decodeFloat16(src[19]); dst[34] = decodeFloat16(src[23]); dst[35] = decodeFloat16(src[32]); dst[36] = decodeFloat16(src[39]); dst[37] = decodeFloat16(src[45]); dst[38] = decodeFloat16(src[52]); dst[39] = decodeFloat16(src[54]); dst[40] = decodeFloat16(src[20]); dst[41] = decodeFloat16(src[22]); dst[42] = decodeFloat16(src[33]); dst[43] = decodeFloat16(src[38]); dst[44] = decodeFloat16(src[46]); dst[45] = decodeFloat16(src[51]); dst[46] = decodeFloat16(src[55]); dst[47] = decodeFloat16(src[60]); dst[48] = decodeFloat16(src[21]); dst[49] = decodeFloat16(src[34]); dst[50] = decodeFloat16(src[37]); dst[51] = decodeFloat16(src[47]); dst[52] = decodeFloat16(src[50]); dst[53] = decodeFloat16(src[56]); dst[54] = decodeFloat16(src[59]); dst[55] = decodeFloat16(src[61]); dst[56] = decodeFloat16(src[35]); dst[57] = decodeFloat16(src[36]); dst[58] = decodeFloat16(src[48]); dst[59] = decodeFloat16(src[49]); dst[60] = decodeFloat16(src[57]); dst[61] = decodeFloat16(src[58]); dst[62] = decodeFloat16(src[62]); dst[63] = decodeFloat16(src[63]); } function dctInverse(data) { const a6 = 0.5 * Math.cos(3.14159 / 4); const b5 = 0.5 * Math.cos(3.14159 / 16); const c2 = 0.5 * Math.cos(3.14159 / 8); const d2 = 0.5 * Math.cos(3 * 3.14159 / 16); const e2 = 0.5 * Math.cos(5 * 3.14159 / 16); const f2 = 0.5 * Math.cos(3 * 3.14159 / 8); const g = 0.5 * Math.cos(7 * 3.14159 / 16); var alpha = new Array(4); var beta = new Array(4); var theta = new Array(4); var gamma = new Array(4); for (var row = 0; row < 8; ++row) { var rowPtr = row * 8; alpha[0] = c2 * data[rowPtr + 2]; alpha[1] = f2 * data[rowPtr + 2]; alpha[2] = c2 * data[rowPtr + 6]; alpha[3] = f2 * data[rowPtr + 6]; beta[0] = b5 * data[rowPtr + 1] + d2 * data[rowPtr + 3] + e2 * data[rowPtr + 5] + g * data[rowPtr + 7]; beta[1] = d2 * data[rowPtr + 1] - g * data[rowPtr + 3] - b5 * data[rowPtr + 5] - e2 * data[rowPtr + 7]; beta[2] = e2 * data[rowPtr + 1] - b5 * data[rowPtr + 3] + g * data[rowPtr + 5] + d2 * data[rowPtr + 7]; beta[3] = g * data[rowPtr + 1] - e2 * data[rowPtr + 3] + d2 * data[rowPtr + 5] - b5 * data[rowPtr + 7]; theta[0] = a6 * (data[rowPtr + 0] + data[rowPtr + 4]); theta[3] = a6 * (data[rowPtr + 0] - data[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]; data[rowPtr + 0] = gamma[0] + beta[0]; data[rowPtr + 1] = gamma[1] + beta[1]; data[rowPtr + 2] = gamma[2] + beta[2]; data[rowPtr + 3] = gamma[3] + beta[3]; data[rowPtr + 4] = gamma[3] - beta[3]; data[rowPtr + 5] = gamma[2] - beta[2]; data[rowPtr + 6] = gamma[1] - beta[1]; data[rowPtr + 7] = gamma[0] - beta[0]; } for (var column = 0; column < 8; ++column) { alpha[0] = c2 * data[16 + column]; alpha[1] = f2 * data[16 + column]; alpha[2] = c2 * data[48 + column]; alpha[3] = f2 * data[48 + column]; beta[0] = b5 * data[8 + column] + d2 * data[24 + column] + e2 * data[40 + column] + g * data[56 + column]; beta[1] = d2 * data[8 + column] - g * data[24 + column] - b5 * data[40 + column] - e2 * data[56 + column]; beta[2] = e2 * data[8 + column] - b5 * data[24 + column] + g * data[40 + column] + d2 * data[56 + column]; beta[3] = g * data[8 + column] - e2 * data[24 + column] + d2 * data[40 + column] - b5 * data[56 + column]; theta[0] = a6 * (data[column] + data[32 + column]); theta[3] = a6 * (data[column] - data[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]; data[0 + column] = gamma[0] + beta[0]; data[8 + column] = gamma[1] + beta[1]; data[16 + column] = gamma[2] + beta[2]; data[24 + column] = gamma[3] + beta[3]; data[32 + column] = gamma[3] - beta[3]; data[40 + column] = gamma[2] - beta[2]; data[48 + column] = gamma[1] - beta[1]; data[56 + column] = gamma[0] - beta[0]; } } function csc709Inverse(data) { for (var i4 = 0; i4 < 64; ++i4) { var y = data[0][i4]; var cb2 = data[1][i4]; var cr = data[2][i4]; data[0][i4] = y + 1.5747 * cr; data[1][i4] = y - 0.1873 * cb2 - 0.4682 * cr; data[2][i4] = y + 1.8556 * cb2; } } function convertToHalf(src, dst, idx) { for (var i4 = 0; i4 < 64; ++i4) { dst[idx + i4] = DataUtils.toHalfFloat(toLinear(src[i4])); } } 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) { var compressed = info.viewer.buffer.slice(info.offset.value, info.offset.value + info.size); var rawBuffer = new Uint8Array(decodeRunLength(compressed)); var tmpBuffer = new Uint8Array(rawBuffer.length); predictor(rawBuffer); interleaveScalar(rawBuffer, tmpBuffer); return new DataView(tmpBuffer.buffer); } function uncompressZIP(info) { var compressed = info.array.slice(info.offset.value, info.offset.value + info.size); var rawBuffer = unzlibSync(compressed); var tmpBuffer = new Uint8Array(rawBuffer.length); predictor(rawBuffer); interleaveScalar(rawBuffer, tmpBuffer); return new DataView(tmpBuffer.buffer); } function uncompressPIZ(info) { var inDataView = info.viewer; var inOffset = { value: info.offset.value }; var outBuffer = new Uint16Array(info.width * info.scanlineBlockSize * (info.channels * info.type)); var bitmap = new Uint8Array(BITMAP_SIZE); var outBufferEnd = 0; var pizChannelData = new Array(info.channels); for (var i4 = 0; i4 < info.channels; i4++) { pizChannelData[i4] = {}; pizChannelData[i4]["start"] = outBufferEnd; pizChannelData[i4]["end"] = pizChannelData[i4]["start"]; pizChannelData[i4]["nx"] = info.width; pizChannelData[i4]["ny"] = info.lines; pizChannelData[i4]["size"] = info.type; outBufferEnd += pizChannelData[i4].nx * pizChannelData[i4].ny * pizChannelData[i4].size; } var minNonZero = parseUint16(inDataView, inOffset); var maxNonZero = parseUint16(inDataView, inOffset); if (maxNonZero >= BITMAP_SIZE) { throw "Something is wrong with PIZ_COMPRESSION BITMAP_SIZE"; } if (minNonZero <= maxNonZero) { for (var i4 = 0; i4 < maxNonZero - minNonZero + 1; i4++) { bitmap[i4 + minNonZero] = parseUint8(inDataView, inOffset); } } var lut = new Uint16Array(USHORT_RANGE); var maxValue = reverseLutFromBitmap(bitmap, lut); var length3 = parseUint32(inDataView, inOffset); hufUncompress(info.array, inDataView, inOffset, length3, outBuffer, outBufferEnd); for (var i4 = 0; i4 < info.channels; ++i4) { var cd = pizChannelData[i4]; for (var j = 0; j < pizChannelData[i4].size; ++j) { wav2Decode(outBuffer, cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } applyLut(lut, outBuffer, outBufferEnd); var tmpOffset2 = 0; var tmpBuffer = new Uint8Array(outBuffer.buffer.byteLength); for (var y = 0; y < info.lines; y++) { for (var c2 = 0; c2 < info.channels; c2++) { var cd = pizChannelData[c2]; var n2 = cd.nx * cd.size; var cp = new Uint8Array(outBuffer.buffer, cd.end * INT16_SIZE, n2 * INT16_SIZE); tmpBuffer.set(cp, tmpOffset2); tmpOffset2 += n2 * INT16_SIZE; cd.end += n2; } } return new DataView(tmpBuffer.buffer); } function uncompressPXR(info) { var compressed = info.array.slice(info.offset.value, info.offset.value + info.size); var rawBuffer = unzlibSync(compressed); const sz = info.lines * info.channels * info.width; const tmpBuffer = info.type == 1 ? new Uint16Array(sz) : new Uint32Array(sz); 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.channels; c2++) { let pixel = 0; switch (info.type) { case 1: ptr[0] = tmpBufferEnd; ptr[1] = ptr[0] + info.width; tmpBufferEnd = ptr[1] + info.width; for (let j = 0; j < info.width; ++j) { const diff = rawBuffer[ptr[0]++] << 8 | rawBuffer[ptr[1]++]; pixel += diff; tmpBuffer[writePtr] = pixel; writePtr++; } break; case 2: ptr[0] = tmpBufferEnd; ptr[1] = ptr[0] + info.width; ptr[2] = ptr[1] + info.width; tmpBufferEnd = ptr[2] + info.width; for (let j = 0; j < info.width; ++j) { const diff = rawBuffer[ptr[0]++] << 24 | rawBuffer[ptr[1]++] << 16 | rawBuffer[ptr[2]++] << 8; pixel += diff; tmpBuffer[writePtr] = pixel; writePtr++; } break; } } } return new DataView(tmpBuffer.buffer); } function uncompressDWA(info) { var inDataView = info.viewer; var inOffset = { value: info.offset.value }; var outBuffer = new Uint8Array(info.width * info.lines * (info.channels * info.type * INT16_SIZE)); var 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 "EXRLoader.parse: " + EXRHeader.compression + " version " + dwaHeader.version + " is unsupported"; } var channelRules = new Array(); var ruleSize = parseUint16(inDataView, inOffset) - INT16_SIZE; while (ruleSize > 0) { var name = parseNullTerminatedString(inDataView.buffer, inOffset); var value = parseUint8(inDataView, inOffset); var compression = value >> 2 & 3; var csc = (value >> 4) - 1; var index2 = new Int8Array([csc])[0]; var type = parseUint8(inDataView, inOffset); channelRules.push({ name, index: index2, type, compression }); ruleSize -= name.length + 3; } var channels = EXRHeader.channels; var channelData = new Array(info.channels); for (var i4 = 0; i4 < info.channels; ++i4) { var cd = channelData[i4] = {}; var channel = channels[i4]; cd.name = channel.name; cd.compression = UNKNOWN; cd.decoded = false; cd.type = channel.pixelType; cd.pLinear = channel.pLinear; cd.width = info.width; cd.height = info.lines; } var cscSet = { idx: new Array(3) }; for (var offset2 = 0; offset2 < info.channels; ++offset2) { var cd = channelData[offset2]; for (var i4 = 0; i4 < channelRules.length; ++i4) { var rule = channelRules[i4]; if (cd.name == rule.name) { cd.compression = rule.compression; if (rule.index >= 0) { cscSet.idx[rule.index] = offset2; } cd.offset = offset2; } } } if (dwaHeader.acCompressedSize > 0) { switch (dwaHeader.acCompression) { case STATIC_HUFFMAN: var acBuffer = new Uint16Array(dwaHeader.totalAcUncompressedCount); hufUncompress( info.array, inDataView, inOffset, dwaHeader.acCompressedSize, acBuffer, dwaHeader.totalAcUncompressedCount ); break; case DEFLATE: var compressed = info.array.slice(inOffset.value, inOffset.value + dwaHeader.totalAcUncompressedCount); var data = unzlibSync(compressed); var acBuffer = new Uint16Array(data.buffer); inOffset.value += dwaHeader.totalAcUncompressedCount; break; } } if (dwaHeader.dcCompressedSize > 0) { var zlibInfo = { array: info.array, offset: inOffset, size: dwaHeader.dcCompressedSize }; var dcBuffer = new Uint16Array(uncompressZIP(zlibInfo).buffer); inOffset.value += dwaHeader.dcCompressedSize; } if (dwaHeader.rleRawSize > 0) { var compressed = info.array.slice(inOffset.value, inOffset.value + dwaHeader.rleCompressedSize); var data = unzlibSync(compressed); var rleBuffer = decodeRunLength(data.buffer); inOffset.value += dwaHeader.rleCompressedSize; } var outBufferEnd = 0; var rowOffsets = new Array(channelData.length); for (var i4 = 0; i4 < rowOffsets.length; ++i4) { rowOffsets[i4] = new Array(); } for (var y = 0; y < info.lines; ++y) { for (var 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 (var i4 = 0; i4 < channelData.length; ++i4) { var cd = channelData[i4]; if (cd.decoded) continue; switch (cd.compression) { case RLE: var row = 0; var rleOffset = 0; for (var y = 0; y < info.lines; ++y) { var rowOffsetBytes = rowOffsets[i4][row]; for (var x = 0; x < cd.width; ++x) { for (var byte = 0; byte < INT16_SIZE * cd.type; ++byte) { outBuffer[rowOffsetBytes++] = rleBuffer[rleOffset + byte * cd.width * cd.height]; } rleOffset++; } row++; } break; case LOSSY_DCT: default: throw "EXRLoader.parse: unsupported channel compression"; } } return new DataView(outBuffer.buffer); } function parseNullTerminatedString(buffer22, offset2) { var uintBuffer = new Uint8Array(buffer22); var endOffset = 0; while (uintBuffer[offset2.value + endOffset] != 0) { endOffset += 1; } var stringValue = new TextDecoder().decode(uintBuffer.slice(offset2.value, offset2.value + endOffset)); offset2.value = offset2.value + endOffset + 1; return stringValue; } function parseFixedLengthString(buffer22, offset2, size2) { var stringValue = new TextDecoder().decode(new Uint8Array(buffer22).slice(offset2.value, offset2.value + size2)); offset2.value = offset2.value + size2; return stringValue; } function parseRational(dataView, offset2) { var x = parseInt32(dataView, offset2); var y = parseUint32(dataView, offset2); return [x, y]; } function parseTimecode(dataView, offset2) { var x = parseUint32(dataView, offset2); var y = parseUint32(dataView, offset2); return [x, y]; } function parseInt32(dataView, offset2) { var Int32 = dataView.getInt32(offset2.value, true); offset2.value = offset2.value + INT32_SIZE; return Int32; } function parseUint32(dataView, offset2) { var Uint32 = dataView.getUint32(offset2.value, true); offset2.value = offset2.value + INT32_SIZE; return Uint32; } function parseUint8Array(uInt8Array2, offset2) { var Uint8 = uInt8Array2[offset2.value]; offset2.value = offset2.value + INT8_SIZE; return Uint8; } function parseUint8(dataView, offset2) { var 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) { var float = dataView.getFloat32(offset2.value, true); offset2.value += FLOAT32_SIZE; return float; } function decodeFloat32(dataView, offset2) { return DataUtils.toHalfFloat(parseFloat32(dataView, offset2)); } function decodeFloat16(binary) { var 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) { var Uint16 = dataView.getUint16(offset2.value, true); offset2.value += INT16_SIZE; return Uint16; } function parseFloat16(buffer22, offset2) { return decodeFloat16(parseUint16(buffer22, offset2)); } function parseChlist(dataView, buffer22, offset2, size2) { var startOffset = offset2.value; var channels = []; while (offset2.value < startOffset + size2 - 1) { var name = parseNullTerminatedString(buffer22, offset2); var pixelType = parseInt32(dataView, offset2); var pLinear = parseUint8(dataView, offset2); offset2.value += 3; var xSampling = parseInt32(dataView, offset2); var ySampling = parseInt32(dataView, offset2); channels.push({ name, pixelType, pLinear, xSampling, ySampling }); } offset2.value += 1; return channels; } function parseChromaticities(dataView, offset2) { var redX = parseFloat32(dataView, offset2); var redY = parseFloat32(dataView, offset2); var greenX = parseFloat32(dataView, offset2); var greenY = parseFloat32(dataView, offset2); var blueX = parseFloat32(dataView, offset2); var blueY = parseFloat32(dataView, offset2); var whiteX = parseFloat32(dataView, offset2); var whiteY = parseFloat32(dataView, offset2); return { redX, redY, greenX, greenY, blueX, blueY, whiteX, whiteY }; } function parseCompression(dataView, offset2) { var compressionCodes = [ "NO_COMPRESSION", "RLE_COMPRESSION", "ZIPS_COMPRESSION", "ZIP_COMPRESSION", "PIZ_COMPRESSION", "PXR24_COMPRESSION", "B44_COMPRESSION", "B44A_COMPRESSION", "DWAA_COMPRESSION", "DWAB_COMPRESSION" ]; var compression = parseUint8(dataView, offset2); return compressionCodes[compression]; } function parseBox2i(dataView, offset2) { var xMin = parseUint32(dataView, offset2); var yMin = parseUint32(dataView, offset2); var xMax = parseUint32(dataView, offset2); var yMax = parseUint32(dataView, offset2); return { xMin, yMin, xMax, yMax }; } function parseLineOrder(dataView, offset2) { var lineOrders = ["INCREASING_Y"]; var lineOrder = parseUint8(dataView, offset2); return lineOrders[lineOrder]; } function parseV2f(dataView, offset2) { var x = parseFloat32(dataView, offset2); var y = parseFloat32(dataView, offset2); return [x, y]; } function parseV3f(dataView, offset2) { var x = parseFloat32(dataView, offset2); var y = parseFloat32(dataView, offset2); var z = parseFloat32(dataView, offset2); return [x, y, z]; } function parseValue(dataView, buffer22, offset2, type, size2) { if (type === "string" || type === "stringvector" || type === "iccProfile") { return parseFixedLengthString(buffer22, offset2, size2); } else if (type === "chlist") { return parseChlist(dataView, buffer22, 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 === "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 parseHeader(dataView, buffer22, offset2) { const EXRHeader2 = {}; if (dataView.getUint32(0, true) != 20000630) { throw "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; var keepReading = true; while (keepReading) { var attributeName = parseNullTerminatedString(buffer22, offset2); if (attributeName == 0) { keepReading = false; } else { var attributeType = parseNullTerminatedString(buffer22, offset2); var attributeSize = parseUint32(dataView, offset2); var attributeValue = parseValue(dataView, buffer22, offset2, attributeType, attributeSize); if (attributeValue === void 0) { console.warn(`EXRLoader.parse: skipped unknown header attribute type '${attributeType}'.`); } else { EXRHeader2[attributeName] = attributeValue; } } } if ((spec & ~4) != 0) { console.error("EXRHeader:", EXRHeader2); throw "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, channels: EXRHeader2.channels.length, bytesPerLine: null, lines: null, inputSize: null, type: EXRHeader2.channels[0].pixelType, uncompress: null, getter: null, format: null, [hasColorSpace ? "colorSpace" : "encoding"]: null }; switch (EXRHeader2.compression) { case "NO_COMPRESSION": EXRDecoder2.lines = 1; EXRDecoder2.uncompress = uncompressRAW; break; case "RLE_COMPRESSION": EXRDecoder2.lines = 1; EXRDecoder2.uncompress = uncompressRLE; break; case "ZIPS_COMPRESSION": EXRDecoder2.lines = 1; EXRDecoder2.uncompress = uncompressZIP; break; case "ZIP_COMPRESSION": EXRDecoder2.lines = 16; EXRDecoder2.uncompress = uncompressZIP; break; case "PIZ_COMPRESSION": EXRDecoder2.lines = 32; EXRDecoder2.uncompress = uncompressPIZ; break; case "PXR24_COMPRESSION": EXRDecoder2.lines = 16; EXRDecoder2.uncompress = uncompressPXR; break; case "DWAA_COMPRESSION": EXRDecoder2.lines = 32; EXRDecoder2.uncompress = uncompressDWA; break; case "DWAB_COMPRESSION": EXRDecoder2.lines = 256; EXRDecoder2.uncompress = uncompressDWA; break; default: throw "EXRLoader.parse: " + EXRHeader2.compression + " is unsupported"; } EXRDecoder2.scanlineBlockSize = EXRDecoder2.lines; if (EXRDecoder2.type == 1) { switch (outputType) { case FloatType: EXRDecoder2.getter = parseFloat16; EXRDecoder2.inputSize = INT16_SIZE; break; case HalfFloatType: EXRDecoder2.getter = parseUint16; EXRDecoder2.inputSize = INT16_SIZE; break; } } else if (EXRDecoder2.type == 2) { switch (outputType) { case FloatType: EXRDecoder2.getter = parseFloat32; EXRDecoder2.inputSize = FLOAT32_SIZE; break; case HalfFloatType: EXRDecoder2.getter = decodeFloat32; EXRDecoder2.inputSize = FLOAT32_SIZE; } } else { throw "EXRLoader.parse: unsupported pixelType " + EXRDecoder2.type + " for " + EXRHeader2.compression + "."; } EXRDecoder2.blockCount = (EXRHeader2.dataWindow.yMax + 1) / EXRDecoder2.scanlineBlockSize; for (var i4 = 0; i4 < EXRDecoder2.blockCount; i4++) parseInt64(dataView, offset2); EXRDecoder2.outputChannels = EXRDecoder2.channels == 3 ? 4 : EXRDecoder2.channels; const size2 = EXRDecoder2.width * EXRDecoder2.height * EXRDecoder2.outputChannels; switch (outputType) { case FloatType: EXRDecoder2.byteArray = new Float32Array(size2); if (EXRDecoder2.channels < EXRDecoder2.outputChannels) EXRDecoder2.byteArray.fill(1, 0, size2); break; case HalfFloatType: EXRDecoder2.byteArray = new Uint16Array(size2); if (EXRDecoder2.channels < EXRDecoder2.outputChannels) EXRDecoder2.byteArray.fill(15360, 0, size2); break; default: console.error("THREE.EXRLoader: unsupported type: ", outputType); break; } EXRDecoder2.bytesPerLine = EXRDecoder2.width * EXRDecoder2.inputSize * EXRDecoder2.channels; if (EXRDecoder2.outputChannels == 4) EXRDecoder2.format = RGBAFormat; else EXRDecoder2.format = RedFormat; if (hasColorSpace) EXRDecoder2.colorSpace = "srgb-linear"; else EXRDecoder2.encoding = 3e3; return EXRDecoder2; } const bufferDataView = new DataView(buffer2); const uInt8Array = new Uint8Array(buffer2); const offset = { value: 0 }; const EXRHeader = parseHeader(bufferDataView, buffer2, offset); const EXRDecoder = setupDecoder(EXRHeader, bufferDataView, uInt8Array, offset, this.type); const tmpOffset = { value: 0 }; const channelOffsets = { R: 0, G: 1, B: 2, A: 3, Y: 0 }; for (let scanlineBlockIdx = 0; scanlineBlockIdx < EXRDecoder.height / EXRDecoder.scanlineBlockSize; scanlineBlockIdx++) { const line = parseUint32(bufferDataView, offset); EXRDecoder.size = parseUint32(bufferDataView, offset); EXRDecoder.lines = line + EXRDecoder.scanlineBlockSize > EXRDecoder.height ? EXRDecoder.height - line : EXRDecoder.scanlineBlockSize; const isCompressed = EXRDecoder.size < EXRDecoder.lines * EXRDecoder.bytesPerLine; const viewer = isCompressed ? EXRDecoder.uncompress(EXRDecoder) : uncompressRAW(EXRDecoder); offset.value += EXRDecoder.size; for (let line_y = 0; line_y < EXRDecoder.scanlineBlockSize; line_y++) { const true_y = line_y + scanlineBlockIdx * EXRDecoder.scanlineBlockSize; if (true_y >= EXRDecoder.height) break; for (let channelID = 0; channelID < EXRDecoder.channels; channelID++) { const cOff = channelOffsets[EXRHeader.channels[channelID].name]; for (let x = 0; x < EXRDecoder.width; x++) { tmpOffset.value = (line_y * (EXRDecoder.channels * EXRDecoder.width) + channelID * EXRDecoder.width + x) * EXRDecoder.inputSize; const outIndex = (EXRDecoder.height - 1 - true_y) * (EXRDecoder.width * EXRDecoder.outputChannels) + x * EXRDecoder.outputChannels + cOff; EXRDecoder.byteArray[outIndex] = EXRDecoder.getter(viewer, tmpOffset); } } } } return { header: EXRHeader, width: EXRDecoder.width, height: EXRDecoder.height, data: EXRDecoder.byteArray, format: EXRDecoder.format, [hasColorSpace ? "colorSpace" : "encoding"]: EXRDecoder[hasColorSpace ? "colorSpace" : "encoding"], type: this.type }; } setDataType(value) { this.type = value; return this; } load(url, onLoad, onProgress, onError) { function onLoadCallback(texture, texData) { if (hasColorSpace) texture.colorSpace = texData.colorSpace; else texture.encoding = texData.encoding; 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-stdlib/loaders/BasisTextureLoader.js var __defProp32 = Object.defineProperty; var __defNormalProp32 = (obj, key, value) => key in obj ? __defProp32(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField32 = (obj, key, value) => { __defNormalProp32(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var _taskCache2 = /* @__PURE__ */ new WeakMap(); var BasisTextureLoader = (() => { const _BasisTextureLoader = class extends Loader { constructor(manager) { super(manager); this.transcoderPath = ""; this.transcoderBinary = null; this.transcoderPending = null; this.workerLimit = 4; this.workerPool = []; this.workerNextTaskID = 1; this.workerSourceURL = ""; this.workerConfig = null; } setTranscoderPath(path) { this.transcoderPath = path; return this; } setWorkerLimit(workerLimit) { this.workerLimit = workerLimit; return this; } detectSupport(renderer) { this.workerConfig = { astcSupported: renderer.extensions.has("WEBGL_compressed_texture_astc"), etc1Supported: renderer.extensions.has("WEBGL_compressed_texture_etc1"), etc2Supported: renderer.extensions.has("WEBGL_compressed_texture_etc"), dxtSupported: renderer.extensions.has("WEBGL_compressed_texture_s3tc"), bptcSupported: renderer.extensions.has("EXT_texture_compression_bptc"), pvrtcSupported: renderer.extensions.has("WEBGL_compressed_texture_pvrtc") || renderer.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc") }; return this; } load(url, onLoad, onProgress, onError) { const loader2 = new FileLoader(this.manager); loader2.setResponseType("arraybuffer"); loader2.setWithCredentials(this.withCredentials); const texture = new CompressedTexture(); loader2.load( url, (buffer2) => { if (_taskCache2.has(buffer2)) { const cachedTask = _taskCache2.get(buffer2); return cachedTask.promise.then(onLoad).catch(onError); } this._createTexture([buffer2]).then(function(_texture) { texture.copy(_texture); texture.needsUpdate = true; if (onLoad) onLoad(texture); }).catch(onError); }, onProgress, onError ); return texture; } /** Low-level transcoding API, exposed for use by KTX2Loader. */ parseInternalAsync(options) { const { levels } = options; const buffers = /* @__PURE__ */ new Set(); for (let i4 = 0; i4 < levels.length; i4++) { buffers.add(levels[i4].data.buffer); } return this._createTexture(Array.from(buffers), { ...options, lowLevel: true }); } /** * @param {ArrayBuffer[]} buffers * @param {object?} config * @return {Promise} */ _createTexture(buffers, config = {}) { let worker; let taskID; const taskConfig = config; let taskCost = 0; for (let i4 = 0; i4 < buffers.length; i4++) { taskCost += buffers[i4].byteLength; } const texturePending = this._allocateWorker(taskCost).then((_worker) => { worker = _worker; taskID = this.workerNextTaskID++; return new Promise((resolve, reject) => { worker._callbacks[taskID] = { resolve, reject }; worker.postMessage({ type: "transcode", id: taskID, buffers, taskConfig }, buffers); }); }).then((message) => { const { mipmaps, width, height, format } = message; const texture = new CompressedTexture(mipmaps, width, height, format, UnsignedByteType); texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; texture.magFilter = LinearFilter; texture.generateMipmaps = false; texture.needsUpdate = true; return texture; }); texturePending.catch(() => true).then(() => { if (worker && taskID) { worker._taskLoad -= taskCost; delete worker._callbacks[taskID]; } }); _taskCache2.set(buffers[0], { promise: texturePending }); return texturePending; } _initTranscoder() { if (!this.transcoderPending) { const jsLoader = new FileLoader(this.manager); jsLoader.setPath(this.transcoderPath); jsLoader.setWithCredentials(this.withCredentials); const jsContent = new Promise((resolve, reject) => { jsLoader.load("basis_transcoder.js", resolve, void 0, reject); }); const binaryLoader = new FileLoader(this.manager); binaryLoader.setPath(this.transcoderPath); binaryLoader.setResponseType("arraybuffer"); binaryLoader.setWithCredentials(this.withCredentials); const binaryContent = new Promise((resolve, reject) => { binaryLoader.load("basis_transcoder.wasm", resolve, void 0, reject); }); this.transcoderPending = Promise.all([jsContent, binaryContent]).then(([jsContent2, binaryContent2]) => { const fn = _BasisTextureLoader.BasisWorker.toString(); const body = [ "/* constants */", "let _EngineFormat = " + JSON.stringify(_BasisTextureLoader.EngineFormat), "let _TranscoderFormat = " + JSON.stringify(_BasisTextureLoader.TranscoderFormat), "let _BasisFormat = " + JSON.stringify(_BasisTextureLoader.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; }); } return this.transcoderPending; } _allocateWorker(taskCost) { return this._initTranscoder().then(() => { if (this.workerPool.length < this.workerLimit) { const worker2 = new Worker(this.workerSourceURL); worker2._callbacks = {}; worker2._taskLoad = 0; worker2.postMessage({ type: "init", config: this.workerConfig, transcoderBinary: this.transcoderBinary }); worker2.onmessage = function(e2) { const message = e2.data; switch (message.type) { case "transcode": worker2._callbacks[message.id].resolve(message); break; case "error": worker2._callbacks[message.id].reject(message); break; default: console.error('THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"'); } }; this.workerPool.push(worker2); } else { this.workerPool.sort(function(a6, b5) { return a6._taskLoad > b5._taskLoad ? -1 : 1; }); } const worker = this.workerPool[this.workerPool.length - 1]; worker._taskLoad += taskCost; return worker; }); } dispose() { for (let i4 = 0; i4 < this.workerPool.length; i4++) { this.workerPool[i4].terminate(); } this.workerPool.length = 0; return this; } }; let BasisTextureLoader2 = _BasisTextureLoader; __publicField32(BasisTextureLoader2, "BasisFormat", { ETC1S: 0, UASTC_4x4: 1 }); __publicField32(BasisTextureLoader2, "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 }); __publicField32(BasisTextureLoader2, "EngineFormat", { RGBAFormat, RGBA_ASTC_4x4_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, RGB_S3TC_DXT1_Format }); __publicField32(BasisTextureLoader2, "BasisWorker", function() { let config; let transcoderPending; let BasisModule; const EngineFormat = _EngineFormat; const TranscoderFormat = _TranscoderFormat; const BasisFormat = _BasisFormat; onmessage = function(e2) { const message = e2.data; switch (message.type) { case "init": config = message.config; init3(message.transcoderBinary); break; case "transcode": transcoderPending.then(() => { try { const { width, height, hasAlpha, mipmaps, format } = message.taskConfig.lowLevel ? transcodeLowLevel(message.taskConfig) : transcode(message.buffers[0]); const buffers = []; for (let i4 = 0; i4 < mipmaps.length; ++i4) { buffers.push(mipmaps[i4].data.buffer); } self.postMessage( { type: "transcode", id: message.id, width, height, hasAlpha, mipmaps, format }, buffers ); } catch (error) { console.error(error); self.postMessage({ type: "error", id: message.id, error: error.message }); } }); break; } }; function init3(wasmBinary) { transcoderPending = new Promise((resolve) => { BasisModule = { wasmBinary, onRuntimeInitialized: resolve }; BASIS(BasisModule); }).then(() => { BasisModule.initializeBasis(); }); } function transcodeLowLevel(taskConfig) { const { basisFormat, width, height, hasAlpha } = taskConfig; const { transcoderFormat, engineFormat } = getTranscoderFormat(basisFormat, width, height, hasAlpha); const blockByteLength = BasisModule.getBytesPerBlockOrPixel(transcoderFormat); assert(BasisModule.isFormatSupported(transcoderFormat), "THREE.BasisTextureLoader: Unsupported format."); const mipmaps = []; if (basisFormat === BasisFormat.ETC1S) { const transcoder = new BasisModule.LowLevelETC1SImageTranscoder(); const { endpointCount, endpointsData, selectorCount, selectorsData, tablesData } = taskConfig.globalData; try { let ok; ok = transcoder.decodePalettes(endpointCount, endpointsData, selectorCount, selectorsData); assert(ok, "THREE.BasisTextureLoader: decodePalettes() failed."); ok = transcoder.decodeTables(tablesData); assert(ok, "THREE.BasisTextureLoader: decodeTables() failed."); for (let i4 = 0; i4 < taskConfig.levels.length; i4++) { const level = taskConfig.levels[i4]; const imageDesc = taskConfig.globalData.imageDescs[i4]; const dstByteLength = getTranscodedImageByteLength(transcoderFormat, level.width, level.height); const dst = new Uint8Array(dstByteLength); ok = transcoder.transcodeImage( transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks(transcoderFormat, level.width), getHeightInBlocks(transcoderFormat, level.height), level.width, level.height, level.index, imageDesc.rgbSliceByteOffset, imageDesc.rgbSliceByteLength, imageDesc.alphaSliceByteOffset, imageDesc.alphaSliceByteLength, imageDesc.imageFlags, hasAlpha, false, 0, 0 ); assert(ok, "THREE.BasisTextureLoader: transcodeImage() failed for level " + level.index + "."); mipmaps.push({ data: dst, width: level.width, height: level.height }); } } finally { transcoder.delete(); } } else { for (let i4 = 0; i4 < taskConfig.levels.length; i4++) { const level = taskConfig.levels[i4]; const dstByteLength = getTranscodedImageByteLength(transcoderFormat, level.width, level.height); const dst = new Uint8Array(dstByteLength); const ok = BasisModule.transcodeUASTCImage( transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks(transcoderFormat, level.width), getHeightInBlocks(transcoderFormat, level.height), level.width, level.height, level.index, 0, level.data.byteLength, 0, hasAlpha, false, 0, 0, -1, -1 ); assert(ok, "THREE.BasisTextureLoader: transcodeUASTCImage() failed for level " + level.index + "."); mipmaps.push({ data: dst, width: level.width, height: level.height }); } } return { width, height, hasAlpha, mipmaps, format: engineFormat }; } function transcode(buffer2) { const basisFile = new BasisModule.BasisFile(new Uint8Array(buffer2)); const basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; const width = basisFile.getImageWidth(0, 0); const height = basisFile.getImageHeight(0, 0); const levels = basisFile.getNumLevels(0); const hasAlpha = basisFile.getHasAlpha(); function cleanup() { basisFile.close(); basisFile.delete(); } const { transcoderFormat, engineFormat } = getTranscoderFormat(basisFormat, width, height, hasAlpha); if (!width || !height || !levels) { cleanup(); throw new Error("THREE.BasisTextureLoader: Invalid texture"); } if (!basisFile.startTranscoding()) { cleanup(); throw new Error("THREE.BasisTextureLoader: .startTranscoding failed"); } const mipmaps = []; for (let mip = 0; mip < levels; mip++) { const mipWidth = basisFile.getImageWidth(0, mip); const mipHeight = basisFile.getImageHeight(0, mip); const dst = new Uint8Array(basisFile.getImageTranscodedSizeInBytes(0, mip, transcoderFormat)); const status = basisFile.transcodeImage(dst, 0, mip, transcoderFormat, 0, hasAlpha); if (!status) { cleanup(); throw new Error("THREE.BasisTextureLoader: .transcodeImage failed."); } mipmaps.push({ data: dst, width: mipWidth, height: mipHeight }); } cleanup(); return { width, height, hasAlpha, mipmaps, format: engineFormat }; } const FORMAT_OPTIONS = [ { if: "astcSupported", basisFormat: [BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4], engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format], priorityETC1S: Infinity, priorityUASTC: 1, needsPowerOfTwo: false }, { if: "bptcSupported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5], engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format], priorityETC1S: 3, priorityUASTC: 2, needsPowerOfTwo: false }, { if: "dxtSupported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3], engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format], priorityETC1S: 4, priorityUASTC: 5, needsPowerOfTwo: false }, { if: "etc2Supported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2], engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format], priorityETC1S: 1, priorityUASTC: 3, needsPowerOfTwo: false }, { if: "etc1Supported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC1], engineFormat: [EngineFormat.RGB_ETC1_Format, EngineFormat.RGB_ETC1_Format], priorityETC1S: 2, priorityUASTC: 4, needsPowerOfTwo: false }, { if: "pvrtcSupported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA], engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format], priorityETC1S: 5, priorityUASTC: 6, needsPowerOfTwo: true } ]; const ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function(a6, b5) { return a6.priorityETC1S - b5.priorityETC1S; }); const UASTC_OPTIONS = FORMAT_OPTIONS.sort(function(a6, b5) { return a6.priorityUASTC - b5.priorityUASTC; }); function getTranscoderFormat(basisFormat, width, height, hasAlpha) { let transcoderFormat; let engineFormat; const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; for (let i4 = 0; i4 < options.length; i4++) { const opt = options[i4]; if (!config[opt.if]) continue; if (!opt.basisFormat.includes(basisFormat)) continue; if (opt.needsPowerOfTwo && !(isPowerOfTwo(width) && isPowerOfTwo(height))) continue; transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0]; engineFormat = opt.engineFormat[hasAlpha ? 1 : 0]; return { transcoderFormat, engineFormat }; } console.warn("THREE.BasisTextureLoader: No suitable compressed texture format found. Decoding to RGBA32."); transcoderFormat = TranscoderFormat.RGBA32; engineFormat = EngineFormat.RGBAFormat; return { transcoderFormat, engineFormat }; } function assert(ok, message) { if (!ok) throw new Error(message); } function getWidthInBlocks(transcoderFormat, width) { return Math.ceil(width / BasisModule.getFormatBlockWidth(transcoderFormat)); } function getHeightInBlocks(transcoderFormat, height) { return Math.ceil(height / BasisModule.getFormatBlockHeight(transcoderFormat)); } function getTranscodedImageByteLength(transcoderFormat, width, height) { const blockByteLength = BasisModule.getBytesPerBlockOrPixel(transcoderFormat); if (BasisModule.formatIsUncompressed(transcoderFormat)) { return width * height * blockByteLength; } if (transcoderFormat === TranscoderFormat.PVRTC1_4_RGB || transcoderFormat === TranscoderFormat.PVRTC1_4_RGBA) { const paddedWidth = width + 3 & ~3; const paddedHeight = height + 3 & ~3; return (Math.max(8, paddedWidth) * Math.max(8, paddedHeight) * 4 + 7) / 8; } return getWidthInBlocks(transcoderFormat, width) * getHeightInBlocks(transcoderFormat, height) * blockByteLength; } function isPowerOfTwo(value) { if (value <= 2) return true; return (value & value - 1) === 0 && value !== 0; } }); return BasisTextureLoader2; })(); // node_modules/three-stdlib/loaders/LDrawLoader.js var _tempVec0 = new Vector3(); var _tempVec1 = new Vector3(); var _ray2 = new Ray(); // node_modules/three-stdlib/loaders/SVGLoader.js var COLOR_SPACE_SVG = "srgb"; var SVGLoader = /* @__PURE__ */ (() => { class SVGLoader2 extends Loader { constructor(manager) { super(manager); this.defaultDPI = 90; this.defaultUnit = "px"; } load(url, onLoad, onProgress, onError) { const scope = this; const loader2 = new FileLoader(scope.manager); loader2.setPath(scope.path); loader2.setRequestHeader(scope.requestHeader); loader2.setWithCredentials(scope.withCredentials); loader2.load( url, function(text) { try { onLoad(scope.parse(text)); } catch (e2) { if (onError) { onError(e2); } else { console.error(e2); } scope.manager.itemError(url); } }, onProgress, onError ); } parse(text) { const scope = this; function parseNode(node, style) { if (node.nodeType !== 1) return; const transform = 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; } 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 i4 = 0; i4 < childNodes.length; i4++) { const node2 = childNodes[i4]; if (isDefsNode && node2.nodeName !== "style" && node2.nodeName !== "defs") { continue; } parseNode(node2, style); } if (transform) { transformStack.pop(); if (transformStack.length > 0) { currentTransform.copy(transformStack[transformStack.length - 1]); } else { currentTransform.identity(); } } } function parsePathNode(node) { const path = new ShapePath(); const point = new Vector2(); const control = new Vector2(); const firstPoint = new Vector2(); let isFirstPoint = true; let doSetFirstPoint = false; const d2 = node.getAttribute("d"); if (d2 === "" || d2 === "none") return null; const commands = d2.match(/[a-df-z][^a-df-z]*/gi); for (let i4 = 0, l2 = commands.length; i4 < l2; i4++) { const command = commands[i4]; const type = command.charAt(0); const data2 = command.slice(1).trim(); if (isFirstPoint === true) { doSetFirstPoint = true; isFirstPoint = false; } let numbers; switch (type) { case "M": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 2) { point.x = numbers[j + 0]; point.y = numbers[j + 1]; control.x = point.x; control.y = point.y; if (j === 0) { path.moveTo(point.x, point.y); } else { path.lineTo(point.x, point.y); } if (j === 0) firstPoint.copy(point); } break; case "H": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j++) { point.x = numbers[j]; control.x = point.x; control.y = point.y; path.lineTo(point.x, point.y); if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "V": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j++) { point.y = numbers[j]; control.x = point.x; control.y = point.y; path.lineTo(point.x, point.y); if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "L": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 2) { point.x = numbers[j + 0]; point.y = numbers[j + 1]; control.x = point.x; control.y = point.y; path.lineTo(point.x, point.y); if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "C": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 6) { path.bezierCurveTo( numbers[j + 0], numbers[j + 1], numbers[j + 2], numbers[j + 3], numbers[j + 4], numbers[j + 5] ); control.x = numbers[j + 2]; control.y = numbers[j + 3]; point.x = numbers[j + 4]; point.y = numbers[j + 5]; if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "S": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 4) { path.bezierCurveTo( getReflection(point.x, control.x), getReflection(point.y, control.y), numbers[j + 0], numbers[j + 1], numbers[j + 2], numbers[j + 3] ); control.x = numbers[j + 0]; control.y = numbers[j + 1]; point.x = numbers[j + 2]; point.y = numbers[j + 3]; if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "Q": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 4) { path.quadraticCurveTo(numbers[j + 0], numbers[j + 1], numbers[j + 2], numbers[j + 3]); control.x = numbers[j + 0]; control.y = numbers[j + 1]; point.x = numbers[j + 2]; point.y = numbers[j + 3]; if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "T": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 2) { const rx = getReflection(point.x, control.x); const ry = getReflection(point.y, control.y); path.quadraticCurveTo(rx, ry, numbers[j + 0], numbers[j + 1]); control.x = rx; control.y = ry; point.x = numbers[j + 0]; point.y = numbers[j + 1]; if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "A": numbers = parseFloats(data2, [3, 4], 7); for (let j = 0, jl = numbers.length; j < jl; j += 7) { if (numbers[j + 5] == point.x && numbers[j + 6] == point.y) continue; const start = point.clone(); point.x = numbers[j + 5]; point.y = numbers[j + 6]; control.x = point.x; control.y = point.y; parseArcCommand( path, numbers[j], numbers[j + 1], numbers[j + 2], numbers[j + 3], numbers[j + 4], start, point ); if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "m": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 2) { point.x += numbers[j + 0]; point.y += numbers[j + 1]; control.x = point.x; control.y = point.y; if (j === 0) { path.moveTo(point.x, point.y); } else { path.lineTo(point.x, point.y); } if (j === 0) firstPoint.copy(point); } break; case "h": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j++) { point.x += numbers[j]; control.x = point.x; control.y = point.y; path.lineTo(point.x, point.y); if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "v": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j++) { point.y += numbers[j]; control.x = point.x; control.y = point.y; path.lineTo(point.x, point.y); if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "l": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 2) { point.x += numbers[j + 0]; point.y += numbers[j + 1]; control.x = point.x; control.y = point.y; path.lineTo(point.x, point.y); if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "c": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 6) { path.bezierCurveTo( point.x + numbers[j + 0], point.y + numbers[j + 1], point.x + numbers[j + 2], point.y + numbers[j + 3], point.x + numbers[j + 4], point.y + numbers[j + 5] ); control.x = point.x + numbers[j + 2]; control.y = point.y + numbers[j + 3]; point.x += numbers[j + 4]; point.y += numbers[j + 5]; if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "s": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 4) { path.bezierCurveTo( getReflection(point.x, control.x), getReflection(point.y, control.y), point.x + numbers[j + 0], point.y + numbers[j + 1], point.x + numbers[j + 2], point.y + numbers[j + 3] ); control.x = point.x + numbers[j + 0]; control.y = point.y + numbers[j + 1]; point.x += numbers[j + 2]; point.y += numbers[j + 3]; if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "q": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 4) { path.quadraticCurveTo( point.x + numbers[j + 0], point.y + numbers[j + 1], point.x + numbers[j + 2], point.y + numbers[j + 3] ); control.x = point.x + numbers[j + 0]; control.y = point.y + numbers[j + 1]; point.x += numbers[j + 2]; point.y += numbers[j + 3]; if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "t": numbers = parseFloats(data2); for (let j = 0, jl = numbers.length; j < jl; j += 2) { const rx = getReflection(point.x, control.x); const ry = getReflection(point.y, control.y); path.quadraticCurveTo(rx, ry, point.x + numbers[j + 0], point.y + numbers[j + 1]); control.x = rx; control.y = ry; point.x = point.x + numbers[j + 0]; point.y = point.y + numbers[j + 1]; if (j === 0 && doSetFirstPoint === true) firstPoint.copy(point); } break; case "a": numbers = parseFloats(data2, [3, 4], 7); for (let j = 0, jl = numbers.length; j < jl; j += 7) { if (numbers[j + 5] == 0 && numbers[j + 6] == 0) continue; const start = point.clone(); point.x += numbers[j + 5]; point.y += numbers[j + 6]; control.x = point.x; control.y = point.y; parseArcCommand( path, numbers[j], numbers[j + 1], numbers[j + 2], numbers[j + 3], numbers[j + 4], start, point ); if (j === 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 i4 = 0; i4 < node.sheet.cssRules.length; i4++) { const stylesheet = node.sheet.cssRules[i4]; if (stylesheet.type !== 1) continue; const selectorList = stylesheet.selectorText.split(/,/gm).filter(Boolean).map((i22) => i22.trim()); for (let j = 0; j < selectorList.length; j++) { const definitions = Object.fromEntries(Object.entries(stylesheet.style).filter(([, v5]) => v5 !== "")); stylesheets[selectorList[j]] = Object.assign(stylesheets[selectorList[j]] || {}, 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 s2 = Math.sqrt(cr); rx = s2 * rx; ry = s2 * ry; rxs = rx * rx; rys = ry * ry; } const dq = rxs * y1ps + rys * x1ps; const pq = (rxs * rys - dq) / dq; let q = Math.sqrt(Math.max(0, pq)); if (large_arc_flag === sweep_flag) q = -q; const cxp = q * rx * y1p / ry; const cyp = -q * 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 dot3 = 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, dot3 / len))); if (ux * vy - uy * vx < 0) ang = -ang; return ang; } function parseRectNode(node) { const x = 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 ShapePath(); path.moveTo(x + rx, y); path.lineTo(x + w - rx, y); if (rx !== 0 || ry !== 0) { path.bezierCurveTo(x + w - rx * bci, y, x + w, y + ry * bci, x + w, y + ry); } path.lineTo(x + w, y + h - ry); if (rx !== 0 || ry !== 0) { path.bezierCurveTo(x + w, y + h - ry * bci, x + w - rx * bci, y + h, x + w - rx, y + h); } path.lineTo(x + rx, y + h); if (rx !== 0 || ry !== 0) { path.bezierCurveTo(x + rx * bci, y + h, x, y + h - ry * bci, x, y + h - ry); } path.lineTo(x, y + ry); if (rx !== 0 || ry !== 0) { path.bezierCurveTo(x, y + ry * bci, x + rx * bci, y, x + rx, y); } return path; } function parsePolygonNode(node) { function iterator(match, a6, b5) { const x = parseFloatWithUnits(a6); const y = parseFloatWithUnits(b5); if (index2 === 0) { path.moveTo(x, y); } else { path.lineTo(x, y); } index2++; } const regex = /([+-]?\d*\.?\d+(?:e[+-]?\d+)?)(?:,|\s)([+-]?\d*\.?\d+(?:e[+-]?\d+)?)/g; const path = new ShapePath(); let index2 = 0; node.getAttribute("points").replace(regex, iterator); path.currentPath.autoClose = true; return path; } function parsePolylineNode(node) { function iterator(match, a6, b5) { const x = parseFloatWithUnits(a6); const y = parseFloatWithUnits(b5); if (index2 === 0) { path.moveTo(x, y); } else { path.lineTo(x, y); } index2++; } const regex = /([+-]?\d*\.?\d+(?:e[+-]?\d+)?)(?:,|\s)([+-]?\d*\.?\d+(?:e[+-]?\d+)?)/g; const path = new ShapePath(); let index2 = 0; node.getAttribute("points").replace(regex, iterator); path.currentPath.autoClose = false; return path; } function parseCircleNode(node) { const x = parseFloatWithUnits(node.getAttribute("cx") || 0); const y = parseFloatWithUnits(node.getAttribute("cy") || 0); const r2 = parseFloatWithUnits(node.getAttribute("r") || 0); const subpath = new Path(); subpath.absarc(x, y, r2, 0, Math.PI * 2); const path = new ShapePath(); path.subPaths.push(subpath); return path; } function parseEllipseNode(node) { const x = 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(x, y, rx, ry, 0, Math.PI * 2); const path = new ShapePath(); 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 ShapePath(); 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((i4) => i4.trim()); for (let i4 = 0; i4 < classSelectors.length; i4++) { stylesheetStyles = Object.assign(stylesheetStyles, stylesheets["." + classSelectors[i4]]); } } if (node.hasAttribute("id")) { stylesheetStyles = Object.assign(stylesheetStyles, stylesheets["#" + node.getAttribute("id")]); } function addStyle(svgName, jsName, adjustFunction) { if (adjustFunction === void 0) adjustFunction = function copy(v5) { if (v5.startsWith("url")) console.warn("SVGLoader: url access in attributes is not implemented."); return v5; }; 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 clamp4(v5) { return Math.max(0, Math.min(1, parseFloatWithUnits(v5))); } function positive(v5) { return Math.max(0, parseFloatWithUnits(v5)); } addStyle("fill", "fill"); addStyle("fill-opacity", "fillOpacity", clamp4); addStyle("fill-rule", "fillRule"); addStyle("opacity", "opacity", clamp4); addStyle("stroke", "stroke"); addStyle("stroke-opacity", "strokeOpacity", clamp4); 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(a6, b5) { return a6 - (b5 - a6); } 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, i4, partial) { const error = new SyntaxError('Unexpected character "' + current2 + '" at index ' + i4 + "."); error.partial = partial; 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 length3 = input.length; for (let i4 = 0; i4 < length3; i4++) { current = input[i4]; 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, i4, 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, i4, 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, i4, 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, i4, 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, i4, 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 i4 = 0, n2 = units.length; i4 < n2; i4++) { const u = units[i4]; if (string.endsWith(u)) { theUnit = u; string = string.substring(0, string.length - u.length); break; } } } let scale5 = void 0; if (theUnit === "px" && scope.defaultUnit !== "px") { scale5 = unitConversion["in"][scope.defaultUnit] / scope.defaultDPI; } else { scale5 = unitConversion[theUnit][scope.defaultUnit]; if (scale5 < 0) { scale5 = unitConversion[theUnit]["in"] * scope.defaultDPI; } } return scale5 * parseFloat(string); } function getNodeTransform(node) { if (!(node.hasAttribute("transform") || node.nodeName === "use" && (node.hasAttribute("x") || node.hasAttribute("y")))) { return null; } const transform = parseNodeTransform(node); if (transformStack.length > 0) { transform.premultiply(transformStack[transformStack.length - 1]); } currentTransform.copy(transform); transformStack.push(transform); return transform; } function parseNodeTransform(node) { const transform = 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")); transform.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; } } transform.premultiply(currentTransform2); } } return transform; } function transformPath(path, m) { function transfVec2(v22) { tempV32.set(v22.x, v22.y, 1).applyMatrix3(m); v22.set(tempV32.x, tempV32.y); } function transfEllipseGeneric(curve) { const a6 = curve.xRadius; const b5 = curve.yRadius; const cosTheta = Math.cos(curve.aRotation); const sinTheta = Math.sin(curve.aRotation); const v13 = new Vector3(a6 * cosTheta, a6 * sinTheta, 0); const v22 = new Vector3(-b5 * sinTheta, b5 * cosTheta, 0); const f1 = v13.applyMatrix3(m); const f2 = v22.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 i4 = 0, n2 = subPaths.length; i4 < n2; i4++) { const subPath = subPaths[i4]; const curves = subPath.curves; for (let j = 0; j < curves.length; j++) { const curve = curves[j]; 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) { tempV22.set(curve.aX, curve.aY); transfVec2(tempV22); curve.aX = tempV22.x; curve.aY = tempV22.y; if (isTransformSkewed(m)) { transfEllipseGeneric(curve); } else { transfEllipseNoSkew(curve); } } } } } function isTransformFlipped(m) { const te2 = m.elements; return te2[0] * te2[4] - te2[1] * te2[3] < 0; } function isTransformSkewed(m) { const te2 = m.elements; const basisDot = te2[0] * te2[3] + te2[1] * te2[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 te2 = m.elements; return Math.sqrt(te2[0] * te2[0] + te2[1] * te2[1]); } function getTransformScaleY(m) { const te2 = m.elements; return Math.sqrt(te2[3] * te2[3] + te2[4] * te2[4]); } function eigenDecomposition(A, B, C) { let rt1, rt2, cs, sn, t3; const sm = A + C; const df = A - C; const rt = Math.sqrt(df * df + 4 * B * B); if (sm > 0) { rt1 = 0.5 * (sm + rt); t3 = 1 / rt1; rt2 = A * t3 * C - B * t3 * B; } 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(B)) { t3 = -2 * B / cs; sn = 1 / Math.sqrt(1 + t3 * t3); cs = t3 * sn; } else if (Math.abs(B) === 0) { cs = 1; sn = 0; } else { t3 = -0.5 * cs / B; 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 tempV22 = new Vector2(); const tempV32 = new Vector3(); const currentTransform = new Matrix3(); const xml = new DOMParser().parseFromString(text, "image/svg+xml"); parseNode(xml.documentElement, { fill: "#000", fillOpacity: 1, strokeOpacity: 1, strokeWidth: 1, strokeLineJoin: "miter", strokeLineCap: "butt", strokeMiterLimit: 4 }); const data = { paths, xml: xml.documentElement }; return data; } 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 i4 = 0; i4 < 2; i4++) { classifyPoint(i4 === 0 ? b0 : b1, a0, a1); if (classifyResult.loc == IntersectionLocationType.ORIGIN) { const point = i4 === 0 ? b0 : b1; return { x: point.x, y: point.y, t: classifyResult.t }; } else if (classifyResult.loc == IntersectionLocationType.BETWEEN) { const x = +(x1 + classifyResult.t * (x2 - x1)).toPrecision(10); const y = +(y1 + classifyResult.t * (y2 - y1)).toPrecision(10); return { x, y, t: classifyResult.t }; } } return null; } else { for (let i4 = 0; i4 < 2; i4++) { classifyPoint(i4 === 0 ? b0 : b1, a0, a1); if (classifyResult.loc == IntersectionLocationType.ORIGIN) { const point = i4 === 0 ? b0 : b1; return { x: point.x, y: point.y, t: classifyResult.t }; } } const x = +(x1 + t1 * (x2 - x1)).toPrecision(10); const y = +(y1 + t1 * (y2 - y1)).toPrecision(10); return { x, y, t: t1 }; } } function classifyPoint(p2, edgeStart, edgeEnd) { const ax = edgeEnd.x - edgeStart.x; const ay = edgeEnd.y - edgeStart.y; const bx = p2.x - edgeStart.x; const by = p2.y - edgeStart.y; const sa = ax * by - bx * ay; if (p2.x === edgeStart.x && p2.y === edgeStart.y) { classifyResult.loc = IntersectionLocationType.ORIGIN; classifyResult.t = 0; return; } if (p2.x === edgeEnd.x && p2.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 intersection3 = findEdgeIntersection(path1EdgeStart, path1EdgeEnd, path2EdgeStart, path2EdgeEnd); if (intersection3 !== null && intersectionsRaw.find( (i4) => i4.t <= intersection3.t + Number.EPSILON && i4.t >= intersection3.t - Number.EPSILON ) === void 0) { intersectionsRaw.push(intersection3); intersections.push(new Vector2(intersection3.x, intersection3.y)); } } } return intersections; } function getScanlineIntersections(scanline, boundingBox5, paths) { const center3 = new Vector2(); boundingBox5.getCenter(center3); const allIntersections = []; paths.forEach((path) => { if (path.boundingBox.containsPoint(center3)) { const intersections = getIntersections(scanline, path.points); intersections.forEach((p2) => { allIntersections.push({ identifier: path.identifier, isCW: path.isCW, point: p2 }); }); } }); allIntersections.sort((i1, i22) => { return i1.point.x - i22.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, i22) => { return i1.point.x - i22.point.x; }); const baseIntersections = []; const otherIntersections = []; scanlineIntersections.forEach((i22) => { if (i22.identifier === simplePath.identifier) { baseIntersections.push(i22); } else { otherIntersections.push(i22); } }); const firstXOfPath = baseIntersections[0].point.x; const stack = []; let i4 = 0; while (i4 < otherIntersections.length && otherIntersections[i4].point.x < firstXOfPath) { if (stack.length > 0 && stack[stack.length - 1] === otherIntersections[i4].identifier) { stack.pop(); } else { stack.push(otherIntersections[i4].identifier); } i4++; } 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 i22 = 0; i22 < stack.length; i22++) { const identifier = stack[i22]; 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((p2) => { const points = p2.getPoints(); let maxY = -BIGNUMBER; let minY = BIGNUMBER; let maxX = -BIGNUMBER; let minX = BIGNUMBER; for (let i4 = 0; i4 < points.length; i4++) { const p22 = points[i4]; if (p22.y > maxY) { maxY = p22.y; } if (p22.y < minY) { minY = p22.y; } if (p22.x > maxX) { maxX = p22.x; } if (p22.x < minX) { minX = p22.x; } } if (scanlineMaxX <= maxX) { scanlineMaxX = maxX + 1; } if (scanlineMinX >= minX) { scanlineMinX = minX - 1; } return { curves: p2.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( (p2) => isHoleTo( p2, simplePaths, scanlineMinX, scanlineMaxX, shapePath.userData ? shapePath.userData.style.fillRule : void 0 ) ); const shapesToReturn = []; simplePaths.forEach((p2) => { const amIAHole = isAHole[p2.identifier]; if (!amIAHole.isHole) { const shape = new Shape(); shape.curves = p2.curves; const holes = isAHole.filter((h) => h.isHole && h.for === p2.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; } static getStrokeStyle(width, color, lineJoin, lineCap, miterLimit) { width = width !== void 0 ? width : 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: width, strokeLineJoin: lineJoin, strokeLineCap: lineCap, strokeMiterLimit: miterLimit }; } static pointsToStroke(points, style, arcDivisions, minDistance) { const vertices = []; const normals = []; const uvs = []; if (SVGLoader2.pointsToStrokeWithBuffers(points, style, arcDivisions, minDistance, vertices, normals, uvs) === 0) { return null; } const geometry3 = new BufferGeometry(); geometry3.setAttribute("position", new Float32BufferAttribute(vertices, 3)); geometry3.setAttribute("normal", new Float32BufferAttribute(normals, 3)); geometry3.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); return geometry3; } 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 dot3 = Math.abs(normal1.dot(tempV2_3)); if (dot3 > Number.EPSILON) { const miterSide = strokeWidth2 / dot3; 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, u, v5) { 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] = u; uvs[currentCoordinateUV + 1] = v5; currentCoordinateUV += 2; } } numVertices += 3; } function makeCircularSector(center3, p1, p2, u, v5) { tempV2_1.copy(p1).sub(center3).normalize(); tempV2_2.copy(p2).sub(center3).normalize(); let angle = Math.PI; const dot3 = tempV2_1.dot(tempV2_2); if (Math.abs(dot3) < 1) angle = Math.abs(Math.acos(dot3)); angle /= arcDivisions; tempV2_3.copy(p1); for (let i4 = 0, il = arcDivisions - 1; i4 < il; i4++) { tempV2_4.copy(tempV2_3).rotateAround(center3, angle); addVertex(tempV2_3, u, v5); addVertex(tempV2_4, u, v5); addVertex(center3, u, 0.5); tempV2_3.copy(tempV2_4); } addVertex(tempV2_4, u, v5); addVertex(p2, u, v5); addVertex(center3, u, 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, u) { 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, u, 0); addVertex(nextPointL, u, 0); addVertex(innerPoint, u, 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, u, 1); addVertex(innerPoint, u, 0); addVertex(nextPointR, u, 1); } } else { if (joinIsOnLeftSide2) { addVertex(currentPointL, u, 0); addVertex(nextPointL, u, 0); addVertex(currentPoint, u, 0.5); } else { addVertex(currentPointR, u, 1); addVertex(nextPointR, u, 0); addVertex(currentPoint, u, 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(center3, p1, p2, joinIsOnLeftSide2, start, u) { switch (style.strokeLineCap) { case "round": if (start) { makeCircularSector(center3, p2, p1, u, 0.5); } else { makeCircularSector(center3, p1, p2, u, 0.5); } break; case "square": if (start) { tempV2_1.subVectors(p1, center3); tempV2_2.set(tempV2_1.y, -tempV2_1.x); tempV2_3.addVectors(tempV2_1, tempV2_2).add(center3); tempV2_4.subVectors(tempV2_2, tempV2_1).add(center3); 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, center3); tempV2_2.set(tempV2_1.y, -tempV2_1.x); tempV2_3.addVectors(tempV2_1, tempV2_2).add(center3); tempV2_4.subVectors(tempV2_2, tempV2_1).add(center3); 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; } } function removeDuplicatedPoints(points2) { let dupPoints = false; for (let i4 = 1, n2 = points2.length - 1; i4 < n2; i4++) { if (points2[i4].distanceTo(points2[i4 + 1]) < minDistance) { dupPoints = true; break; } } if (!dupPoints) return points2; const newPoints = []; newPoints.push(points2[0]); for (let i4 = 1, n2 = points2.length - 1; i4 < n2; i4++) { if (points2[i4].distanceTo(points2[i4 + 1]) >= minDistance) { newPoints.push(points2[i4]); } } newPoints.push(points2[points2.length - 1]); return newPoints; } } } return SVGLoader2; })(); // node_modules/three-stdlib/loaders/OBJLoader.js var _vA = new Vector3(); var _vB = new Vector3(); var _vC = new Vector3(); var _ab = new Vector3(); var _cb = new Vector3(); // node_modules/three-stdlib/loaders/KTXLoader.js var HEADER_LEN = 12 + 13 * 4; // node_modules/three-stdlib/loaders/DRACOLoader.js var _taskCache3 = /* @__PURE__ */ new WeakMap(); var DRACOLoader = class extends Loader { 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" }; } setDecoderPath(path) { this.decoderPath = path; return this; } setDecoderConfig(config) { this.decoderConfig = config; return this; } setWorkerLimit(workerLimit) { this.workerLimit = workerLimit; return this; } load(url, onLoad, onProgress, onError) { const loader2 = new FileLoader(this.manager); loader2.setPath(this.path); loader2.setResponseType("arraybuffer"); loader2.setRequestHeader(this.requestHeader); loader2.setWithCredentials(this.withCredentials); loader2.load( url, (buffer2) => { const taskConfig = { attributeIDs: this.defaultAttributeIDs, attributeTypes: this.defaultAttributeTypes, useUniqueIDs: false }; this.decodeGeometry(buffer2, taskConfig).then(onLoad).catch(onError); }, onProgress, onError ); } /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */ decodeDracoFile(buffer2, callback, attributeIDs, attributeTypes) { const taskConfig = { attributeIDs: attributeIDs || this.defaultAttributeIDs, attributeTypes: attributeTypes || this.defaultAttributeTypes, useUniqueIDs: !!attributeIDs }; this.decodeGeometry(buffer2, taskConfig).then(callback); } decodeGeometry(buffer2, taskConfig) { for (const attribute in taskConfig.attributeTypes) { const type = taskConfig.attributeTypes[attribute]; if (type.BYTES_PER_ELEMENT !== void 0) { taskConfig.attributeTypes[attribute] = type.name; } } const taskKey = JSON.stringify(taskConfig); if (_taskCache3.has(buffer2)) { const cachedTask = _taskCache3.get(buffer2); if (cachedTask.key === taskKey) { return cachedTask.promise; } else if (buffer2.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 = buffer2.byteLength; const geometryPending = this._getWorker(taskID, taskCost).then((_worker) => { worker = _worker; return new Promise((resolve, reject) => { worker._callbacks[taskID] = { resolve, reject }; worker.postMessage({ type: "decode", id: taskID, taskConfig, buffer: buffer2 }, [buffer2]); }); }).then((message) => this._createGeometry(message.geometry)); geometryPending.catch(() => true).then(() => { if (worker && taskID) { this._releaseTask(worker, taskID); } }); _taskCache3.set(buffer2, { key: taskKey, promise: geometryPending }); return geometryPending; } _createGeometry(geometryData) { const geometry3 = new BufferGeometry(); if (geometryData.index) { geometry3.setIndex(new BufferAttribute(geometryData.index.array, 1)); } for (let i4 = 0; i4 < geometryData.attributes.length; i4++) { const attribute = geometryData.attributes[i4]; const name = attribute.name; const array = attribute.array; const itemSize = attribute.itemSize; geometry3.setAttribute(name, new BufferAttribute(array, itemSize)); } return geometry3; } _loadLibrary(url, responseType) { const loader2 = new FileLoader(this.manager); loader2.setPath(this.decoderPath); loader2.setResponseType(responseType); loader2.setWithCredentials(this.withCredentials); return new Promise((resolve, reject) => { loader2.load(url, resolve, void 0, reject); }); } 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(e2) { const message = e2.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(a6, b5) { return a6._taskLoad > b5._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 i4 = 0; i4 < this.workerPool.length; ++i4) { this.workerPool[i4].terminate(); } this.workerPool.length = 0; return this; } }; function DRACOWorker() { let decoderConfig; let decoderPending; onmessage = function(e2) { const message = e2.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 buffer2 = message.buffer; const taskConfig = message.taskConfig; decoderPending.then((module2) => { const draco = module2.draco; const decoder = new draco.Decoder(); const decoderBuffer = new draco.DecoderBuffer(); decoderBuffer.Init(new Int8Array(buffer2), buffer2.byteLength); try { const geometry3 = decodeGeometry(draco, decoder, decoderBuffer, taskConfig); const buffers = geometry3.attributes.map((attr) => attr.array.buffer); if (geometry3.index) buffers.push(geometry3.index.array.buffer); self.postMessage({ type: "decode", id: message.id, geometry: geometry3 }, buffers); } catch (error) { console.error(error); self.postMessage({ type: "error", id: message.id, error: error.message }); } finally { draco.destroy(decoderBuffer); draco.destroy(decoder); } }); break; } }; function decodeGeometry(draco, decoder, decoderBuffer, taskConfig) { const attributeIDs = taskConfig.attributeIDs; const attributeTypes = taskConfig.attributeTypes; let dracoGeometry; let decodingStatus; const geometryType = decoder.GetEncodedGeometryType(decoderBuffer); if (geometryType === draco.TRIANGULAR_MESH) { dracoGeometry = new draco.Mesh(); decodingStatus = decoder.DecodeBufferToMesh(decoderBuffer, dracoGeometry); } else if (geometryType === draco.POINT_CLOUD) { dracoGeometry = new draco.PointCloud(); decodingStatus = decoder.DecodeBufferToPointCloud(decoderBuffer, 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 geometry3 = { 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); } geometry3.attributes.push(decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute)); } if (geometryType === draco.TRIANGULAR_MESH) { geometry3.index = decodeIndex(draco, decoder, dracoGeometry); } draco.destroy(dracoGeometry); return geometry3; } 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-stdlib/lines/LineSegmentsGeometry.js var _box = new Box3(); var _vector5 = new Vector3(); var LineSegmentsGeometry = class extends InstancedBufferGeometry { 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)); } applyMatrix4(matrix6) { const start = this.attributes.instanceStart; const end = this.attributes.instanceEnd; if (start !== void 0) { start.applyMatrix4(matrix6); end.applyMatrix4(matrix6); start.needsUpdate = true; } if (this.boundingBox !== null) { this.computeBoundingBox(); } if (this.boundingSphere !== null) { this.computeBoundingSphere(); } return this; } 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.computeBoundingBox(); this.computeBoundingSphere(); return this; } setColors(array, itemSize = 3) { let colors2; if (array instanceof Float32Array) { colors2 = array; } else if (Array.isArray(array)) { colors2 = new Float32Array(array); } const instanceColorBuffer = new InstancedInterleavedBuffer(colors2, itemSize * 2, 1); this.setAttribute("instanceColorStart", new InterleavedBufferAttribute(instanceColorBuffer, itemSize, 0)); this.setAttribute("instanceColorEnd", new InterleavedBufferAttribute(instanceColorBuffer, itemSize, itemSize)); return this; } fromWireframeGeometry(geometry3) { this.setPositions(geometry3.attributes.position.array); return this; } fromEdgesGeometry(geometry3) { this.setPositions(geometry3.attributes.position.array); return this; } fromMesh(mesh) { this.fromWireframeGeometry(new WireframeGeometry(mesh.geometry)); return this; } fromLineSegments(lineSegments) { const geometry3 = lineSegments.geometry; this.setPositions(geometry3.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 center3 = this.boundingSphere.center; this.boundingBox.getCenter(center3); let maxRadiusSq = 0; for (let i4 = 0, il = start.count; i4 < il; i4++) { _vector5.fromBufferAttribute(start, i4); maxRadiusSq = Math.max(maxRadiusSq, center3.distanceToSquared(_vector5)); _vector5.fromBufferAttribute(end, i4); maxRadiusSq = Math.max(maxRadiusSq, center3.distanceToSquared(_vector5)); } 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() { } applyMatrix(matrix6) { console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4()."); return this.applyMatrix4(matrix6); } }; // node_modules/three-stdlib/lines/LineGeometry.js var LineGeometry = class extends LineSegmentsGeometry { constructor() { super(); this.isLineGeometry = true; this.type = "LineGeometry"; } setPositions(array) { const length3 = array.length - 3; const points = new Float32Array(2 * length3); for (let i4 = 0; i4 < length3; i4 += 3) { points[2 * i4] = array[i4]; points[2 * i4 + 1] = array[i4 + 1]; points[2 * i4 + 2] = array[i4 + 2]; points[2 * i4 + 3] = array[i4 + 3]; points[2 * i4 + 4] = array[i4 + 4]; points[2 * i4 + 5] = array[i4 + 5]; } super.setPositions(points); return this; } setColors(array, itemSize = 3) { const length3 = array.length - itemSize; const colors2 = new Float32Array(2 * length3); if (itemSize === 3) { for (let i4 = 0; i4 < length3; i4 += itemSize) { colors2[2 * i4] = array[i4]; colors2[2 * i4 + 1] = array[i4 + 1]; colors2[2 * i4 + 2] = array[i4 + 2]; colors2[2 * i4 + 3] = array[i4 + 3]; colors2[2 * i4 + 4] = array[i4 + 4]; colors2[2 * i4 + 5] = array[i4 + 5]; } } else { for (let i4 = 0; i4 < length3; i4 += itemSize) { colors2[2 * i4] = array[i4]; colors2[2 * i4 + 1] = array[i4 + 1]; colors2[2 * i4 + 2] = array[i4 + 2]; colors2[2 * i4 + 3] = array[i4 + 3]; colors2[2 * i4 + 4] = array[i4 + 4]; colors2[2 * i4 + 5] = array[i4 + 5]; colors2[2 * i4 + 6] = array[i4 + 6]; colors2[2 * i4 + 7] = array[i4 + 7]; } } super.setColors(colors2, itemSize); return this; } fromLine(line) { const geometry3 = line.geometry; this.setPositions(geometry3.attributes.position.array); return this; } }; // node_modules/three-stdlib/lines/LineMaterial.js var LineMaterial = class extends ShaderMaterial { constructor(parameters) { super({ type: "LineMaterial", uniforms: UniformsUtils.clone( UniformsUtils.merge([ UniformsLib.common, UniformsLib.fog, { 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 } ]) ), vertexShader: ( /* glsl */ ` #include #include #include #include uniform float linewidth; uniform vec2 resolution; attribute vec3 instanceStart; attribute vec3 instanceEnd; #ifdef USE_COLOR #ifdef USE_LINE_COLOR_ALPHA varying vec4 vLineColor; attribute vec4 instanceColorStart; attribute vec4 instanceColorEnd; #else varying vec3 vLineColor; attribute vec3 instanceColorStart; attribute vec3 instanceColorEnd; #endif #endif #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 vLineColor = ( 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 // get the offset direction as perpendicular to the view vector vec3 worldDir = normalize( end.xyz - start.xyz ); vec3 offset; if ( position.y < 0.5 ) { offset = normalize( cross( start.xyz, worldDir ) ); } else { offset = normalize( cross( end.xyz, worldDir ) ); } // sign flip if ( position.x < 0.0 ) offset *= - 1.0; float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) ); // don't extend the line if we're rendering dashes because we // won't be rendering the endcaps #ifndef USE_DASH // extend the line bounds to encompass endcaps start.xyz += - worldDir * linewidth * 0.5; end.xyz += worldDir * linewidth * 0.5; // shift the position of the quad so it hugs the forward edge of the line offset.xy -= dir * forwardOffset; offset.z += 0.5; #endif // endcaps if ( position.y > 1.0 || position.y < 0.0 ) { offset.xy += dir * 2.0 * forwardOffset; } // adjust for linewidth offset *= linewidth * 0.5; // set the world position worldPos = ( position.y < 0.5 ) ? start : end; worldPos.xyz += offset; // 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 #include #include } ` ), 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 #include #include #include #ifdef USE_COLOR #ifdef USE_LINE_COLOR_ALPHA varying vec4 vLineColor; #else varying vec3 vLineColor; #endif #endif vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) { float mua; float mub; vec3 p13 = p1 - p3; vec3 p43 = p4 - p3; vec3 p21 = p2 - p1; float d1343 = dot( p13, p43 ); float d4321 = dot( p43, p21 ); float d1321 = dot( p13, p21 ); float d4343 = dot( p43, p43 ); float d2121 = dot( p21, p21 ); float denom = d2121 * d4343 - d4321 * d4321; float numer = d1343 * d4321 - d1321 * d4343; mua = numer / denom; mua = clamp( mua, 0.0, 1.0 ); mub = ( d1343 + d4321 * ( mua ) ) / d4343; mub = clamp( mub, 0.0, 1.0 ); return vec2( mua, mub ); } void main() { #include #ifdef USE_DASH if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX #endif float alpha = opacity; #ifdef WORLD_UNITS // Find the closest points on the view ray and the line segment vec3 rayEnd = normalize( worldPos.xyz ) * 1e5; vec3 lineDir = worldEnd - worldStart; vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd ); vec3 p1 = worldStart + lineDir * params.x; vec3 p2 = rayEnd * params.y; vec3 delta = p1 - p2; float len = length( delta ); float norm = len / linewidth; #ifndef USE_DASH #ifdef USE_ALPHA_TO_COVERAGE float dnorm = fwidth( norm ); alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm ); #else if ( norm > 0.5 ) { discard; } #endif #endif #else #ifdef USE_ALPHA_TO_COVERAGE // artifacts appear on some hardware if a derivative is taken within a conditional float a = vUv.x; float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; float len2 = a * a + b * b; float dlen = fwidth( len2 ); if ( abs( vUv.y ) > 1.0 ) { alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 ); } #else if ( abs( vUv.y ) > 1.0 ) { float a = vUv.x; float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; float len2 = a * a + b * b; if ( len2 > 1.0 ) discard; } #endif #endif vec4 diffuseColor = vec4( diffuse, alpha ); #ifdef USE_COLOR #ifdef USE_LINE_COLOR_ALPHA diffuseColor *= vLineColor; #else diffuseColor.rgb *= vLineColor; #endif #endif #include gl_FragColor = diffuseColor; #include #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}> #include #include } ` ), clipping: true // required for clipping support }); this.isLineMaterial = true; this.onBeforeCompile = function() { if (this.transparent) { this.defines.USE_LINE_COLOR_ALPHA = "1"; } else { delete this.defines.USE_LINE_COLOR_ALPHA; } }; Object.defineProperties(this, { color: { enumerable: true, get: function() { return this.uniforms.diffuse.value; }, set: function(value) { this.uniforms.diffuse.value = value; } }, worldUnits: { enumerable: true, get: function() { return "WORLD_UNITS" in this.defines; }, set: function(value) { if (value === true) { this.defines.WORLD_UNITS = ""; } else { delete this.defines.WORLD_UNITS; } } }, linewidth: { enumerable: true, get: function() { return this.uniforms.linewidth.value; }, set: function(value) { this.uniforms.linewidth.value = value; } }, dashed: { enumerable: true, get: function() { return Boolean("USE_DASH" in this.defines); }, set(value) { if (Boolean(value) !== Boolean("USE_DASH" in this.defines)) { this.needsUpdate = true; } if (value === true) { this.defines.USE_DASH = ""; } else { delete this.defines.USE_DASH; } } }, dashScale: { enumerable: true, get: function() { return this.uniforms.dashScale.value; }, set: function(value) { this.uniforms.dashScale.value = value; } }, dashSize: { enumerable: true, get: function() { return this.uniforms.dashSize.value; }, set: function(value) { this.uniforms.dashSize.value = value; } }, dashOffset: { enumerable: true, get: function() { return this.uniforms.dashOffset.value; }, set: function(value) { this.uniforms.dashOffset.value = value; } }, gapSize: { enumerable: true, get: function() { return this.uniforms.gapSize.value; }, set: function(value) { this.uniforms.gapSize.value = value; } }, opacity: { enumerable: true, get: function() { return this.uniforms.opacity.value; }, set: function(value) { this.uniforms.opacity.value = value; } }, resolution: { enumerable: true, get: function() { return this.uniforms.resolution.value; }, set: function(value) { this.uniforms.resolution.value.copy(value); } }, alphaToCoverage: { enumerable: true, get: function() { return Boolean("USE_ALPHA_TO_COVERAGE" in this.defines); }, set: function(value) { if (Boolean(value) !== Boolean("USE_ALPHA_TO_COVERAGE" in this.defines)) { this.needsUpdate = true; } if (value === true) { this.defines.USE_ALPHA_TO_COVERAGE = ""; this.extensions.derivatives = true; } else { delete this.defines.USE_ALPHA_TO_COVERAGE; this.extensions.derivatives = false; } } } }); this.setValues(parameters); } }; // node_modules/three-stdlib/lines/Wireframe.js var _start = new Vector3(); var _end = new Vector3(); var _viewport = new Vector4(); // node_modules/three-stdlib/lines/LineSegments2.js var _viewport2 = new Vector4(); var _start2 = new Vector3(); var _end2 = 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 _sphere2 = new Sphere(); var _clipToWorldVector = new Vector4(); var _ray3; var _lineWidth; function getWorldSpaceHalfWidth(camera, distance3, resolution) { _clipToWorldVector.set(0, 0, -distance3, 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 geometry3 = lineSegments.geometry; const instanceStart = geometry3.attributes.instanceStart; const instanceEnd = geometry3.attributes.instanceEnd; const segmentCount = Math.min(geometry3.instanceCount, instanceStart.count); for (let i4 = 0, l2 = segmentCount; i4 < l2; i4++) { _line.start.fromBufferAttribute(instanceStart, i4); _line.end.fromBufferAttribute(instanceEnd, i4); _line.applyMatrix4(matrixWorld); const pointOnLine = new Vector3(); const point = new Vector3(); _ray3.distanceSqToSegment(_line.start, _line.end, point, pointOnLine); const isInside = point.distanceTo(pointOnLine) < _lineWidth * 0.5; if (isInside) { intersects.push({ point, pointOnLine, distance: _ray3.origin.distanceTo(point), object: lineSegments, face: null, faceIndex: i4, 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 geometry3 = lineSegments.geometry; const instanceStart = geometry3.attributes.instanceStart; const instanceEnd = geometry3.attributes.instanceEnd; const segmentCount = Math.min(geometry3.instanceCount, instanceStart.count); const near = -camera.near; _ray3.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 i4 = 0, l2 = segmentCount; i4 < l2; i4++) { _start4.fromBufferAttribute(instanceStart, i4); _end4.fromBufferAttribute(instanceEnd, i4); _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, i4); _line.end.fromBufferAttribute(instanceEnd, i4); _line.start.applyMatrix4(matrixWorld); _line.end.applyMatrix4(matrixWorld); const pointOnLine = new Vector3(); const point = new Vector3(); _ray3.distanceSqToSegment(_line.start, _line.end, point, pointOnLine); intersects.push({ point, pointOnLine, distance: _ray3.origin.distanceTo(point), object: lineSegments, face: null, faceIndex: i4, uv: null, [UV1]: null }); } } } var LineSegments2 = class extends Mesh { constructor(geometry3 = new LineSegmentsGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) { super(geometry3, material); this.isLineSegments2 = true; this.type = "LineSegments2"; } // for backwards-compatibility, but could be a method of LineSegmentsGeometry... computeLineDistances() { const geometry3 = this.geometry; const instanceStart = geometry3.attributes.instanceStart; const instanceEnd = geometry3.attributes.instanceEnd; const lineDistances = new Float32Array(2 * instanceStart.count); for (let i4 = 0, j = 0, l2 = instanceStart.count; i4 < l2; i4++, j += 2) { _start2.fromBufferAttribute(instanceStart, i4); _end2.fromBufferAttribute(instanceEnd, i4); lineDistances[j] = j === 0 ? 0 : lineDistances[j - 1]; lineDistances[j + 1] = lineDistances[j] + _start2.distanceTo(_end2); } const instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1); geometry3.setAttribute("instanceDistanceStart", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0)); geometry3.setAttribute("instanceDistanceEnd", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1)); return this; } 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; _ray3 = raycaster.ray; const matrixWorld = this.matrixWorld; const geometry3 = this.geometry; const material = this.material; _lineWidth = material.linewidth + threshold; if (geometry3.boundingSphere === null) { geometry3.computeBoundingSphere(); } _sphere2.copy(geometry3.boundingSphere).applyMatrix4(matrixWorld); let sphereMargin; if (worldUnits) { sphereMargin = _lineWidth * 0.5; } else { const distanceToSphere = Math.max(camera.near, _sphere2.distanceToPoint(_ray3.origin)); sphereMargin = getWorldSpaceHalfWidth(camera, distanceToSphere, material.resolution); } _sphere2.radius += sphereMargin; if (_ray3.intersectsSphere(_sphere2) === false) { return; } if (geometry3.boundingBox === null) { geometry3.computeBoundingBox(); } _box2.copy(geometry3.boundingBox).applyMatrix4(matrixWorld); let boxMargin; if (worldUnits) { boxMargin = _lineWidth * 0.5; } else { const distanceToBox = Math.max(camera.near, _box2.distanceToPoint(_ray3.origin)); boxMargin = getWorldSpaceHalfWidth(camera, distanceToBox, material.resolution); } _box2.expandByScalar(boxMargin); if (_ray3.intersectsBox(_box2) === false) { return; } if (worldUnits) { raycastWorldUnits(this, intersects); } else { raycastScreenSpace(this, camera, intersects); } } onBeforeRender(renderer) { const uniforms = this.material.uniforms; if (uniforms && uniforms.resolution) { renderer.getViewport(_viewport2); this.material.uniforms.resolution.value.set(_viewport2.z, _viewport2.w); } } }; // node_modules/three-stdlib/lines/Line2.js var Line2 = class extends LineSegments2 { constructor(geometry3 = new LineGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) { super(geometry3, material); this.isLine2 = true; this.type = "Line2"; } }; // node_modules/three-stdlib/helpers/RaycasterHelper.js var _o = new Object3D(); var _v = new Vector3(); // node_modules/three-stdlib/helpers/VertexTangentsHelper.js var _v15 = new Vector3(); var _v23 = new Vector3(); // node_modules/three-stdlib/helpers/VertexNormalsHelper.js var _v16 = new Vector3(); var _v24 = new Vector3(); var _normalMatrix = new Matrix3(); // node_modules/three-stdlib/deprecated/Geometry.js var _m12 = new Matrix4(); var _obj = new Object3D(); var _offset = new Vector3(); // node_modules/three-stdlib/libs/MeshoptDecoder.js var generated; var MeshoptDecoder = () => { if (generated) return generated; const wasm_base = "B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB"; const wasm_simd = "B9h9z9tFBBBFiI9gBB9gLaaaaaFa9gEaaaB9gFaFaEMcBBFBFFGGGEILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBOn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBNI9z9iqlBVc+N9IcIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMk8lLbaE97F9+FaL978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAeDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAeDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBReCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBH8ZCFD9tA8ZAPD9OD9hD9RH8ZDQBTFtGmEYIPLdKeOnHpAIAQJDBIBHyCFD9tAyAPD9OD9hD9RHyAIASJDBIBH8cCFD9tA8cAPD9OD9hD9RH8cDQBTFtGmEYIPLdKeOnH8dDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAeD9uHeDyBjGBAEAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeApA8dDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNiV8ZcpMyS8cQ8df8eb8fHdAyA8cDQNiV8ZcpMyS8cQ8df8eb8fH8ZDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/dLEK97FaF97GXGXAGCI9HQBAF9FQFCBRGEXABABDBBBHECiD+rFCiD+sFD/6FHIAECND+rFCiD+sFD/6FAID/gFAECTD+rFCiD+sFD/6FHLD/gFD/kFD/lFHKCBDtD+2FHOAICUUUU94DtHND9OD9RD/kFHI9DBB/+hDYAIAID/mFAKAKD/mFALAOALAND9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHLD/mF9DBBX9LDYHOD/kFCgFDtD9OAECUUU94DtD9OD9QAIALD/mFAOD/kFCND+rFCU/+EDtD9OD9QAKALD/mFAOD/kFCTD+rFCUU/8ODtD9OD9QDMBBABCTJRBAGCIJHGAF9JQBSGMMAF9FQBCBRGEXABCTJHVAVDBBBHECBDtHOCUU98D8cFCUU98D8cEHND9OABDBBBHKAEDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAKAEDQBFGENVcMTtmYi8ZpyHECTD+sFD/6FHID/gFAECTD+rFCTD+sFD/6FHLD/gFD/kFD/lFHE9DB/+g6DYALAEAOD+2FHOALCUUUU94DtHcD9OD9RD/kFHLALD/mFAEAED/mFAIAOAIAcD9OD9RD/kFHEAED/mFD/kFD/kFD/jFD/nFHID/mF9DBBX9LDYHOD/kFCTD+rFALAID/mFAOD/kFCggEDtD9OD9QHLAEAID/mFAOD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHEDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAKAND9OALAEDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM/hEIGaF97FaL978jUUUUBCTlREGXAF9FQBCBRIEXAEABDBBBHLABCTJHKDBBBHODQILKOSQfbPden8c8d8e8fHNCTD+sFHVCID+rFDMIBAB9DBBU8/DY9D/zI818/DYAVCEDtD9QD/6FD/nFHVALAODQBFGENVcMTtmYi8ZpyHLCTD+rFCTD+sFD/6FD/mFHOAOD/mFAVALCTD+sFD/6FD/mFHcAcD/mFAVANCTD+rFCTD+sFD/6FD/mFHNAND/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHVD/mF9DBBX9LDYHLD/kFCggEDtHMD9OAcAVD/mFALD/kFCTD+rFD9QHcANAVD/mFALD/kFCTD+rFAOAVD/mFALD/kFAMD9OD9QHVDQBFTtGEmYILPdKOenHLD8dBAEDBIBDyB+t+J83EBABCNJALD8dFAEDBIBDyF+t+J83EBAKAcAVDQNVi8ZcMpySQ8c8dfb8e8fHVD8dBAEDBIBDyG+t+J83EBABCiJAVD8dFAEDBIBDyE+t+J83EBABCAJRBAICIJHIAF9JQBMMM9jFF97GXAGCGrAF9sHG9FQBCBRFEXABABDBBBHECND+rFCND+sFD/6FAECiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBABCTJRBAFCIJHFAG9JQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB"; const detector = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11, 7, 0, 65, 0, 253, 15, 26, 11 ]); const wasmpack = new Uint8Array([ 32, 0, 65, 253, 3, 1, 2, 34, 4, 106, 6, 5, 11, 8, 7, 20, 13, 33, 12, 16, 128, 9, 116, 64, 19, 113, 127, 15, 10, 21, 22, 14, 255, 66, 24, 54, 136, 107, 18, 23, 192, 26, 114, 118, 132, 17, 77, 101, 130, 144, 27, 87, 131, 44, 45, 74, 156, 154, 70, 167 ]); if (typeof WebAssembly !== "object") { return { supported: false }; } let wasm2 = wasm_base; if (WebAssembly.validate(detector)) { wasm2 = wasm_simd; } let instance2; const promise = WebAssembly.instantiate(unpack(wasm2), {}).then((result) => { instance2 = result.instance; instance2.exports.__wasm_call_ctors(); }); function unpack(data) { const result = new Uint8Array(data.length); for (let i4 = 0; i4 < data.length; ++i4) { const ch3 = data.charCodeAt(i4); result[i4] = ch3 > 96 ? ch3 - 71 : ch3 > 64 ? ch3 - 65 : ch3 > 47 ? ch3 + 4 : ch3 > 46 ? 63 : 62; } let write = 0; for (let i4 = 0; i4 < data.length; ++i4) { result[write++] = result[i4] < 60 ? wasmpack[result[i4]] : (result[i4] - 60) * 64 + result[++i4]; } return result.buffer.slice(0, write); } function decode(fun, target2, count, size2, source, filter) { const sbrk = instance2.exports.sbrk; const count4 = count + 3 & ~3; const tp = sbrk(count4 * size2); const sp = sbrk(source.length); const heap2 = new Uint8Array(instance2.exports.memory.buffer); heap2.set(source, sp); const res = fun(tp, count, size2, sp, source.length); if (res === 0 && filter) { filter(tp, count4, size2); } target2.set(heap2.subarray(tp, tp + count * size2)); sbrk(tp - sbrk(0)); if (res !== 0) { throw new Error(`Malformed buffer data: ${res}`); } } const filters = { // legacy index-based enums for glTF 0: "", 1: "meshopt_decodeFilterOct", 2: "meshopt_decodeFilterQuat", 3: "meshopt_decodeFilterExp", // string-based enums for glTF NONE: "", OCTAHEDRAL: "meshopt_decodeFilterOct", QUATERNION: "meshopt_decodeFilterQuat", EXPONENTIAL: "meshopt_decodeFilterExp" }; const decoders = { // legacy index-based enums for glTF 0: "meshopt_decodeVertexBuffer", 1: "meshopt_decodeIndexBuffer", 2: "meshopt_decodeIndexSequence", // string-based enums for glTF ATTRIBUTES: "meshopt_decodeVertexBuffer", TRIANGLES: "meshopt_decodeIndexBuffer", INDICES: "meshopt_decodeIndexSequence" }; generated = { ready: promise, supported: true, decodeVertexBuffer(target2, count, size2, source, filter) { decode( instance2.exports.meshopt_decodeVertexBuffer, target2, count, size2, source, instance2.exports[filters[filter]] ); }, decodeIndexBuffer(target2, count, size2, source) { decode(instance2.exports.meshopt_decodeIndexBuffer, target2, count, size2, source); }, decodeIndexSequence(target2, count, size2, source) { decode(instance2.exports.meshopt_decodeIndexSequence, target2, count, size2, source); }, decodeGltfBuffer(target2, count, size2, source, mode, filter) { decode( instance2.exports[decoders[mode]], target2, count, size2, source, instance2.exports[filters[filter]] ); } }; return generated; }; // node_modules/zustand/esm/vanilla/shallow.mjs var isIterable = (obj) => Symbol.iterator in obj; var hasIterableEntries = (value) => ( // HACK: avoid checking entries type "entries" in value ); var compareEntries = (valueA, valueB) => { const mapA = valueA instanceof Map ? valueA : new Map(valueA.entries()); const mapB = valueB instanceof Map ? valueB : new Map(valueB.entries()); if (mapA.size !== mapB.size) { return false; } for (const [key, value] of mapA) { if (!mapB.has(key) || !Object.is(value, mapB.get(key))) { return false; } } return true; }; var compareIterables = (valueA, valueB) => { const iteratorA = valueA[Symbol.iterator](); const iteratorB = valueB[Symbol.iterator](); let nextA = iteratorA.next(); let nextB = iteratorB.next(); while (!nextA.done && !nextB.done) { if (!Object.is(nextA.value, nextB.value)) { return false; } nextA = iteratorA.next(); nextB = iteratorB.next(); } return !!nextA.done && !!nextB.done; }; function shallow(valueA, valueB) { if (Object.is(valueA, valueB)) { return true; } if (typeof valueA !== "object" || valueA === null || typeof valueB !== "object" || valueB === null) { return false; } if (Object.getPrototypeOf(valueA) !== Object.getPrototypeOf(valueB)) { return false; } if (isIterable(valueA) && isIterable(valueB)) { if (hasIterableEntries(valueA) && hasIterableEntries(valueB)) { return compareEntries(valueA, valueB); } return compareIterables(valueA, valueB); } return compareEntries( { entries: () => Object.entries(valueA) }, { entries: () => Object.entries(valueB) } ); } // node_modules/zustand/esm/react/shallow.mjs var import_react4 = __toESM(require_react(), 1); // node_modules/@react-three/drei/web/Select.js var context4 = React12.createContext([]); function Select({ box, multiple, children, onChange, onChangePointerUp, border = "1px solid #55aaff", backgroundColor = "rgba(75, 160, 255, 0.1)", filter: customFilter = (item) => item, ...props }) { const [downed, down] = React12.useState(false); const { setEvents, camera, raycaster, gl, controls, size: size2, get } = useThree(); const [hovered, hover] = React12.useState(false); const [active, dispatch] = React12.useReducer( // @ts-expect-error (state, { object, shift }) => { if (object === void 0) return []; else if (Array.isArray(object)) return object; else if (!shift) return state[0] === object ? [] : [object]; else if (state.includes(object)) return state.filter((o2) => o2 !== object); else return [object, ...state]; }, [] ); React12.useEffect(() => { if (downed) onChange == null || onChange(active); else onChangePointerUp == null || onChangePointerUp(active); }, [active, downed]); const onClick = React12.useCallback((e2) => { e2.stopPropagation(); dispatch({ object: customFilter([e2.object])[0], shift: multiple && e2.shiftKey }); }, []); const onPointerMissed = React12.useCallback((e2) => !hovered && dispatch({}), [hovered]); const ref = React12.useRef(null); React12.useEffect(() => { if (!box || !multiple) return; const selBox = new SelectionBox(camera, ref.current); const element = document.createElement("div"); element.style.pointerEvents = "none"; element.style.border = border; element.style.backgroundColor = backgroundColor; element.style.position = "fixed"; const startPoint = new Vector2(); const pointTopLeft = new Vector2(); const pointBottomRight = new Vector2(); const oldRaycasterEnabled = get().events.enabled; const oldControlsEnabled = controls == null ? void 0 : controls.enabled; let isDown = false; function prepareRay(event, vec) { const { offsetX, offsetY } = event; const { width, height } = size2; vec.set(offsetX / width * 2 - 1, -(offsetY / height) * 2 + 1); } function onSelectStart(event) { var _gl$domElement$parent; if (controls) controls.enabled = false; setEvents({ enabled: false }); down(isDown = true); (_gl$domElement$parent = gl.domElement.parentElement) == null || _gl$domElement$parent.appendChild(element); element.style.left = `${event.clientX}px`; element.style.top = `${event.clientY}px`; element.style.width = "0px"; element.style.height = "0px"; startPoint.x = event.clientX; startPoint.y = event.clientY; } function onSelectMove(event) { pointBottomRight.x = Math.max(startPoint.x, event.clientX); pointBottomRight.y = Math.max(startPoint.y, event.clientY); pointTopLeft.x = Math.min(startPoint.x, event.clientX); pointTopLeft.y = Math.min(startPoint.y, event.clientY); element.style.left = `${pointTopLeft.x}px`; element.style.top = `${pointTopLeft.y}px`; element.style.width = `${pointBottomRight.x - pointTopLeft.x}px`; element.style.height = `${pointBottomRight.y - pointTopLeft.y}px`; } function onSelectOver() { if (isDown) { var _element$parentElemen; if (controls) controls.enabled = oldControlsEnabled; setEvents({ enabled: oldRaycasterEnabled }); down(isDown = false); (_element$parentElemen = element.parentElement) == null || _element$parentElemen.removeChild(element); } } function pointerDown(event) { if (event.shiftKey) { onSelectStart(event); prepareRay(event, selBox.startPoint); } } let previous = []; function pointerMove(event) { if (isDown) { onSelectMove(event); prepareRay(event, selBox.endPoint); const allSelected = selBox.select().sort((o2) => o2.uuid).filter((o2) => o2.isMesh); if (!shallow(allSelected, previous)) { previous = allSelected; dispatch({ object: customFilter(allSelected) }); } } } function pointerUp(event) { if (isDown) onSelectOver(); } document.addEventListener("pointerdown", pointerDown, { passive: true }); document.addEventListener("pointermove", pointerMove, { passive: true, capture: true }); document.addEventListener("pointerup", pointerUp, { passive: true }); return () => { document.removeEventListener("pointerdown", pointerDown); document.removeEventListener("pointermove", pointerMove, true); document.removeEventListener("pointerup", pointerUp); }; }, [size2.width, size2.height, raycaster, camera, controls, gl]); return React12.createElement("group", _extends({ ref, onClick, onPointerOver: () => hover(true), onPointerOut: () => hover(false), onPointerMissed }, props), React12.createElement(context4.Provider, { value: active }, children)); } function useSelect() { return React12.useContext(context4); } // node_modules/@react-three/drei/core/Billboard.js var React13 = __toESM(require_react()); var Billboard = React13.forwardRef(function Billboard2({ children, follow = true, lockX = false, lockY = false, lockZ = false, ...props }, fref) { const inner = React13.useRef(null); const localRef = React13.useRef(null); const q = new Quaternion(); useFrame(({ camera }) => { if (!follow || !localRef.current) return; const prevRotation = inner.current.rotation.clone(); localRef.current.updateMatrix(); localRef.current.updateWorldMatrix(false, false); localRef.current.getWorldQuaternion(q); camera.getWorldQuaternion(inner.current.quaternion).premultiply(q.invert()); if (lockX) inner.current.rotation.x = prevRotation.x; if (lockY) inner.current.rotation.y = prevRotation.y; if (lockZ) inner.current.rotation.z = prevRotation.z; }); React13.useImperativeHandle(fref, () => localRef.current, []); return React13.createElement("group", _extends({ ref: localRef }, props), React13.createElement("group", { ref: inner }, children)); }); // node_modules/@react-three/drei/core/ScreenSpace.js var React14 = __toESM(require_react()); var ScreenSpace = React14.forwardRef(({ children, depth = -1, ...rest }, ref) => { const localRef = React14.useRef(null); React14.useImperativeHandle(ref, () => localRef.current, []); useFrame(({ camera }) => { localRef.current.quaternion.copy(camera.quaternion); localRef.current.position.copy(camera.position); }); return React14.createElement("group", _extends({ ref: localRef }, rest), React14.createElement("group", { "position-z": -depth }, children)); }); // node_modules/@react-three/drei/core/ScreenSizer.js var React15 = __toESM(require_react()); var import_react5 = __toESM(require_react()); // node_modules/@react-three/drei/core/calculateScaleFactor.js var tV0 = new Vector3(); var tV1 = new Vector3(); var tV2 = new Vector3(); var getPoint2 = (point3, camera, size2) => { const widthHalf = size2.width / 2; const heightHalf = size2.height / 2; camera.updateMatrixWorld(false); const vector = point3.project(camera); vector.x = vector.x * widthHalf + widthHalf; vector.y = -(vector.y * heightHalf) + heightHalf; return vector; }; var getPoint3 = (point2, camera, size2, zValue = 1) => { const vector = tV0.set(point2.x / size2.width * 2 - 1, -(point2.y / size2.height) * 2 + 1, zValue); vector.unproject(camera); return vector; }; var calculateScaleFactor = (point3, radiusPx, camera, size2) => { const point2 = getPoint2(tV2.copy(point3), camera, size2); let scale5 = 0; for (let i4 = 0; i4 < 2; ++i4) { const point2off = tV1.copy(point2).setComponent(i4, point2.getComponent(i4) + radiusPx); const point3off = getPoint3(point2off, camera, size2, point2off.z); scale5 = Math.max(scale5, point3.distanceTo(point3off)); } return scale5; }; // node_modules/@react-three/drei/core/ScreenSizer.js var worldPos = new Vector3(); var ScreenSizer = (0, import_react5.forwardRef)(({ scale: scale5 = 1, ...props }, ref) => { const container = (0, import_react5.useRef)(null); React15.useImperativeHandle(ref, () => container.current, []); useFrame((state) => { const obj = container.current; if (!obj) return; const sf = calculateScaleFactor(obj.getWorldPosition(worldPos), scale5, state.camera, state.size); obj.scale.setScalar(sf * scale5); }); return React15.createElement("object3D", _extends({ ref: container }, props)); }); // node_modules/@react-three/drei/core/QuadraticBezierLine.js var React17 = __toESM(require_react()); // node_modules/@react-three/drei/core/Line.js var React16 = __toESM(require_react()); var Line4 = React16.forwardRef(function Line5({ points, color = 16777215, vertexColors, linewidth, lineWidth, segments, dashed, ...rest }, ref) { var _vertexColors$, _ref; const size2 = useThree((state) => state.size); const line2 = React16.useMemo(() => segments ? new LineSegments2() : new Line2(), [segments]); const [lineMaterial] = React16.useState(() => new LineMaterial()); const itemSize = (vertexColors == null || (_vertexColors$ = vertexColors[0]) == null ? void 0 : _vertexColors$.length) === 4 ? 4 : 3; const lineGeom = React16.useMemo(() => { const geom = segments ? new LineSegmentsGeometry() : new LineGeometry(); const pValues = points.map((p2) => { const isArray3 = Array.isArray(p2); return p2 instanceof Vector3 || p2 instanceof Vector4 ? [p2.x, p2.y, p2.z] : p2 instanceof Vector2 ? [p2.x, p2.y, 0] : isArray3 && p2.length === 3 ? [p2[0], p2[1], p2[2]] : isArray3 && p2.length === 2 ? [p2[0], p2[1], 0] : p2; }); geom.setPositions(pValues.flat()); if (vertexColors) { color = 16777215; const cValues = vertexColors.map((c2) => c2 instanceof Color ? c2.toArray() : c2); geom.setColors(cValues.flat(), itemSize); } return geom; }, [points, segments, vertexColors, itemSize]); React16.useLayoutEffect(() => { line2.computeLineDistances(); }, [points, line2]); React16.useLayoutEffect(() => { if (dashed) { lineMaterial.defines.USE_DASH = ""; } else { delete lineMaterial.defines.USE_DASH; } lineMaterial.needsUpdate = true; }, [dashed, lineMaterial]); React16.useEffect(() => { return () => { lineGeom.dispose(); lineMaterial.dispose(); }; }, [lineGeom]); return React16.createElement("primitive", _extends({ object: line2, ref }, rest), React16.createElement("primitive", { object: lineGeom, attach: "geometry" }), React16.createElement("primitive", _extends({ object: lineMaterial, attach: "material", color, vertexColors: Boolean(vertexColors), resolution: [size2.width, size2.height], linewidth: (_ref = linewidth !== null && linewidth !== void 0 ? linewidth : lineWidth) !== null && _ref !== void 0 ? _ref : 1, dashed, transparent: itemSize === 4 }, rest))); }); // node_modules/@react-three/drei/core/QuadraticBezierLine.js var v = new Vector3(); var QuadraticBezierLine = React17.forwardRef(function QuadraticBezierLine2({ start = [0, 0, 0], end = [0, 0, 0], mid, segments = 20, ...rest }, forwardref) { const ref = React17.useRef(null); React17.useImperativeHandle(forwardref, () => ref.current); const [curve] = React17.useState(() => new QuadraticBezierCurve3(void 0, void 0, void 0)); const getPoints = React17.useCallback((start2, end2, mid2, segments2 = 20) => { if (start2 instanceof Vector3) curve.v0.copy(start2); else curve.v0.set(...start2); if (end2 instanceof Vector3) curve.v2.copy(end2); else curve.v2.set(...end2); if (mid2 instanceof Vector3) { curve.v1.copy(mid2); } else if (Array.isArray(mid2)) { curve.v1.set(...mid2); } else { curve.v1.copy(curve.v0.clone().add(curve.v2.clone().sub(curve.v0)).add(v.set(0, curve.v0.y - curve.v2.y, 0))); } return curve.getPoints(segments2); }, []); React17.useLayoutEffect(() => { ref.current.setPoints = (start2, end2, mid2) => { const points2 = getPoints(start2, end2, mid2); if (ref.current.geometry) ref.current.geometry.setPositions(points2.map((p2) => p2.toArray()).flat()); }; }, []); const points = React17.useMemo(() => getPoints(start, end, mid, segments), [start, end, mid, segments]); return React17.createElement(Line4, _extends({ ref, points }, rest)); }); // node_modules/@react-three/drei/core/CubicBezierLine.js var React18 = __toESM(require_react()); var CubicBezierLine = React18.forwardRef(function CubicBezierLine2({ start, end, midA, midB, segments = 20, ...rest }, ref) { const points = React18.useMemo(() => { const startV = start instanceof Vector3 ? start : new Vector3(...start); const endV = end instanceof Vector3 ? end : new Vector3(...end); const midAV = midA instanceof Vector3 ? midA : new Vector3(...midA); const midBV = midB instanceof Vector3 ? midB : new Vector3(...midB); const interpolatedV = new CubicBezierCurve3(startV, midAV, midBV, endV).getPoints(segments); return interpolatedV; }, [start, end, midA, midB, segments]); return React18.createElement(Line4, _extends({ ref, points }, rest)); }); // node_modules/@react-three/drei/core/CatmullRomLine.js var React19 = __toESM(require_react()); var CatmullRomLine = React19.forwardRef(function CatmullRomLine2({ points, closed = false, curveType = "centripetal", tension = 0.5, segments = 20, vertexColors, ...rest }, ref) { const curve = React19.useMemo(() => { const mappedPoints = points.map((pt) => pt instanceof Vector3 ? pt : new Vector3(...pt)); return new CatmullRomCurve3(mappedPoints, closed, curveType, tension); }, [points, closed, curveType, tension]); const segmentedPoints = React19.useMemo(() => curve.getPoints(segments), [curve, segments]); const interpolatedVertexColors = React19.useMemo(() => { if (!vertexColors || vertexColors.length < 2) return void 0; if (vertexColors.length === segments + 1) return vertexColors; const mappedColors = vertexColors.map((color) => color instanceof Color ? color : new Color(...color)); if (closed) mappedColors.push(mappedColors[0].clone()); const iColors = [mappedColors[0]]; const divisions = segments / (mappedColors.length - 1); for (let i4 = 1; i4 < segments; i4++) { const alpha = i4 % divisions / divisions; const colorIndex = Math.floor(i4 / divisions); iColors.push(mappedColors[colorIndex].clone().lerp(mappedColors[colorIndex + 1], alpha)); } iColors.push(mappedColors[mappedColors.length - 1]); return iColors; }, [vertexColors, segments]); return React19.createElement(Line4, _extends({ ref, points: segmentedPoints, vertexColors: interpolatedVertexColors }, rest)); }); // node_modules/@react-three/drei/core/PositionalAudio.js var React20 = __toESM(require_react()); var PositionalAudio = React20.forwardRef(({ url, distance: distance3 = 1, loop = true, autoplay, ...props }, ref) => { const sound = React20.useRef(null); React20.useImperativeHandle(ref, () => sound.current, []); const camera = useThree(({ camera: camera2 }) => camera2); const [listener] = React20.useState(() => new AudioListener()); const buffer2 = useLoader(AudioLoader, url); React20.useEffect(() => { const _sound = sound.current; if (_sound) { _sound.setBuffer(buffer2); _sound.setRefDistance(distance3); _sound.setLoop(loop); if (autoplay && !_sound.isPlaying) _sound.play(); } }, [buffer2, camera, distance3, loop]); React20.useEffect(() => { const _sound = sound.current; camera.add(listener); return () => { camera.remove(listener); if (_sound) { if (_sound.isPlaying) _sound.stop(); if (_sound.source && _sound.source._connected) _sound.disconnect(); } }; }, []); return React20.createElement("positionalAudio", _extends({ ref: sound, args: [listener] }, props)); }); // node_modules/@react-three/drei/core/Text.js var React21 = __toESM(require_react()); // node_modules/troika-worker-utils/dist/troika-worker-utils.esm.js function workerBootstrap() { var modules = /* @__PURE__ */ Object.create(null); function registerModule(ref, callback) { var id = ref.id; var name = ref.name; var dependencies = ref.dependencies; if (dependencies === void 0) dependencies = []; var init3 = ref.init; if (init3 === void 0) init3 = function() { }; var getTransferables = ref.getTransferables; if (getTransferables === void 0) getTransferables = null; if (modules[id]) { return; } try { dependencies = dependencies.map(function(dep) { if (dep && dep.isWorkerModule) { registerModule(dep, function(depResult) { if (depResult instanceof Error) { throw depResult; } }); dep = modules[dep.id].value; } return dep; }); init3 = rehydrate("<" + name + ">.init", init3); if (getTransferables) { getTransferables = rehydrate("<" + name + ">.getTransferables", getTransferables); } var value = null; if (typeof init3 === "function") { value = init3.apply(void 0, dependencies); } else { console.error("worker module init function failed to rehydrate"); } modules[id] = { id, value, getTransferables }; callback(value); } catch (err) { if (!(err && err.noLog)) { console.error(err); } callback(err); } } function callModule(ref, callback) { var ref$1; var id = ref.id; var args = ref.args; if (!modules[id] || typeof modules[id].value !== "function") { callback(new Error("Worker module " + id + ": not found or its 'init' did not return a function")); } try { var result = (ref$1 = modules[id]).value.apply(ref$1, args); if (result && typeof result.then === "function") { result.then(handleResult, function(rej) { return callback(rej instanceof Error ? rej : new Error("" + rej)); }); } else { handleResult(result); } } catch (err) { callback(err); } function handleResult(result2) { try { var tx = modules[id].getTransferables && modules[id].getTransferables(result2); if (!tx || !Array.isArray(tx) || !tx.length) { tx = void 0; } callback(result2, tx); } catch (err) { console.error(err); callback(err); } } } function rehydrate(name, str) { var result = void 0; self.troikaDefine = function(r2) { return result = r2; }; var url = URL.createObjectURL( new Blob( ["/** " + name.replace(/\*/g, "") + " **/\n\ntroikaDefine(\n" + str + "\n)"], { type: "application/javascript" } ) ); try { importScripts(url); } catch (err) { console.error(err); } URL.revokeObjectURL(url); delete self.troikaDefine; return result; } self.addEventListener("message", function(e2) { var ref = e2.data; var messageId = ref.messageId; var action = ref.action; var data = ref.data; try { if (action === "registerModule") { registerModule(data, function(result) { if (result instanceof Error) { postMessage({ messageId, success: false, error: result.message }); } else { postMessage({ messageId, success: true, result: { isCallable: typeof result === "function" } }); } }); } if (action === "callModule") { callModule(data, function(result, transferables) { if (result instanceof Error) { postMessage({ messageId, success: false, error: result.message }); } else { postMessage({ messageId, success: true, result }, transferables || void 0); } }); } } catch (err) { postMessage({ messageId, success: false, error: err.stack }); } }); } function defineMainThreadModule(options) { var moduleFunc = function() { var args = [], len = arguments.length; while (len--) args[len] = arguments[len]; return moduleFunc._getInitResult().then(function(initResult) { if (typeof initResult === "function") { return initResult.apply(void 0, args); } else { throw new Error("Worker module function was called but `init` did not return a callable function"); } }); }; moduleFunc._getInitResult = function() { var dependencies = options.dependencies; var init3 = options.init; dependencies = Array.isArray(dependencies) ? dependencies.map(function(dep) { if (dep) { dep = dep.onMainThread || dep; if (dep._getInitResult) { dep = dep._getInitResult(); } } return dep; }) : []; var initPromise = Promise.all(dependencies).then(function(deps) { return init3.apply(null, deps); }); moduleFunc._getInitResult = function() { return initPromise; }; return initPromise; }; return moduleFunc; } var supportsWorkers = function() { var supported = false; if (typeof window !== "undefined" && typeof window.document !== "undefined") { try { var worker = new Worker( URL.createObjectURL(new Blob([""], { type: "application/javascript" })) ); worker.terminate(); supported = true; } catch (err) { if (typeof process !== "undefined" && false) ; else { console.log( "Troika createWorkerModule: web workers not allowed; falling back to main thread execution. Cause: [" + err.message + "]" ); } } } supportsWorkers = function() { return supported; }; return supported; }; var _workerModuleId = 0; var _messageId = 0; var _allowInitAsString = false; var workers = /* @__PURE__ */ Object.create(null); var registeredModules = /* @__PURE__ */ Object.create(null); var openRequests = /* @__PURE__ */ Object.create(null); function defineWorkerModule(options) { if ((!options || typeof options.init !== "function") && !_allowInitAsString) { throw new Error("requires `options.init` function"); } var dependencies = options.dependencies; var init3 = options.init; var getTransferables = options.getTransferables; var workerId = options.workerId; var onMainThread = defineMainThreadModule(options); if (workerId == null) { workerId = "#default"; } var id = "workerModule" + ++_workerModuleId; var name = options.name || id; var registrationPromise = null; dependencies = dependencies && dependencies.map(function(dep) { if (typeof dep === "function" && !dep.workerModuleData) { _allowInitAsString = true; dep = defineWorkerModule({ workerId, name: "<" + name + "> function dependency: " + dep.name, init: "function(){return (\n" + stringifyFunction(dep) + "\n)}" }); _allowInitAsString = false; } if (dep && dep.workerModuleData) { dep = dep.workerModuleData; } return dep; }); function moduleFunc() { var args = [], len = arguments.length; while (len--) args[len] = arguments[len]; if (!supportsWorkers()) { return onMainThread.apply(void 0, args); } if (!registrationPromise) { registrationPromise = callWorker(workerId, "registerModule", moduleFunc.workerModuleData); var unregister = function() { registrationPromise = null; registeredModules[workerId].delete(unregister); }; (registeredModules[workerId] || (registeredModules[workerId] = /* @__PURE__ */ new Set())).add(unregister); } return registrationPromise.then(function(ref) { var isCallable = ref.isCallable; if (isCallable) { return callWorker(workerId, "callModule", { id, args }); } else { throw new Error("Worker module function was called but `init` did not return a callable function"); } }); } moduleFunc.workerModuleData = { isWorkerModule: true, id, name, dependencies, init: stringifyFunction(init3), getTransferables: getTransferables && stringifyFunction(getTransferables) }; moduleFunc.onMainThread = onMainThread; return moduleFunc; } function terminateWorker(workerId) { if (registeredModules[workerId]) { registeredModules[workerId].forEach(function(unregister) { unregister(); }); } if (workers[workerId]) { workers[workerId].terminate(); delete workers[workerId]; } } function stringifyFunction(fn) { var str = fn.toString(); if (!/^function/.test(str) && /^\w+\s*\(/.test(str)) { str = "function " + str; } return str; } function getWorker(workerId) { var worker = workers[workerId]; if (!worker) { var bootstrap = stringifyFunction(workerBootstrap); worker = workers[workerId] = new Worker( URL.createObjectURL( new Blob( ["/** Worker Module Bootstrap: " + workerId.replace(/\*/g, "") + " **/\n\n;(" + bootstrap + ")()"], { type: "application/javascript" } ) ) ); worker.onmessage = function(e2) { var response = e2.data; var msgId = response.messageId; var callback = openRequests[msgId]; if (!callback) { throw new Error("WorkerModule response with empty or unknown messageId"); } delete openRequests[msgId]; callback(response); }; } return worker; } function callWorker(workerId, action, data) { return new Promise(function(resolve, reject) { var messageId = ++_messageId; openRequests[messageId] = function(response) { if (response.success) { resolve(response.result); } else { reject(new Error("Error in worker " + action + " call: " + response.error)); } }; getWorker(workerId).postMessage({ messageId, action, data }); }); } // node_modules/webgl-sdf-generator/dist/webgl-sdf-generator.mjs function SDFGenerator() { var exports2 = (function(exports3) { function pointOnQuadraticBezier(x0, y0, x1, y1, x2, y2, t3, pointOut) { var t22 = 1 - t3; pointOut.x = t22 * t22 * x0 + 2 * t22 * t3 * x1 + t3 * t3 * x2; pointOut.y = t22 * t22 * y0 + 2 * t22 * t3 * y1 + t3 * t3 * y2; } function pointOnCubicBezier(x0, y0, x1, y1, x2, y2, x3, y3, t3, pointOut) { var t22 = 1 - t3; pointOut.x = t22 * t22 * t22 * x0 + 3 * t22 * t22 * t3 * x1 + 3 * t22 * t3 * t3 * x2 + t3 * t3 * t3 * x3; pointOut.y = t22 * t22 * t22 * y0 + 3 * t22 * t22 * t3 * y1 + 3 * t22 * t3 * t3 * y2 + t3 * t3 * t3 * y3; } function forEachPathCommand(pathString, commandCallback) { var segmentRE = /([MLQCZ])([^MLQCZ]*)/g; var match, firstX, firstY, prevX, prevY; while (match = segmentRE.exec(pathString)) { var args = match[2].replace(/^\s*|\s*$/g, "").split(/[,\s]+/).map(function(v5) { return parseFloat(v5); }); switch (match[1]) { case "M": prevX = firstX = args[0]; prevY = firstY = args[1]; break; case "L": if (args[0] !== prevX || args[1] !== prevY) { commandCallback("L", prevX, prevY, prevX = args[0], prevY = args[1]); } break; case "Q": { commandCallback("Q", prevX, prevY, prevX = args[2], prevY = args[3], args[0], args[1]); break; } case "C": { commandCallback("C", prevX, prevY, prevX = args[4], prevY = args[5], args[0], args[1], args[2], args[3]); break; } case "Z": if (prevX !== firstX || prevY !== firstY) { commandCallback("L", prevX, prevY, firstX, firstY); } break; } } } function pathToLineSegments(pathString, segmentCallback, curvePoints) { if (curvePoints === void 0) curvePoints = 16; var tempPoint = { x: 0, y: 0 }; forEachPathCommand(pathString, function(command, startX, startY, endX, endY, ctrl1X, ctrl1Y, ctrl2X, ctrl2Y) { switch (command) { case "L": segmentCallback(startX, startY, endX, endY); break; case "Q": { var prevCurveX = startX; var prevCurveY = startY; for (var i4 = 1; i4 < curvePoints; i4++) { pointOnQuadraticBezier( startX, startY, ctrl1X, ctrl1Y, endX, endY, i4 / (curvePoints - 1), tempPoint ); segmentCallback(prevCurveX, prevCurveY, tempPoint.x, tempPoint.y); prevCurveX = tempPoint.x; prevCurveY = tempPoint.y; } break; } case "C": { var prevCurveX$1 = startX; var prevCurveY$1 = startY; for (var i$1 = 1; i$1 < curvePoints; i$1++) { pointOnCubicBezier( startX, startY, ctrl1X, ctrl1Y, ctrl2X, ctrl2Y, endX, endY, i$1 / (curvePoints - 1), tempPoint ); segmentCallback(prevCurveX$1, prevCurveY$1, tempPoint.x, tempPoint.y); prevCurveX$1 = tempPoint.x; prevCurveY$1 = tempPoint.y; } break; } } }); } var viewportQuadVertex = "precision highp float;attribute vec2 aUV;varying vec2 vUV;void main(){vUV=aUV;gl_Position=vec4(mix(vec2(-1.0),vec2(1.0),aUV),0.0,1.0);}"; var copyTexFragment = "precision highp float;uniform sampler2D tex;varying vec2 vUV;void main(){gl_FragColor=texture2D(tex,vUV);}"; var cache = /* @__PURE__ */ new WeakMap(); var glContextParams = { premultipliedAlpha: false, preserveDrawingBuffer: true, antialias: false, depth: false }; function withWebGLContext(glOrCanvas, callback) { var gl = glOrCanvas.getContext ? glOrCanvas.getContext("webgl", glContextParams) : glOrCanvas; var wrapper = cache.get(gl); if (!wrapper) { let getExtension2 = function(name) { var ext = extensions2[name]; if (!ext) { ext = extensions2[name] = gl.getExtension(name); if (!ext) { throw new Error(name + " not supported"); } } return ext; }, compileShader = function(src, type) { var shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); return shader; }, withProgram = function(name, vert, frag, func) { if (!programs[name]) { var attributes = {}; var uniforms = {}; var program = gl.createProgram(); gl.attachShader(program, compileShader(vert, gl.VERTEX_SHADER)); gl.attachShader(program, compileShader(frag, gl.FRAGMENT_SHADER)); gl.linkProgram(program); programs[name] = { program, transaction: function transaction(func2) { gl.useProgram(program); func2({ setUniform: function setUniform(type, name2) { var values = [], len = arguments.length - 2; while (len-- > 0) values[len] = arguments[len + 2]; var uniformLoc = uniforms[name2] || (uniforms[name2] = gl.getUniformLocation(program, name2)); gl["uniform" + type].apply(gl, [uniformLoc].concat(values)); }, setAttribute: function setAttribute(name2, size2, usage, instancingDivisor, data) { var attr = attributes[name2]; if (!attr) { attr = attributes[name2] = { buf: gl.createBuffer(), // TODO should we destroy our buffers? loc: gl.getAttribLocation(program, name2), data: null }; } gl.bindBuffer(gl.ARRAY_BUFFER, attr.buf); gl.vertexAttribPointer(attr.loc, size2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(attr.loc); if (isWebGL2) { gl.vertexAttribDivisor(attr.loc, instancingDivisor); } else { getExtension2("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(attr.loc, instancingDivisor); } if (data !== attr.data) { gl.bufferData(gl.ARRAY_BUFFER, data, usage); attr.data = data; } } }); } }; } programs[name].transaction(func); }, withTexture = function(name, func) { textureUnit++; try { gl.activeTexture(gl.TEXTURE0 + textureUnit); var texture = textures[name]; if (!texture) { texture = textures[name] = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); } gl.bindTexture(gl.TEXTURE_2D, texture); func(texture, textureUnit); } finally { textureUnit--; } }, withTextureFramebuffer = function(texture, textureUnit2, func) { var framebuffer = gl.createFramebuffer(); framebufferStack.push(framebuffer); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); gl.activeTexture(gl.TEXTURE0 + textureUnit2); gl.bindTexture(gl.TEXTURE_2D, texture); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); try { func(framebuffer); } finally { gl.deleteFramebuffer(framebuffer); gl.bindFramebuffer(gl.FRAMEBUFFER, framebufferStack[--framebufferStack.length - 1] || null); } }, handleContextLoss = function() { extensions2 = {}; programs = {}; textures = {}; textureUnit = -1; framebufferStack.length = 0; }; var isWebGL2 = typeof WebGL2RenderingContext !== "undefined" && gl instanceof WebGL2RenderingContext; var extensions2 = {}; var programs = {}; var textures = {}; var textureUnit = -1; var framebufferStack = []; gl.canvas.addEventListener("webglcontextlost", function(e2) { handleContextLoss(); e2.preventDefault(); }, false); cache.set(gl, wrapper = { gl, isWebGL2, getExtension: getExtension2, withProgram, withTexture, withTextureFramebuffer, handleContextLoss }); } callback(wrapper); } function renderImageData(glOrCanvas, imageData, x, y, width, height, channels, framebuffer) { if (channels === void 0) channels = 15; if (framebuffer === void 0) framebuffer = null; withWebGLContext(glOrCanvas, function(ref) { var gl = ref.gl; var withProgram = ref.withProgram; var withTexture = ref.withTexture; withTexture("copy", function(tex, texUnit) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData); withProgram("copy", viewportQuadVertex, copyTexFragment, function(ref2) { var setUniform = ref2.setUniform; var setAttribute = ref2.setAttribute; setAttribute("aUV", 2, gl.STATIC_DRAW, 0, new Float32Array([0, 0, 2, 0, 0, 2])); setUniform("1i", "image", texUnit); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer || null); gl.disable(gl.BLEND); gl.colorMask(channels & 8, channels & 4, channels & 2, channels & 1); gl.viewport(x, y, width, height); gl.scissor(x, y, width, height); gl.drawArrays(gl.TRIANGLES, 0, 3); }); }); }); } function resizeWebGLCanvasWithoutClearing2(canvas, newWidth, newHeight) { var width = canvas.width; var height = canvas.height; withWebGLContext(canvas, function(ref) { var gl = ref.gl; var data = new Uint8Array(width * height * 4); gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data); canvas.width = newWidth; canvas.height = newHeight; renderImageData(gl, data, 0, 0, width, height); }); } var webglUtils = Object.freeze({ __proto__: null, withWebGLContext, renderImageData, resizeWebGLCanvasWithoutClearing: resizeWebGLCanvasWithoutClearing2 }); function generate$2(sdfWidth, sdfHeight, path, viewBox, maxDistance, sdfExponent) { if (sdfExponent === void 0) sdfExponent = 1; var textureData = new Uint8Array(sdfWidth * sdfHeight); var viewBoxWidth = viewBox[2] - viewBox[0]; var viewBoxHeight = viewBox[3] - viewBox[1]; var segments = []; pathToLineSegments(path, function(x1, y1, x2, y2) { segments.push({ x1, y1, x2, y2, minX: Math.min(x1, x2), minY: Math.min(y1, y2), maxX: Math.max(x1, x2), maxY: Math.max(y1, y2) }); }); segments.sort(function(a6, b5) { return a6.maxX - b5.maxX; }); for (var sdfX = 0; sdfX < sdfWidth; sdfX++) { for (var sdfY = 0; sdfY < sdfHeight; sdfY++) { var signedDist = findNearestSignedDistance( viewBox[0] + viewBoxWidth * (sdfX + 0.5) / sdfWidth, viewBox[1] + viewBoxHeight * (sdfY + 0.5) / sdfHeight ); var alpha = Math.pow(1 - Math.abs(signedDist) / maxDistance, sdfExponent) / 2; if (signedDist < 0) { alpha = 1 - alpha; } alpha = Math.max(0, Math.min(255, Math.round(alpha * 255))); textureData[sdfY * sdfWidth + sdfX] = alpha; } } return textureData; function findNearestSignedDistance(x, y) { var closestDistSq = Infinity; var closestDist = Infinity; for (var i4 = segments.length; i4--; ) { var seg = segments[i4]; if (seg.maxX + closestDist <= x) { break; } if (x + closestDist > seg.minX && y - closestDist < seg.maxY && y + closestDist > seg.minY) { var distSq = absSquareDistanceToLineSegment(x, y, seg.x1, seg.y1, seg.x2, seg.y2); if (distSq < closestDistSq) { closestDistSq = distSq; closestDist = Math.sqrt(closestDistSq); } } } if (isPointInPoly(x, y)) { closestDist = -closestDist; } return closestDist; } function isPointInPoly(x, y) { var winding = 0; for (var i4 = segments.length; i4--; ) { var seg = segments[i4]; if (seg.maxX <= x) { break; } var intersects = seg.y1 > y !== seg.y2 > y && x < (seg.x2 - seg.x1) * (y - seg.y1) / (seg.y2 - seg.y1) + seg.x1; if (intersects) { winding += seg.y1 < seg.y2 ? 1 : -1; } } return winding !== 0; } } function generateIntoCanvas$2(sdfWidth, sdfHeight, path, viewBox, maxDistance, sdfExponent, canvas, x, y, channel) { if (sdfExponent === void 0) sdfExponent = 1; if (x === void 0) x = 0; if (y === void 0) y = 0; if (channel === void 0) channel = 0; generateIntoFramebuffer$1(sdfWidth, sdfHeight, path, viewBox, maxDistance, sdfExponent, canvas, null, x, y, channel); } function generateIntoFramebuffer$1(sdfWidth, sdfHeight, path, viewBox, maxDistance, sdfExponent, glOrCanvas, framebuffer, x, y, channel) { if (sdfExponent === void 0) sdfExponent = 1; if (x === void 0) x = 0; if (y === void 0) y = 0; if (channel === void 0) channel = 0; var data = generate$2(sdfWidth, sdfHeight, path, viewBox, maxDistance, sdfExponent); var rgbaData = new Uint8Array(data.length * 4); for (var i4 = 0; i4 < data.length; i4++) { rgbaData[i4 * 4 + channel] = data[i4]; } renderImageData(glOrCanvas, rgbaData, x, y, sdfWidth, sdfHeight, 1 << 3 - channel, framebuffer); } function absSquareDistanceToLineSegment(x, y, lineX0, lineY0, lineX1, lineY1) { var ldx = lineX1 - lineX0; var ldy = lineY1 - lineY0; var lengthSq = ldx * ldx + ldy * ldy; var t3 = lengthSq ? Math.max(0, Math.min(1, ((x - lineX0) * ldx + (y - lineY0) * ldy) / lengthSq)) : 0; var dx = x - (lineX0 + t3 * ldx); var dy = y - (lineY0 + t3 * ldy); return dx * dx + dy * dy; } var javascript = Object.freeze({ __proto__: null, generate: generate$2, generateIntoCanvas: generateIntoCanvas$2, generateIntoFramebuffer: generateIntoFramebuffer$1 }); var mainVertex = "precision highp float;uniform vec4 uGlyphBounds;attribute vec2 aUV;attribute vec4 aLineSegment;varying vec4 vLineSegment;varying vec2 vGlyphXY;void main(){vLineSegment=aLineSegment;vGlyphXY=mix(uGlyphBounds.xy,uGlyphBounds.zw,aUV);gl_Position=vec4(mix(vec2(-1.0),vec2(1.0),aUV),0.0,1.0);}"; var mainFragment = "precision highp float;uniform vec4 uGlyphBounds;uniform float uMaxDistance;uniform float uExponent;varying vec4 vLineSegment;varying vec2 vGlyphXY;float absDistToSegment(vec2 point,vec2 lineA,vec2 lineB){vec2 lineDir=lineB-lineA;float lenSq=dot(lineDir,lineDir);float t=lenSq==0.0 ? 0.0 : clamp(dot(point-lineA,lineDir)/lenSq,0.0,1.0);vec2 linePt=lineA+t*lineDir;return distance(point,linePt);}void main(){vec4 seg=vLineSegment;vec2 p=vGlyphXY;float dist=absDistToSegment(p,seg.xy,seg.zw);float val=pow(1.0-clamp(dist/uMaxDistance,0.0,1.0),uExponent)*0.5;bool crossing=(seg.y>p.y!=seg.w>p.y)&&(p.x<(seg.z-seg.x)*(p.y-seg.y)/(seg.w-seg.y)+seg.x);bool crossingUp=crossing&&vLineSegment.y1,1e>2,u>2,2wt>1,1>1,1ge>1,1wp>1,1j>1,f>1,hm>1,1>1,u>1,u6>1,1>1,+5,28>1,w>1,1>1,+3,b8>1,1>1,+3,1>3,-1>-1,3>1,1>1,+2,1s>1,1>1,x>1,th>1,1>1,+2,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,4q>1,1e>2,u>2,2>1,+1", "canonical": "6f1>-6dx,6dy>-6dx,6ec>-6ed,6ee>-6ed,6ww>2jj,-2ji>2jj,14r4>-1e7l,1e7m>-1e7l,1e7m>-1e5c,1e5d>-1e5b,1e5c>-14qx,14qy>-14qx,14vn>-1ecg,1ech>-1ecg,1edu>-1ecg,1eci>-1ecg,1eda>-1ecg,1eci>-1ecg,1eci>-168q,168r>-168q,168s>-14ye,14yf>-14ye" }; function parseCharacterMap(encodedString, includeReverse) { var radix = 36; var lastCode = 0; var map3 = /* @__PURE__ */ new Map(); var reverseMap = includeReverse && /* @__PURE__ */ new Map(); var prevPair; encodedString.split(",").forEach(function visit(entry) { if (entry.indexOf("+") !== -1) { for (var i4 = +entry; i4--; ) { visit(prevPair); } } else { prevPair = entry; var ref = entry.split(">"); var a6 = ref[0]; var b5 = ref[1]; a6 = String.fromCodePoint(lastCode += parseInt(a6, radix)); b5 = String.fromCodePoint(lastCode += parseInt(b5, radix)); map3.set(a6, b5); includeReverse && reverseMap.set(b5, a6); } }); return { map: map3, reverseMap }; } var openToClose, closeToOpen, canonical; function parse$1() { if (!openToClose) { var ref = parseCharacterMap(data$1.pairs, true); var map3 = ref.map; var reverseMap = ref.reverseMap; openToClose = map3; closeToOpen = reverseMap; canonical = parseCharacterMap(data$1.canonical, false).map; } } function openingToClosingBracket(char) { parse$1(); return openToClose.get(char) || null; } function closingToOpeningBracket(char) { parse$1(); return closeToOpen.get(char) || null; } function getCanonicalBracket(char) { parse$1(); return canonical.get(char) || null; } var TYPE_L = TYPES.L; var TYPE_R = TYPES.R; var TYPE_EN = TYPES.EN; var TYPE_ES = TYPES.ES; var TYPE_ET = TYPES.ET; var TYPE_AN = TYPES.AN; var TYPE_CS = TYPES.CS; var TYPE_B = TYPES.B; var TYPE_S = TYPES.S; var TYPE_ON = TYPES.ON; var TYPE_BN = TYPES.BN; var TYPE_NSM = TYPES.NSM; var TYPE_AL = TYPES.AL; var TYPE_LRO = TYPES.LRO; var TYPE_RLO = TYPES.RLO; var TYPE_LRE = TYPES.LRE; var TYPE_RLE = TYPES.RLE; var TYPE_PDF = TYPES.PDF; var TYPE_LRI = TYPES.LRI; var TYPE_RLI = TYPES.RLI; var TYPE_FSI = TYPES.FSI; var TYPE_PDI = TYPES.PDI; function getEmbeddingLevels(string, baseDirection) { var MAX_DEPTH = 125; var charTypes = new Uint32Array(string.length); for (var i4 = 0; i4 < string.length; i4++) { charTypes[i4] = getBidiCharType(string[i4]); } var charTypeCounts = /* @__PURE__ */ new Map(); function changeCharType(i5, type2) { var oldType = charTypes[i5]; charTypes[i5] = type2; charTypeCounts.set(oldType, charTypeCounts.get(oldType) - 1); if (oldType & NEUTRAL_ISOLATE_TYPES) { charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) - 1); } charTypeCounts.set(type2, (charTypeCounts.get(type2) || 0) + 1); if (type2 & NEUTRAL_ISOLATE_TYPES) { charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1); } } var embedLevels = new Uint8Array(string.length); var isolationPairs = /* @__PURE__ */ new Map(); var paragraphs = []; var paragraph = null; for (var i$1 = 0; i$1 < string.length; i$1++) { if (!paragraph) { paragraphs.push(paragraph = { start: i$1, end: string.length - 1, // 3.3.1 P2-P3: Determine the paragraph level level: baseDirection === "rtl" ? 1 : baseDirection === "ltr" ? 0 : determineAutoEmbedLevel(i$1, false) }); } if (charTypes[i$1] & TYPE_B) { paragraph.end = i$1; paragraph = null; } } var FORMATTING_TYPES = TYPE_RLE | TYPE_LRE | TYPE_RLO | TYPE_LRO | ISOLATE_INIT_TYPES | TYPE_PDI | TYPE_PDF | TYPE_B; var nextEven = function(n2) { return n2 + (n2 & 1 ? 1 : 2); }; var nextOdd = function(n2) { return n2 + (n2 & 1 ? 2 : 1); }; for (var paraIdx = 0; paraIdx < paragraphs.length; paraIdx++) { paragraph = paragraphs[paraIdx]; var statusStack = [{ _level: paragraph.level, _override: 0, //0=neutral, 1=L, 2=R _isolate: 0 //bool }]; var stackTop = void 0; var overflowIsolateCount = 0; var overflowEmbeddingCount = 0; var validIsolateCount = 0; charTypeCounts.clear(); for (var i$2 = paragraph.start; i$2 <= paragraph.end; i$2++) { var charType = charTypes[i$2]; stackTop = statusStack[statusStack.length - 1]; charTypeCounts.set(charType, (charTypeCounts.get(charType) || 0) + 1); if (charType & NEUTRAL_ISOLATE_TYPES) { charTypeCounts.set(NEUTRAL_ISOLATE_TYPES, (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES) || 0) + 1); } if (charType & FORMATTING_TYPES) { if (charType & (TYPE_RLE | TYPE_LRE)) { embedLevels[i$2] = stackTop._level; var level = (charType === TYPE_RLE ? nextOdd : nextEven)(stackTop._level); if (level <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) { statusStack.push({ _level: level, _override: 0, _isolate: 0 }); } else if (!overflowIsolateCount) { overflowEmbeddingCount++; } } else if (charType & (TYPE_RLO | TYPE_LRO)) { embedLevels[i$2] = stackTop._level; var level$1 = (charType === TYPE_RLO ? nextOdd : nextEven)(stackTop._level); if (level$1 <= MAX_DEPTH && !overflowIsolateCount && !overflowEmbeddingCount) { statusStack.push({ _level: level$1, _override: charType & TYPE_RLO ? TYPE_R : TYPE_L, _isolate: 0 }); } else if (!overflowIsolateCount) { overflowEmbeddingCount++; } } else if (charType & ISOLATE_INIT_TYPES) { if (charType & TYPE_FSI) { charType = determineAutoEmbedLevel(i$2 + 1, true) === 1 ? TYPE_RLI : TYPE_LRI; } embedLevels[i$2] = stackTop._level; if (stackTop._override) { changeCharType(i$2, stackTop._override); } var level$2 = (charType === TYPE_RLI ? nextOdd : nextEven)(stackTop._level); if (level$2 <= MAX_DEPTH && overflowIsolateCount === 0 && overflowEmbeddingCount === 0) { validIsolateCount++; statusStack.push({ _level: level$2, _override: 0, _isolate: 1, _isolInitIndex: i$2 }); } else { overflowIsolateCount++; } } else if (charType & TYPE_PDI) { if (overflowIsolateCount > 0) { overflowIsolateCount--; } else if (validIsolateCount > 0) { overflowEmbeddingCount = 0; while (!statusStack[statusStack.length - 1]._isolate) { statusStack.pop(); } var isolInitIndex = statusStack[statusStack.length - 1]._isolInitIndex; if (isolInitIndex != null) { isolationPairs.set(isolInitIndex, i$2); isolationPairs.set(i$2, isolInitIndex); } statusStack.pop(); validIsolateCount--; } stackTop = statusStack[statusStack.length - 1]; embedLevels[i$2] = stackTop._level; if (stackTop._override) { changeCharType(i$2, stackTop._override); } } else if (charType & TYPE_PDF) { if (overflowIsolateCount === 0) { if (overflowEmbeddingCount > 0) { overflowEmbeddingCount--; } else if (!stackTop._isolate && statusStack.length > 1) { statusStack.pop(); stackTop = statusStack[statusStack.length - 1]; } } embedLevels[i$2] = stackTop._level; } else if (charType & TYPE_B) { embedLevels[i$2] = paragraph.level; } } else { embedLevels[i$2] = stackTop._level; if (stackTop._override && charType !== TYPE_BN) { changeCharType(i$2, stackTop._override); } } } var levelRuns = []; var currentRun = null; for (var i$3 = paragraph.start; i$3 <= paragraph.end; i$3++) { var charType$1 = charTypes[i$3]; if (!(charType$1 & BN_LIKE_TYPES)) { var lvl = embedLevels[i$3]; var isIsolInit = charType$1 & ISOLATE_INIT_TYPES; var isPDI = charType$1 === TYPE_PDI; if (currentRun && lvl === currentRun._level) { currentRun._end = i$3; currentRun._endsWithIsolInit = isIsolInit; } else { levelRuns.push(currentRun = { _start: i$3, _end: i$3, _level: lvl, _startsWithPDI: isPDI, _endsWithIsolInit: isIsolInit }); } } } var isolatingRunSeqs = []; for (var runIdx = 0; runIdx < levelRuns.length; runIdx++) { var run = levelRuns[runIdx]; if (!run._startsWithPDI || run._startsWithPDI && !isolationPairs.has(run._start)) { var seqRuns = [currentRun = run]; for (var pdiIndex = void 0; currentRun && currentRun._endsWithIsolInit && (pdiIndex = isolationPairs.get(currentRun._end)) != null; ) { for (var i$4 = runIdx + 1; i$4 < levelRuns.length; i$4++) { if (levelRuns[i$4]._start === pdiIndex) { seqRuns.push(currentRun = levelRuns[i$4]); break; } } } var seqIndices = []; for (var i$5 = 0; i$5 < seqRuns.length; i$5++) { var run$1 = seqRuns[i$5]; for (var j = run$1._start; j <= run$1._end; j++) { seqIndices.push(j); } } var firstLevel = embedLevels[seqIndices[0]]; var prevLevel = paragraph.level; for (var i$6 = seqIndices[0] - 1; i$6 >= 0; i$6--) { if (!(charTypes[i$6] & BN_LIKE_TYPES)) { prevLevel = embedLevels[i$6]; break; } } var lastIndex = seqIndices[seqIndices.length - 1]; var lastLevel = embedLevels[lastIndex]; var nextLevel = paragraph.level; if (!(charTypes[lastIndex] & ISOLATE_INIT_TYPES)) { for (var i$7 = lastIndex + 1; i$7 <= paragraph.end; i$7++) { if (!(charTypes[i$7] & BN_LIKE_TYPES)) { nextLevel = embedLevels[i$7]; break; } } } isolatingRunSeqs.push({ _seqIndices: seqIndices, _sosType: Math.max(prevLevel, firstLevel) % 2 ? TYPE_R : TYPE_L, _eosType: Math.max(nextLevel, lastLevel) % 2 ? TYPE_R : TYPE_L }); } } for (var seqIdx = 0; seqIdx < isolatingRunSeqs.length; seqIdx++) { var ref = isolatingRunSeqs[seqIdx]; var seqIndices$1 = ref._seqIndices; var sosType = ref._sosType; var eosType = ref._eosType; var embedDirection = embedLevels[seqIndices$1[0]] & 1 ? TYPE_R : TYPE_L; if (charTypeCounts.get(TYPE_NSM)) { for (var si = 0; si < seqIndices$1.length; si++) { var i$8 = seqIndices$1[si]; if (charTypes[i$8] & TYPE_NSM) { var prevType = sosType; for (var sj = si - 1; sj >= 0; sj--) { if (!(charTypes[seqIndices$1[sj]] & BN_LIKE_TYPES)) { prevType = charTypes[seqIndices$1[sj]]; break; } } changeCharType(i$8, prevType & (ISOLATE_INIT_TYPES | TYPE_PDI) ? TYPE_ON : prevType); } } } if (charTypeCounts.get(TYPE_EN)) { for (var si$1 = 0; si$1 < seqIndices$1.length; si$1++) { var i$9 = seqIndices$1[si$1]; if (charTypes[i$9] & TYPE_EN) { for (var sj$1 = si$1 - 1; sj$1 >= -1; sj$1--) { var prevCharType = sj$1 === -1 ? sosType : charTypes[seqIndices$1[sj$1]]; if (prevCharType & STRONG_TYPES) { if (prevCharType === TYPE_AL) { changeCharType(i$9, TYPE_AN); } break; } } } } } if (charTypeCounts.get(TYPE_AL)) { for (var si$2 = 0; si$2 < seqIndices$1.length; si$2++) { var i$10 = seqIndices$1[si$2]; if (charTypes[i$10] & TYPE_AL) { changeCharType(i$10, TYPE_R); } } } if (charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) { for (var si$3 = 1; si$3 < seqIndices$1.length - 1; si$3++) { var i$11 = seqIndices$1[si$3]; if (charTypes[i$11] & (TYPE_ES | TYPE_CS)) { var prevType$1 = 0, nextType = 0; for (var sj$2 = si$3 - 1; sj$2 >= 0; sj$2--) { prevType$1 = charTypes[seqIndices$1[sj$2]]; if (!(prevType$1 & BN_LIKE_TYPES)) { break; } } for (var sj$3 = si$3 + 1; sj$3 < seqIndices$1.length; sj$3++) { nextType = charTypes[seqIndices$1[sj$3]]; if (!(nextType & BN_LIKE_TYPES)) { break; } } if (prevType$1 === nextType && (charTypes[i$11] === TYPE_ES ? prevType$1 === TYPE_EN : prevType$1 & (TYPE_EN | TYPE_AN))) { changeCharType(i$11, prevType$1); } } } } if (charTypeCounts.get(TYPE_EN)) { for (var si$4 = 0; si$4 < seqIndices$1.length; si$4++) { var i$12 = seqIndices$1[si$4]; if (charTypes[i$12] & TYPE_EN) { for (var sj$4 = si$4 - 1; sj$4 >= 0 && charTypes[seqIndices$1[sj$4]] & (TYPE_ET | BN_LIKE_TYPES); sj$4--) { changeCharType(seqIndices$1[sj$4], TYPE_EN); } for (si$4++; si$4 < seqIndices$1.length && charTypes[seqIndices$1[si$4]] & (TYPE_ET | BN_LIKE_TYPES | TYPE_EN); si$4++) { if (charTypes[seqIndices$1[si$4]] !== TYPE_EN) { changeCharType(seqIndices$1[si$4], TYPE_EN); } } } } } if (charTypeCounts.get(TYPE_ET) || charTypeCounts.get(TYPE_ES) || charTypeCounts.get(TYPE_CS)) { for (var si$5 = 0; si$5 < seqIndices$1.length; si$5++) { var i$13 = seqIndices$1[si$5]; if (charTypes[i$13] & (TYPE_ET | TYPE_ES | TYPE_CS)) { changeCharType(i$13, TYPE_ON); for (var sj$5 = si$5 - 1; sj$5 >= 0 && charTypes[seqIndices$1[sj$5]] & BN_LIKE_TYPES; sj$5--) { changeCharType(seqIndices$1[sj$5], TYPE_ON); } for (var sj$6 = si$5 + 1; sj$6 < seqIndices$1.length && charTypes[seqIndices$1[sj$6]] & BN_LIKE_TYPES; sj$6++) { changeCharType(seqIndices$1[sj$6], TYPE_ON); } } } } if (charTypeCounts.get(TYPE_EN)) { for (var si$6 = 0, prevStrongType = sosType; si$6 < seqIndices$1.length; si$6++) { var i$14 = seqIndices$1[si$6]; var type = charTypes[i$14]; if (type & TYPE_EN) { if (prevStrongType === TYPE_L) { changeCharType(i$14, TYPE_L); } } else if (type & STRONG_TYPES) { prevStrongType = type; } } } if (charTypeCounts.get(NEUTRAL_ISOLATE_TYPES)) { var R_TYPES_FOR_N_STEPS = TYPE_R | TYPE_EN | TYPE_AN; var STRONG_TYPES_FOR_N_STEPS = R_TYPES_FOR_N_STEPS | TYPE_L; var bracketPairs = []; { var openerStack = []; for (var si$7 = 0; si$7 < seqIndices$1.length; si$7++) { if (charTypes[seqIndices$1[si$7]] & NEUTRAL_ISOLATE_TYPES) { var char = string[seqIndices$1[si$7]]; var oppositeBracket = void 0; if (openingToClosingBracket(char) !== null) { if (openerStack.length < 63) { openerStack.push({ char, seqIndex: si$7 }); } else { break; } } else if ((oppositeBracket = closingToOpeningBracket(char)) !== null) { for (var stackIdx = openerStack.length - 1; stackIdx >= 0; stackIdx--) { var stackChar = openerStack[stackIdx].char; if (stackChar === oppositeBracket || stackChar === closingToOpeningBracket(getCanonicalBracket(char)) || openingToClosingBracket(getCanonicalBracket(stackChar)) === char) { bracketPairs.push([openerStack[stackIdx].seqIndex, si$7]); openerStack.length = stackIdx; break; } } } } } bracketPairs.sort(function(a6, b5) { return a6[0] - b5[0]; }); } for (var pairIdx = 0; pairIdx < bracketPairs.length; pairIdx++) { var ref$1 = bracketPairs[pairIdx]; var openSeqIdx = ref$1[0]; var closeSeqIdx = ref$1[1]; var foundStrongType = false; var useStrongType = 0; for (var si$8 = openSeqIdx + 1; si$8 < closeSeqIdx; si$8++) { var i$15 = seqIndices$1[si$8]; if (charTypes[i$15] & STRONG_TYPES_FOR_N_STEPS) { foundStrongType = true; var lr = charTypes[i$15] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L; if (lr === embedDirection) { useStrongType = lr; break; } } } if (foundStrongType && !useStrongType) { useStrongType = sosType; for (var si$9 = openSeqIdx - 1; si$9 >= 0; si$9--) { var i$16 = seqIndices$1[si$9]; if (charTypes[i$16] & STRONG_TYPES_FOR_N_STEPS) { var lr$1 = charTypes[i$16] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L; if (lr$1 !== embedDirection) { useStrongType = lr$1; } else { useStrongType = embedDirection; } break; } } } if (useStrongType) { charTypes[seqIndices$1[openSeqIdx]] = charTypes[seqIndices$1[closeSeqIdx]] = useStrongType; if (useStrongType !== embedDirection) { for (var si$10 = openSeqIdx + 1; si$10 < seqIndices$1.length; si$10++) { if (!(charTypes[seqIndices$1[si$10]] & BN_LIKE_TYPES)) { if (getBidiCharType(string[seqIndices$1[si$10]]) & TYPE_NSM) { charTypes[seqIndices$1[si$10]] = useStrongType; } break; } } } if (useStrongType !== embedDirection) { for (var si$11 = closeSeqIdx + 1; si$11 < seqIndices$1.length; si$11++) { if (!(charTypes[seqIndices$1[si$11]] & BN_LIKE_TYPES)) { if (getBidiCharType(string[seqIndices$1[si$11]]) & TYPE_NSM) { charTypes[seqIndices$1[si$11]] = useStrongType; } break; } } } } } for (var si$12 = 0; si$12 < seqIndices$1.length; si$12++) { if (charTypes[seqIndices$1[si$12]] & NEUTRAL_ISOLATE_TYPES) { var niRunStart = si$12, niRunEnd = si$12; var prevType$2 = sosType; for (var si2 = si$12 - 1; si2 >= 0; si2--) { if (charTypes[seqIndices$1[si2]] & BN_LIKE_TYPES) { niRunStart = si2; } else { prevType$2 = charTypes[seqIndices$1[si2]] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L; break; } } var nextType$1 = eosType; for (var si2$1 = si$12 + 1; si2$1 < seqIndices$1.length; si2$1++) { if (charTypes[seqIndices$1[si2$1]] & (NEUTRAL_ISOLATE_TYPES | BN_LIKE_TYPES)) { niRunEnd = si2$1; } else { nextType$1 = charTypes[seqIndices$1[si2$1]] & R_TYPES_FOR_N_STEPS ? TYPE_R : TYPE_L; break; } } for (var sj$7 = niRunStart; sj$7 <= niRunEnd; sj$7++) { charTypes[seqIndices$1[sj$7]] = prevType$2 === nextType$1 ? prevType$2 : embedDirection; } si$12 = niRunEnd; } } } } for (var i$17 = paragraph.start; i$17 <= paragraph.end; i$17++) { var level$3 = embedLevels[i$17]; var type$1 = charTypes[i$17]; if (level$3 & 1) { if (type$1 & (TYPE_L | TYPE_EN | TYPE_AN)) { embedLevels[i$17]++; } } else { if (type$1 & TYPE_R) { embedLevels[i$17]++; } else if (type$1 & (TYPE_AN | TYPE_EN)) { embedLevels[i$17] += 2; } } if (type$1 & BN_LIKE_TYPES) { embedLevels[i$17] = i$17 === 0 ? paragraph.level : embedLevels[i$17 - 1]; } if (i$17 === paragraph.end || getBidiCharType(string[i$17]) & (TYPE_S | TYPE_B)) { for (var j$1 = i$17; j$1 >= 0 && getBidiCharType(string[j$1]) & TRAILING_TYPES; j$1--) { embedLevels[j$1] = paragraph.level; } } } } return { levels: embedLevels, paragraphs }; function determineAutoEmbedLevel(start, isFSI) { for (var i5 = start; i5 < string.length; i5++) { var charType2 = charTypes[i5]; if (charType2 & (TYPE_R | TYPE_AL)) { return 1; } if (charType2 & (TYPE_B | TYPE_L) || isFSI && charType2 === TYPE_PDI) { return 0; } if (charType2 & ISOLATE_INIT_TYPES) { var pdi = indexOfMatchingPDI(i5); i5 = pdi === -1 ? string.length : pdi; } } return 0; } function indexOfMatchingPDI(isolateStart) { var isolationLevel = 1; for (var i5 = isolateStart + 1; i5 < string.length; i5++) { var charType2 = charTypes[i5]; if (charType2 & TYPE_B) { break; } if (charType2 & TYPE_PDI) { if (--isolationLevel === 0) { return i5; } } else if (charType2 & ISOLATE_INIT_TYPES) { isolationLevel++; } } return -1; } } var data = "14>1,j>2,t>2,u>2,1a>g,2v3>1,1>1,1ge>1,1wd>1,b>1,1j>1,f>1,ai>3,-2>3,+1,8>1k0,-1jq>1y7,-1y6>1hf,-1he>1h6,-1h5>1ha,-1h8>1qi,-1pu>1,6>3u,-3s>7,6>1,1>1,f>1,1>1,+2,3>1,1>1,+13,4>1,1>1,6>1eo,-1ee>1,3>1mg,-1me>1mk,-1mj>1mi,-1mg>1mi,-1md>1,1>1,+2,1>10k,-103>1,1>1,4>1,5>1,1>1,+10,3>1,1>8,-7>8,+1,-6>7,+1,a>1,1>1,u>1,u6>1,1>1,+5,26>1,1>1,2>1,2>2,8>1,7>1,4>1,1>1,+5,b8>1,1>1,+3,1>3,-2>1,2>1,1>1,+2,c>1,3>1,1>1,+2,h>1,3>1,a>1,1>1,2>1,3>1,1>1,d>1,f>1,3>1,1a>1,1>1,6>1,7>1,13>1,k>1,1>1,+19,4>1,1>1,+2,2>1,1>1,+18,m>1,a>1,1>1,lk>1,1>1,4>1,2>1,f>1,3>1,1>1,+3,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,6>1,4j>1,j>2,t>2,u>2,2>1,+1"; var mirrorMap; function parse2() { if (!mirrorMap) { var ref = parseCharacterMap(data, true); var map3 = ref.map; var reverseMap = ref.reverseMap; reverseMap.forEach(function(value, key) { map3.set(key, value); }); mirrorMap = map3; } } function getMirroredCharacter(char) { parse2(); return mirrorMap.get(char) || null; } function getMirroredCharactersMap(string, embeddingLevels, start, end) { var strLen = string.length; start = Math.max(0, start == null ? 0 : +start); end = Math.min(strLen - 1, end == null ? strLen - 1 : +end); var map3 = /* @__PURE__ */ new Map(); for (var i4 = start; i4 <= end; i4++) { if (embeddingLevels[i4] & 1) { var mirror = getMirroredCharacter(string[i4]); if (mirror !== null) { map3.set(i4, mirror); } } } return map3; } function getReorderSegments(string, embeddingLevelsResult, start, end) { var strLen = string.length; start = Math.max(0, start == null ? 0 : +start); end = Math.min(strLen - 1, end == null ? strLen - 1 : +end); var segments = []; embeddingLevelsResult.paragraphs.forEach(function(paragraph) { var lineStart = Math.max(start, paragraph.start); var lineEnd = Math.min(end, paragraph.end); if (lineStart < lineEnd) { var lineLevels = embeddingLevelsResult.levels.slice(lineStart, lineEnd + 1); for (var i4 = lineEnd; i4 >= lineStart && getBidiCharType(string[i4]) & TRAILING_TYPES; i4--) { lineLevels[i4] = paragraph.level; } var maxLevel = paragraph.level; var minOddLevel = Infinity; for (var i$1 = 0; i$1 < lineLevels.length; i$1++) { var level = lineLevels[i$1]; if (level > maxLevel) { maxLevel = level; } if (level < minOddLevel) { minOddLevel = level | 1; } } for (var lvl = maxLevel; lvl >= minOddLevel; lvl--) { for (var i$2 = 0; i$2 < lineLevels.length; i$2++) { if (lineLevels[i$2] >= lvl) { var segStart = i$2; while (i$2 + 1 < lineLevels.length && lineLevels[i$2 + 1] >= lvl) { i$2++; } if (i$2 > segStart) { segments.push([segStart + lineStart, i$2 + lineStart]); } } } } } }); return segments; } function getReorderedString(string, embedLevelsResult, start, end) { var indices = getReorderedIndices(string, embedLevelsResult, start, end); var chars = [].concat(string); indices.forEach(function(charIndex, i4) { chars[i4] = (embedLevelsResult.levels[charIndex] & 1 ? getMirroredCharacter(string[charIndex]) : null) || string[charIndex]; }); return chars.join(""); } function getReorderedIndices(string, embedLevelsResult, start, end) { var segments = getReorderSegments(string, embedLevelsResult, start, end); var indices = []; for (var i4 = 0; i4 < string.length; i4++) { indices[i4] = i4; } segments.forEach(function(ref) { var start2 = ref[0]; var end2 = ref[1]; var slice2 = indices.slice(start2, end2 + 1); for (var i5 = slice2.length; i5--; ) { indices[end2 - i5] = slice2[i5]; } }); return indices; } exports2.closingToOpeningBracket = closingToOpeningBracket; exports2.getBidiCharType = getBidiCharType; exports2.getBidiCharTypeName = getBidiCharTypeName; exports2.getCanonicalBracket = getCanonicalBracket; exports2.getEmbeddingLevels = getEmbeddingLevels; exports2.getMirroredCharacter = getMirroredCharacter; exports2.getMirroredCharactersMap = getMirroredCharactersMap; exports2.getReorderSegments = getReorderSegments; exports2.getReorderedIndices = getReorderedIndices; exports2.getReorderedString = getReorderedString; exports2.openingToClosingBracket = openingToClosingBracket; Object.defineProperty(exports2, "__esModule", { value: true }); return exports2; })({}); return bidi; } var bidi_default = bidiFactory; // node_modules/troika-three-utils/dist/troika-three-utils.esm.js var voidMainRegExp = /\bvoid\s+main\s*\(\s*\)\s*{/g; function expandShaderIncludes(source) { const pattern = /^[ \t]*#include +<([\w\d./]+)>/gm; function replace(match, include) { let chunk = ShaderChunk[include]; return chunk ? expandShaderIncludes(chunk) : match; } return source.replace(pattern, replace); } var _lut = []; for (let i4 = 0; i4 < 256; i4++) { _lut[i4] = (i4 < 16 ? "0" : "") + i4.toString(16); } function generateUUID() { const d0 = Math.random() * 4294967295 | 0; const d1 = Math.random() * 4294967295 | 0; const d2 = Math.random() * 4294967295 | 0; const d3 = Math.random() * 4294967295 | 0; const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255]; return uuid.toUpperCase(); } var assign = Object.assign || function() { let target2 = arguments[0]; for (let i4 = 1, len = arguments.length; i4 < len; i4++) { let source = arguments[i4]; if (source) { for (let prop in source) { if (Object.prototype.hasOwnProperty.call(source, prop)) { target2[prop] = source[prop]; } } } } return target2; }; var epoch = Date.now(); var CONSTRUCTOR_CACHE = /* @__PURE__ */ new WeakMap(); var SHADER_UPGRADE_CACHE = /* @__PURE__ */ new Map(); var materialInstanceId = 1e10; function createDerivedMaterial(baseMaterial, options) { const optionsKey = getKeyForOptions(options); let ctorsByDerivation = CONSTRUCTOR_CACHE.get(baseMaterial); if (!ctorsByDerivation) { CONSTRUCTOR_CACHE.set(baseMaterial, ctorsByDerivation = /* @__PURE__ */ Object.create(null)); } if (ctorsByDerivation[optionsKey]) { return new ctorsByDerivation[optionsKey](); } const privateBeforeCompileProp = `_onBeforeCompile${optionsKey}`; const onBeforeCompile = function(shaderInfo, renderer) { baseMaterial.onBeforeCompile.call(this, shaderInfo, renderer); const cacheKey = this.customProgramCacheKey() + "|" + shaderInfo.vertexShader + "|" + shaderInfo.fragmentShader; let upgradedShaders = SHADER_UPGRADE_CACHE[cacheKey]; if (!upgradedShaders) { const upgraded = upgradeShaders(this, shaderInfo, options, optionsKey); upgradedShaders = SHADER_UPGRADE_CACHE[cacheKey] = upgraded; } shaderInfo.vertexShader = upgradedShaders.vertexShader; shaderInfo.fragmentShader = upgradedShaders.fragmentShader; assign(shaderInfo.uniforms, this.uniforms); if (options.timeUniform) { shaderInfo.uniforms[options.timeUniform] = { get value() { return Date.now() - epoch; } }; } if (this[privateBeforeCompileProp]) { this[privateBeforeCompileProp](shaderInfo); } }; const DerivedMaterial = function DerivedMaterial2() { return derive(options.chained ? baseMaterial : baseMaterial.clone()); }; const derive = function(base) { const derived = Object.create(base, descriptor); Object.defineProperty(derived, "baseMaterial", { value: baseMaterial }); Object.defineProperty(derived, "id", { value: materialInstanceId++ }); derived.uuid = generateUUID(); derived.uniforms = assign({}, base.uniforms, options.uniforms); derived.defines = assign({}, base.defines, options.defines); derived.defines[`TROIKA_DERIVED_MATERIAL_${optionsKey}`] = ""; derived.extensions = assign({}, base.extensions, options.extensions); derived._listeners = void 0; return derived; }; const descriptor = { constructor: { value: DerivedMaterial }, isDerivedMaterial: { value: true }, type: { get: () => baseMaterial.type, set: (value) => { baseMaterial.type = value; } }, isDerivedFrom: { writable: true, configurable: true, value: function(testMaterial) { const base = this.baseMaterial; return testMaterial === base || base.isDerivedMaterial && base.isDerivedFrom(testMaterial) || false; } }, customProgramCacheKey: { writable: true, configurable: true, value: function() { return baseMaterial.customProgramCacheKey() + "|" + optionsKey; } }, onBeforeCompile: { get() { return onBeforeCompile; }, set(fn) { this[privateBeforeCompileProp] = fn; } }, copy: { writable: true, configurable: true, value: function(source) { baseMaterial.copy.call(this, source); if (!baseMaterial.isShaderMaterial && !baseMaterial.isDerivedMaterial) { assign(this.extensions, source.extensions); assign(this.defines, source.defines); assign(this.uniforms, UniformsUtils.clone(source.uniforms)); } return this; } }, clone: { writable: true, configurable: true, value: function() { const newBase = new baseMaterial.constructor(); return derive(newBase).copy(this); } }, /** * Utility to get a MeshDepthMaterial that will honor this derived material's vertex * transformations and discarded fragments. */ getDepthMaterial: { writable: true, configurable: true, value: function() { let depthMaterial = this._depthMaterial; if (!depthMaterial) { depthMaterial = this._depthMaterial = createDerivedMaterial( baseMaterial.isDerivedMaterial ? baseMaterial.getDepthMaterial() : new MeshDepthMaterial({ depthPacking: RGBADepthPacking }), options ); depthMaterial.defines.IS_DEPTH_MATERIAL = ""; depthMaterial.uniforms = this.uniforms; } return depthMaterial; } }, /** * Utility to get a MeshDistanceMaterial that will honor this derived material's vertex * transformations and discarded fragments. */ getDistanceMaterial: { writable: true, configurable: true, value: function() { let distanceMaterial = this._distanceMaterial; if (!distanceMaterial) { distanceMaterial = this._distanceMaterial = createDerivedMaterial( baseMaterial.isDerivedMaterial ? baseMaterial.getDistanceMaterial() : new MeshDistanceMaterial(), options ); distanceMaterial.defines.IS_DISTANCE_MATERIAL = ""; distanceMaterial.uniforms = this.uniforms; } return distanceMaterial; } }, dispose: { writable: true, configurable: true, value() { const { _depthMaterial, _distanceMaterial } = this; if (_depthMaterial) _depthMaterial.dispose(); if (_distanceMaterial) _distanceMaterial.dispose(); baseMaterial.dispose.call(this); } } }; ctorsByDerivation[optionsKey] = DerivedMaterial; return new DerivedMaterial(); } function upgradeShaders(material, { vertexShader: vertexShader3, fragmentShader: fragmentShader3 }, options, key) { let { vertexDefs, vertexMainIntro, vertexMainOutro, vertexTransform, fragmentDefs, fragmentMainIntro, fragmentMainOutro, fragmentColorTransform, customRewriter, timeUniform } = options; vertexDefs = vertexDefs || ""; vertexMainIntro = vertexMainIntro || ""; vertexMainOutro = vertexMainOutro || ""; fragmentDefs = fragmentDefs || ""; fragmentMainIntro = fragmentMainIntro || ""; fragmentMainOutro = fragmentMainOutro || ""; if (vertexTransform || customRewriter) { vertexShader3 = expandShaderIncludes(vertexShader3); } if (fragmentColorTransform || customRewriter) { fragmentShader3 = fragmentShader3.replace( /^[ \t]*#include <((?:tonemapping|encodings|colorspace|fog|premultiplied_alpha|dithering)_fragment)>/gm, "\n//!BEGIN_POST_CHUNK $1\n$&\n//!END_POST_CHUNK\n" ); fragmentShader3 = expandShaderIncludes(fragmentShader3); } if (customRewriter) { let res = customRewriter({ vertexShader: vertexShader3, fragmentShader: fragmentShader3 }); vertexShader3 = res.vertexShader; fragmentShader3 = res.fragmentShader; } if (fragmentColorTransform) { let postChunks = []; fragmentShader3 = fragmentShader3.replace( /^\/\/!BEGIN_POST_CHUNK[^]+?^\/\/!END_POST_CHUNK/gm, // [^]+? = non-greedy match of any chars including newlines (match) => { postChunks.push(match); return ""; } ); fragmentMainOutro = `${fragmentColorTransform} ${postChunks.join("\n")} ${fragmentMainOutro}`; } if (timeUniform) { const code = ` uniform float ${timeUniform}; `; vertexDefs = code + vertexDefs; fragmentDefs = code + fragmentDefs; } if (vertexTransform) { vertexShader3 = `vec3 troika_position_${key}; vec3 troika_normal_${key}; vec2 troika_uv_${key}; ${vertexShader3} `; vertexDefs = `${vertexDefs} void troikaVertexTransform${key}(inout vec3 position, inout vec3 normal, inout vec2 uv) { ${vertexTransform} } `; vertexMainIntro = ` troika_position_${key} = vec3(position); troika_normal_${key} = vec3(normal); troika_uv_${key} = vec2(uv); troikaVertexTransform${key}(troika_position_${key}, troika_normal_${key}, troika_uv_${key}); ${vertexMainIntro} `; vertexShader3 = vertexShader3.replace(/\b(position|normal|uv)\b/g, (match, match1, index2, fullStr) => { return /\battribute\s+vec[23]\s+$/.test(fullStr.substr(0, index2)) ? match1 : `troika_${match1}_${key}`; }); if (!(material.map && material.map.channel > 0)) { vertexShader3 = vertexShader3.replace(/\bMAP_UV\b/g, `troika_uv_${key}`); } } vertexShader3 = injectIntoShaderCode(vertexShader3, key, vertexDefs, vertexMainIntro, vertexMainOutro); fragmentShader3 = injectIntoShaderCode(fragmentShader3, key, fragmentDefs, fragmentMainIntro, fragmentMainOutro); return { vertexShader: vertexShader3, fragmentShader: fragmentShader3 }; } function injectIntoShaderCode(shaderCode, id, defs, intro, outro) { if (intro || outro || defs) { shaderCode = shaderCode.replace( voidMainRegExp, ` ${defs} void troikaOrigMain${id}() {` ); shaderCode += ` void main() { ${intro} troikaOrigMain${id}(); ${outro} }`; } return shaderCode; } function optionsJsonReplacer(key, value) { return key === "uniforms" ? void 0 : typeof value === "function" ? value.toString() : value; } var _idCtr = 0; var optionsHashesToIds = /* @__PURE__ */ new Map(); function getKeyForOptions(options) { const optionsHash = JSON.stringify(options, optionsJsonReplacer); let id = optionsHashesToIds.get(optionsHash); if (id == null) { optionsHashesToIds.set(optionsHash, id = ++_idCtr); } return id; } var defaultBaseMaterial = new MeshStandardMaterial({ color: 16777215, side: DoubleSide }); // node_modules/troika-three-text/dist/troika-three-text.esm.js function typrFactory() { return "undefined" == typeof window && (self.window = self), (function(r2) { var e2 = { parse: function(r3) { var t4 = e2._bin, a7 = new Uint8Array(r3); if ("ttcf" == t4.readASCII(a7, 0, 4)) { var n2 = 4; t4.readUshort(a7, n2), n2 += 2, t4.readUshort(a7, n2), n2 += 2; var o2 = t4.readUint(a7, n2); n2 += 4; for (var s2 = [], i4 = 0; i4 < o2; i4++) { var h = t4.readUint(a7, n2); n2 += 4, s2.push(e2._readFont(a7, h)); } return s2; } return [e2._readFont(a7, 0)]; }, _readFont: function(r3, t4) { var a7 = e2._bin, n2 = t4; a7.readFixed(r3, t4), t4 += 4; var o2 = a7.readUshort(r3, t4); t4 += 2, a7.readUshort(r3, t4), t4 += 2, a7.readUshort(r3, t4), t4 += 2, a7.readUshort(r3, t4), t4 += 2; for (var s2 = ["cmap", "head", "hhea", "maxp", "hmtx", "name", "OS/2", "post", "loca", "glyf", "kern", "CFF ", "GDEF", "GPOS", "GSUB", "SVG "], i4 = { _data: r3, _offset: n2 }, h = {}, d2 = 0; d2 < o2; d2++) { var f2 = a7.readASCII(r3, t4, 4); t4 += 4, a7.readUint(r3, t4), t4 += 4; var u = a7.readUint(r3, t4); t4 += 4; var l2 = a7.readUint(r3, t4); t4 += 4, h[f2] = { offset: u, length: l2 }; } for (d2 = 0; d2 < s2.length; d2++) { var v5 = s2[d2]; h[v5] && (i4[v5.trim()] = e2[v5.trim()].parse(r3, h[v5].offset, h[v5].length, i4)); } return i4; }, _tabOffset: function(r3, t4, a7) { for (var n2 = e2._bin, o2 = n2.readUshort(r3, a7 + 4), s2 = a7 + 12, i4 = 0; i4 < o2; i4++) { var h = n2.readASCII(r3, s2, 4); s2 += 4, n2.readUint(r3, s2), s2 += 4; var d2 = n2.readUint(r3, s2); if (s2 += 4, n2.readUint(r3, s2), s2 += 4, h == t4) return d2; } return 0; } }; e2._bin = { readFixed: function(r3, e3) { return (r3[e3] << 8 | r3[e3 + 1]) + (r3[e3 + 2] << 8 | r3[e3 + 3]) / 65540; }, readF2dot14: function(r3, t4) { return e2._bin.readShort(r3, t4) / 16384; }, readInt: function(r3, t4) { return e2._bin._view(r3).getInt32(t4); }, readInt8: function(r3, t4) { return e2._bin._view(r3).getInt8(t4); }, readShort: function(r3, t4) { return e2._bin._view(r3).getInt16(t4); }, readUshort: function(r3, t4) { return e2._bin._view(r3).getUint16(t4); }, readUshorts: function(r3, t4, a7) { for (var n2 = [], o2 = 0; o2 < a7; o2++) n2.push(e2._bin.readUshort(r3, t4 + 2 * o2)); return n2; }, readUint: function(r3, t4) { return e2._bin._view(r3).getUint32(t4); }, readUint64: function(r3, t4) { return 4294967296 * e2._bin.readUint(r3, t4) + e2._bin.readUint(r3, t4 + 4); }, readASCII: function(r3, e3, t4) { for (var a7 = "", n2 = 0; n2 < t4; n2++) a7 += String.fromCharCode(r3[e3 + n2]); return a7; }, readUnicode: function(r3, e3, t4) { for (var a7 = "", n2 = 0; n2 < t4; n2++) { var o2 = r3[e3++] << 8 | r3[e3++]; a7 += String.fromCharCode(o2); } return a7; }, _tdec: "undefined" != typeof window && window.TextDecoder ? new window.TextDecoder() : null, readUTF8: function(r3, t4, a7) { var n2 = e2._bin._tdec; return n2 && 0 == t4 && a7 == r3.length ? n2.decode(r3) : e2._bin.readASCII(r3, t4, a7); }, readBytes: function(r3, e3, t4) { for (var a7 = [], n2 = 0; n2 < t4; n2++) a7.push(r3[e3 + n2]); return a7; }, readASCIIArray: function(r3, e3, t4) { for (var a7 = [], n2 = 0; n2 < t4; n2++) a7.push(String.fromCharCode(r3[e3 + n2])); return a7; }, _view: function(r3) { return r3._dataView || (r3._dataView = r3.buffer ? new DataView(r3.buffer, r3.byteOffset, r3.byteLength) : new DataView(new Uint8Array(r3).buffer)); } }, e2._lctf = {}, e2._lctf.parse = function(r3, t4, a7, n2, o2) { var s2 = e2._bin, i4 = {}, h = t4; s2.readFixed(r3, t4), t4 += 4; var d2 = s2.readUshort(r3, t4); t4 += 2; var f2 = s2.readUshort(r3, t4); t4 += 2; var u = s2.readUshort(r3, t4); return t4 += 2, i4.scriptList = e2._lctf.readScriptList(r3, h + d2), i4.featureList = e2._lctf.readFeatureList(r3, h + f2), i4.lookupList = e2._lctf.readLookupList(r3, h + u, o2), i4; }, e2._lctf.readLookupList = function(r3, t4, a7) { var n2 = e2._bin, o2 = t4, s2 = [], i4 = n2.readUshort(r3, t4); t4 += 2; for (var h = 0; h < i4; h++) { var d2 = n2.readUshort(r3, t4); t4 += 2; var f2 = e2._lctf.readLookupTable(r3, o2 + d2, a7); s2.push(f2); } return s2; }, e2._lctf.readLookupTable = function(r3, t4, a7) { var n2 = e2._bin, o2 = t4, s2 = { tabs: [] }; s2.ltype = n2.readUshort(r3, t4), t4 += 2, s2.flag = n2.readUshort(r3, t4), t4 += 2; var i4 = n2.readUshort(r3, t4); t4 += 2; for (var h = s2.ltype, d2 = 0; d2 < i4; d2++) { var f2 = n2.readUshort(r3, t4); t4 += 2; var u = a7(r3, h, o2 + f2, s2); s2.tabs.push(u); } return s2; }, e2._lctf.numOfOnes = function(r3) { for (var e3 = 0, t4 = 0; t4 < 32; t4++) 0 != (r3 >>> t4 & 1) && e3++; return e3; }, e2._lctf.readClassDef = function(r3, t4) { var a7 = e2._bin, n2 = [], o2 = a7.readUshort(r3, t4); if (t4 += 2, 1 == o2) { var s2 = a7.readUshort(r3, t4); t4 += 2; var i4 = a7.readUshort(r3, t4); t4 += 2; for (var h = 0; h < i4; h++) n2.push(s2 + h), n2.push(s2 + h), n2.push(a7.readUshort(r3, t4)), t4 += 2; } if (2 == o2) { var d2 = a7.readUshort(r3, t4); t4 += 2; for (h = 0; h < d2; h++) n2.push(a7.readUshort(r3, t4)), t4 += 2, n2.push(a7.readUshort(r3, t4)), t4 += 2, n2.push(a7.readUshort(r3, t4)), t4 += 2; } return n2; }, e2._lctf.getInterval = function(r3, e3) { for (var t4 = 0; t4 < r3.length; t4 += 3) { var a7 = r3[t4], n2 = r3[t4 + 1]; if (r3[t4 + 2], a7 <= e3 && e3 <= n2) return t4; } return -1; }, e2._lctf.readCoverage = function(r3, t4) { var a7 = e2._bin, n2 = {}; n2.fmt = a7.readUshort(r3, t4), t4 += 2; var o2 = a7.readUshort(r3, t4); return t4 += 2, 1 == n2.fmt && (n2.tab = a7.readUshorts(r3, t4, o2)), 2 == n2.fmt && (n2.tab = a7.readUshorts(r3, t4, 3 * o2)), n2; }, e2._lctf.coverageIndex = function(r3, t4) { var a7 = r3.tab; if (1 == r3.fmt) return a7.indexOf(t4); if (2 == r3.fmt) { var n2 = e2._lctf.getInterval(a7, t4); if (-1 != n2) return a7[n2 + 2] + (t4 - a7[n2]); } return -1; }, e2._lctf.readFeatureList = function(r3, t4) { var a7 = e2._bin, n2 = t4, o2 = [], s2 = a7.readUshort(r3, t4); t4 += 2; for (var i4 = 0; i4 < s2; i4++) { var h = a7.readASCII(r3, t4, 4); t4 += 4; var d2 = a7.readUshort(r3, t4); t4 += 2; var f2 = e2._lctf.readFeatureTable(r3, n2 + d2); f2.tag = h.trim(), o2.push(f2); } return o2; }, e2._lctf.readFeatureTable = function(r3, t4) { var a7 = e2._bin, n2 = t4, o2 = {}, s2 = a7.readUshort(r3, t4); t4 += 2, s2 > 0 && (o2.featureParams = n2 + s2); var i4 = a7.readUshort(r3, t4); t4 += 2, o2.tab = []; for (var h = 0; h < i4; h++) o2.tab.push(a7.readUshort(r3, t4 + 2 * h)); return o2; }, e2._lctf.readScriptList = function(r3, t4) { var a7 = e2._bin, n2 = t4, o2 = {}, s2 = a7.readUshort(r3, t4); t4 += 2; for (var i4 = 0; i4 < s2; i4++) { var h = a7.readASCII(r3, t4, 4); t4 += 4; var d2 = a7.readUshort(r3, t4); t4 += 2, o2[h.trim()] = e2._lctf.readScriptTable(r3, n2 + d2); } return o2; }, e2._lctf.readScriptTable = function(r3, t4) { var a7 = e2._bin, n2 = t4, o2 = {}, s2 = a7.readUshort(r3, t4); t4 += 2, s2 > 0 && (o2.default = e2._lctf.readLangSysTable(r3, n2 + s2)); var i4 = a7.readUshort(r3, t4); t4 += 2; for (var h = 0; h < i4; h++) { var d2 = a7.readASCII(r3, t4, 4); t4 += 4; var f2 = a7.readUshort(r3, t4); t4 += 2, o2[d2.trim()] = e2._lctf.readLangSysTable(r3, n2 + f2); } return o2; }, e2._lctf.readLangSysTable = function(r3, t4) { var a7 = e2._bin, n2 = {}; a7.readUshort(r3, t4), t4 += 2, n2.reqFeature = a7.readUshort(r3, t4), t4 += 2; var o2 = a7.readUshort(r3, t4); return t4 += 2, n2.features = a7.readUshorts(r3, t4, o2), n2; }, e2.CFF = {}, e2.CFF.parse = function(r3, t4, a7) { var n2 = e2._bin; (r3 = new Uint8Array(r3.buffer, t4, a7))[t4 = 0], r3[++t4], r3[++t4], r3[++t4], t4++; var o2 = []; t4 = e2.CFF.readIndex(r3, t4, o2); for (var s2 = [], i4 = 0; i4 < o2.length - 1; i4++) s2.push(n2.readASCII(r3, t4 + o2[i4], o2[i4 + 1] - o2[i4])); t4 += o2[o2.length - 1]; var h = []; t4 = e2.CFF.readIndex(r3, t4, h); var d2 = []; for (i4 = 0; i4 < h.length - 1; i4++) d2.push(e2.CFF.readDict(r3, t4 + h[i4], t4 + h[i4 + 1])); t4 += h[h.length - 1]; var f2 = d2[0], u = []; t4 = e2.CFF.readIndex(r3, t4, u); var l2 = []; for (i4 = 0; i4 < u.length - 1; i4++) l2.push(n2.readASCII(r3, t4 + u[i4], u[i4 + 1] - u[i4])); if (t4 += u[u.length - 1], e2.CFF.readSubrs(r3, t4, f2), f2.CharStrings) { t4 = f2.CharStrings; u = []; t4 = e2.CFF.readIndex(r3, t4, u); var v5 = []; for (i4 = 0; i4 < u.length - 1; i4++) v5.push(n2.readBytes(r3, t4 + u[i4], u[i4 + 1] - u[i4])); f2.CharStrings = v5; } if (f2.ROS) { t4 = f2.FDArray; var c2 = []; t4 = e2.CFF.readIndex(r3, t4, c2), f2.FDArray = []; for (i4 = 0; i4 < c2.length - 1; i4++) { var p2 = e2.CFF.readDict(r3, t4 + c2[i4], t4 + c2[i4 + 1]); e2.CFF._readFDict(r3, p2, l2), f2.FDArray.push(p2); } t4 += c2[c2.length - 1], t4 = f2.FDSelect, f2.FDSelect = []; var U = r3[t4]; if (t4++, 3 != U) throw U; var g = n2.readUshort(r3, t4); t4 += 2; for (i4 = 0; i4 < g + 1; i4++) f2.FDSelect.push(n2.readUshort(r3, t4), r3[t4 + 2]), t4 += 3; } return f2.Encoding && (f2.Encoding = e2.CFF.readEncoding(r3, f2.Encoding, f2.CharStrings.length)), f2.charset && (f2.charset = e2.CFF.readCharset(r3, f2.charset, f2.CharStrings.length)), e2.CFF._readFDict(r3, f2, l2), f2; }, e2.CFF._readFDict = function(r3, t4, a7) { var n2; for (var o2 in t4.Private && (n2 = t4.Private[1], t4.Private = e2.CFF.readDict(r3, n2, n2 + t4.Private[0]), t4.Private.Subrs && e2.CFF.readSubrs(r3, n2 + t4.Private.Subrs, t4.Private)), t4) -1 != ["FamilyName", "FontName", "FullName", "Notice", "version", "Copyright"].indexOf(o2) && (t4[o2] = a7[t4[o2] - 426 + 35]); }, e2.CFF.readSubrs = function(r3, t4, a7) { var n2 = e2._bin, o2 = []; t4 = e2.CFF.readIndex(r3, t4, o2); var s2, i4 = o2.length; s2 = i4 < 1240 ? 107 : i4 < 33900 ? 1131 : 32768, a7.Bias = s2, a7.Subrs = []; for (var h = 0; h < o2.length - 1; h++) a7.Subrs.push(n2.readBytes(r3, t4 + o2[h], o2[h + 1] - o2[h])); }, e2.CFF.tableSE = [0, 0, 0, 0, 0, 0, 0, 0, 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, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 0, 115, 116, 117, 118, 119, 120, 121, 122, 0, 123, 0, 124, 125, 126, 127, 128, 129, 130, 131, 0, 132, 133, 0, 134, 135, 136, 137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 138, 0, 139, 0, 0, 0, 0, 140, 141, 142, 143, 0, 0, 0, 0, 0, 144, 0, 0, 0, 145, 0, 0, 146, 147, 148, 149, 0, 0, 0, 0], e2.CFF.glyphByUnicode = function(r3, e3) { for (var t4 = 0; t4 < r3.charset.length; t4++) if (r3.charset[t4] == e3) return t4; return -1; }, e2.CFF.glyphBySE = function(r3, t4) { return t4 < 0 || t4 > 255 ? -1 : e2.CFF.glyphByUnicode(r3, e2.CFF.tableSE[t4]); }, e2.CFF.readEncoding = function(r3, t4, a7) { e2._bin; var n2 = [".notdef"], o2 = r3[t4]; if (t4++, 0 != o2) throw "error: unknown encoding format: " + o2; var s2 = r3[t4]; t4++; for (var i4 = 0; i4 < s2; i4++) n2.push(r3[t4 + i4]); return n2; }, e2.CFF.readCharset = function(r3, t4, a7) { var n2 = e2._bin, o2 = [".notdef"], s2 = r3[t4]; if (t4++, 0 == s2) for (var i4 = 0; i4 < a7; i4++) { var h = n2.readUshort(r3, t4); t4 += 2, o2.push(h); } else { if (1 != s2 && 2 != s2) throw "error: format: " + s2; for (; o2.length < a7; ) { h = n2.readUshort(r3, t4); t4 += 2; var d2 = 0; 1 == s2 ? (d2 = r3[t4], t4++) : (d2 = n2.readUshort(r3, t4), t4 += 2); for (i4 = 0; i4 <= d2; i4++) o2.push(h), h++; } } return o2; }, e2.CFF.readIndex = function(r3, t4, a7) { var n2 = e2._bin, o2 = n2.readUshort(r3, t4) + 1, s2 = r3[t4 += 2]; if (t4++, 1 == s2) for (var i4 = 0; i4 < o2; i4++) a7.push(r3[t4 + i4]); else if (2 == s2) for (i4 = 0; i4 < o2; i4++) a7.push(n2.readUshort(r3, t4 + 2 * i4)); else if (3 == s2) for (i4 = 0; i4 < o2; i4++) a7.push(16777215 & n2.readUint(r3, t4 + 3 * i4 - 1)); else if (1 != o2) throw "unsupported offset size: " + s2 + ", count: " + o2; return (t4 += o2 * s2) - 1; }, e2.CFF.getCharString = function(r3, t4, a7) { var n2 = e2._bin, o2 = r3[t4], s2 = r3[t4 + 1]; r3[t4 + 2], r3[t4 + 3], r3[t4 + 4]; var i4 = 1, h = null, d2 = null; o2 <= 20 && (h = o2, i4 = 1), 12 == o2 && (h = 100 * o2 + s2, i4 = 2), 21 <= o2 && o2 <= 27 && (h = o2, i4 = 1), 28 == o2 && (d2 = n2.readShort(r3, t4 + 1), i4 = 3), 29 <= o2 && o2 <= 31 && (h = o2, i4 = 1), 32 <= o2 && o2 <= 246 && (d2 = o2 - 139, i4 = 1), 247 <= o2 && o2 <= 250 && (d2 = 256 * (o2 - 247) + s2 + 108, i4 = 2), 251 <= o2 && o2 <= 254 && (d2 = 256 * -(o2 - 251) - s2 - 108, i4 = 2), 255 == o2 && (d2 = n2.readInt(r3, t4 + 1) / 65535, i4 = 5), a7.val = null != d2 ? d2 : "o" + h, a7.size = i4; }, e2.CFF.readCharString = function(r3, t4, a7) { for (var n2 = t4 + a7, o2 = e2._bin, s2 = []; t4 < n2; ) { var i4 = r3[t4], h = r3[t4 + 1]; r3[t4 + 2], r3[t4 + 3], r3[t4 + 4]; var d2 = 1, f2 = null, u = null; i4 <= 20 && (f2 = i4, d2 = 1), 12 == i4 && (f2 = 100 * i4 + h, d2 = 2), 19 != i4 && 20 != i4 || (f2 = i4, d2 = 2), 21 <= i4 && i4 <= 27 && (f2 = i4, d2 = 1), 28 == i4 && (u = o2.readShort(r3, t4 + 1), d2 = 3), 29 <= i4 && i4 <= 31 && (f2 = i4, d2 = 1), 32 <= i4 && i4 <= 246 && (u = i4 - 139, d2 = 1), 247 <= i4 && i4 <= 250 && (u = 256 * (i4 - 247) + h + 108, d2 = 2), 251 <= i4 && i4 <= 254 && (u = 256 * -(i4 - 251) - h - 108, d2 = 2), 255 == i4 && (u = o2.readInt(r3, t4 + 1) / 65535, d2 = 5), s2.push(null != u ? u : "o" + f2), t4 += d2; } return s2; }, e2.CFF.readDict = function(r3, t4, a7) { for (var n2 = e2._bin, o2 = {}, s2 = []; t4 < a7; ) { var i4 = r3[t4], h = r3[t4 + 1]; r3[t4 + 2], r3[t4 + 3], r3[t4 + 4]; var d2 = 1, f2 = null, u = null; if (28 == i4 && (u = n2.readShort(r3, t4 + 1), d2 = 3), 29 == i4 && (u = n2.readInt(r3, t4 + 1), d2 = 5), 32 <= i4 && i4 <= 246 && (u = i4 - 139, d2 = 1), 247 <= i4 && i4 <= 250 && (u = 256 * (i4 - 247) + h + 108, d2 = 2), 251 <= i4 && i4 <= 254 && (u = 256 * -(i4 - 251) - h - 108, d2 = 2), 255 == i4) throw u = n2.readInt(r3, t4 + 1) / 65535, d2 = 5, "unknown number"; if (30 == i4) { var l2 = []; for (d2 = 1; ; ) { var v5 = r3[t4 + d2]; d2++; var c2 = v5 >> 4, p2 = 15 & v5; if (15 != c2 && l2.push(c2), 15 != p2 && l2.push(p2), 15 == p2) break; } for (var U = "", g = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ".", "e", "e-", "reserved", "-", "endOfNumber"], S = 0; S < l2.length; S++) U += g[l2[S]]; u = parseFloat(U); } if (i4 <= 21) { if (f2 = ["version", "Notice", "FullName", "FamilyName", "Weight", "FontBBox", "BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "StdHW", "StdVW", "escape", "UniqueID", "XUID", "charset", "Encoding", "CharStrings", "Private", "Subrs", "defaultWidthX", "nominalWidthX"][i4], d2 = 1, 12 == i4) f2 = ["Copyright", "isFixedPitch", "ItalicAngle", "UnderlinePosition", "UnderlineThickness", "PaintType", "CharstringType", "FontMatrix", "StrokeWidth", "BlueScale", "BlueShift", "BlueFuzz", "StemSnapH", "StemSnapV", "ForceBold", 0, 0, "LanguageGroup", "ExpansionFactor", "initialRandomSeed", "SyntheticBase", "PostScript", "BaseFontName", "BaseFontBlend", 0, 0, 0, 0, 0, 0, "ROS", "CIDFontVersion", "CIDFontRevision", "CIDFontType", "CIDCount", "UIDBase", "FDArray", "FDSelect", "FontName"][h], d2 = 2; } null != f2 ? (o2[f2] = 1 == s2.length ? s2[0] : s2, s2 = []) : s2.push(u), t4 += d2; } return o2; }, e2.cmap = {}, e2.cmap.parse = function(r3, t4, a7) { r3 = new Uint8Array(r3.buffer, t4, a7), t4 = 0; var n2 = e2._bin, o2 = {}; n2.readUshort(r3, t4), t4 += 2; var s2 = n2.readUshort(r3, t4); t4 += 2; var i4 = []; o2.tables = []; for (var h = 0; h < s2; h++) { var d2 = n2.readUshort(r3, t4); t4 += 2; var f2 = n2.readUshort(r3, t4); t4 += 2; var u = n2.readUint(r3, t4); t4 += 4; var l2 = "p" + d2 + "e" + f2, v5 = i4.indexOf(u); if (-1 == v5) { var c2; v5 = o2.tables.length, i4.push(u); var p2 = n2.readUshort(r3, u); 0 == p2 ? c2 = e2.cmap.parse0(r3, u) : 4 == p2 ? c2 = e2.cmap.parse4(r3, u) : 6 == p2 ? c2 = e2.cmap.parse6(r3, u) : 12 == p2 ? c2 = e2.cmap.parse12(r3, u) : console.debug("unknown format: " + p2, d2, f2, u), o2.tables.push(c2); } if (null != o2[l2]) throw "multiple tables for one platform+encoding"; o2[l2] = v5; } return o2; }, e2.cmap.parse0 = function(r3, t4) { var a7 = e2._bin, n2 = {}; n2.format = a7.readUshort(r3, t4), t4 += 2; var o2 = a7.readUshort(r3, t4); t4 += 2, a7.readUshort(r3, t4), t4 += 2, n2.map = []; for (var s2 = 0; s2 < o2 - 6; s2++) n2.map.push(r3[t4 + s2]); return n2; }, e2.cmap.parse4 = function(r3, t4) { var a7 = e2._bin, n2 = t4, o2 = {}; o2.format = a7.readUshort(r3, t4), t4 += 2; var s2 = a7.readUshort(r3, t4); t4 += 2, a7.readUshort(r3, t4), t4 += 2; var i4 = a7.readUshort(r3, t4); t4 += 2; var h = i4 / 2; o2.searchRange = a7.readUshort(r3, t4), t4 += 2, o2.entrySelector = a7.readUshort(r3, t4), t4 += 2, o2.rangeShift = a7.readUshort(r3, t4), t4 += 2, o2.endCount = a7.readUshorts(r3, t4, h), t4 += 2 * h, t4 += 2, o2.startCount = a7.readUshorts(r3, t4, h), t4 += 2 * h, o2.idDelta = []; for (var d2 = 0; d2 < h; d2++) o2.idDelta.push(a7.readShort(r3, t4)), t4 += 2; for (o2.idRangeOffset = a7.readUshorts(r3, t4, h), t4 += 2 * h, o2.glyphIdArray = []; t4 < n2 + s2; ) o2.glyphIdArray.push(a7.readUshort(r3, t4)), t4 += 2; return o2; }, e2.cmap.parse6 = function(r3, t4) { var a7 = e2._bin, n2 = {}; n2.format = a7.readUshort(r3, t4), t4 += 2, a7.readUshort(r3, t4), t4 += 2, a7.readUshort(r3, t4), t4 += 2, n2.firstCode = a7.readUshort(r3, t4), t4 += 2; var o2 = a7.readUshort(r3, t4); t4 += 2, n2.glyphIdArray = []; for (var s2 = 0; s2 < o2; s2++) n2.glyphIdArray.push(a7.readUshort(r3, t4)), t4 += 2; return n2; }, e2.cmap.parse12 = function(r3, t4) { var a7 = e2._bin, n2 = {}; n2.format = a7.readUshort(r3, t4), t4 += 2, t4 += 2, a7.readUint(r3, t4), t4 += 4, a7.readUint(r3, t4), t4 += 4; var o2 = a7.readUint(r3, t4); t4 += 4, n2.groups = []; for (var s2 = 0; s2 < o2; s2++) { var i4 = t4 + 12 * s2, h = a7.readUint(r3, i4 + 0), d2 = a7.readUint(r3, i4 + 4), f2 = a7.readUint(r3, i4 + 8); n2.groups.push([h, d2, f2]); } return n2; }, e2.glyf = {}, e2.glyf.parse = function(r3, e3, t4, a7) { for (var n2 = [], o2 = 0; o2 < a7.maxp.numGlyphs; o2++) n2.push(null); return n2; }, e2.glyf._parseGlyf = function(r3, t4) { var a7 = e2._bin, n2 = r3._data, o2 = e2._tabOffset(n2, "glyf", r3._offset) + r3.loca[t4]; if (r3.loca[t4] == r3.loca[t4 + 1]) return null; var s2 = {}; if (s2.noc = a7.readShort(n2, o2), o2 += 2, s2.xMin = a7.readShort(n2, o2), o2 += 2, s2.yMin = a7.readShort(n2, o2), o2 += 2, s2.xMax = a7.readShort(n2, o2), o2 += 2, s2.yMax = a7.readShort(n2, o2), o2 += 2, s2.xMin >= s2.xMax || s2.yMin >= s2.yMax) return null; if (s2.noc > 0) { s2.endPts = []; for (var i4 = 0; i4 < s2.noc; i4++) s2.endPts.push(a7.readUshort(n2, o2)), o2 += 2; var h = a7.readUshort(n2, o2); if (o2 += 2, n2.length - o2 < h) return null; s2.instructions = a7.readBytes(n2, o2, h), o2 += h; var d2 = s2.endPts[s2.noc - 1] + 1; s2.flags = []; for (i4 = 0; i4 < d2; i4++) { var f2 = n2[o2]; if (o2++, s2.flags.push(f2), 0 != (8 & f2)) { var u = n2[o2]; o2++; for (var l2 = 0; l2 < u; l2++) s2.flags.push(f2), i4++; } } s2.xs = []; for (i4 = 0; i4 < d2; i4++) { var v5 = 0 != (2 & s2.flags[i4]), c2 = 0 != (16 & s2.flags[i4]); v5 ? (s2.xs.push(c2 ? n2[o2] : -n2[o2]), o2++) : c2 ? s2.xs.push(0) : (s2.xs.push(a7.readShort(n2, o2)), o2 += 2); } s2.ys = []; for (i4 = 0; i4 < d2; i4++) { v5 = 0 != (4 & s2.flags[i4]), c2 = 0 != (32 & s2.flags[i4]); v5 ? (s2.ys.push(c2 ? n2[o2] : -n2[o2]), o2++) : c2 ? s2.ys.push(0) : (s2.ys.push(a7.readShort(n2, o2)), o2 += 2); } var p2 = 0, U = 0; for (i4 = 0; i4 < d2; i4++) p2 += s2.xs[i4], U += s2.ys[i4], s2.xs[i4] = p2, s2.ys[i4] = U; } else { var g; s2.parts = []; do { g = a7.readUshort(n2, o2), o2 += 2; var S = { m: { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 }, p1: -1, p2: -1 }; if (s2.parts.push(S), S.glyphIndex = a7.readUshort(n2, o2), o2 += 2, 1 & g) { var m = a7.readShort(n2, o2); o2 += 2; var b5 = a7.readShort(n2, o2); o2 += 2; } else { m = a7.readInt8(n2, o2); o2++; b5 = a7.readInt8(n2, o2); o2++; } 2 & g ? (S.m.tx = m, S.m.ty = b5) : (S.p1 = m, S.p2 = b5), 8 & g ? (S.m.a = S.m.d = a7.readF2dot14(n2, o2), o2 += 2) : 64 & g ? (S.m.a = a7.readF2dot14(n2, o2), o2 += 2, S.m.d = a7.readF2dot14(n2, o2), o2 += 2) : 128 & g && (S.m.a = a7.readF2dot14(n2, o2), o2 += 2, S.m.b = a7.readF2dot14(n2, o2), o2 += 2, S.m.c = a7.readF2dot14(n2, o2), o2 += 2, S.m.d = a7.readF2dot14(n2, o2), o2 += 2); } while (32 & g); if (256 & g) { var y = a7.readUshort(n2, o2); o2 += 2, s2.instr = []; for (i4 = 0; i4 < y; i4++) s2.instr.push(n2[o2]), o2++; } } return s2; }, e2.GDEF = {}, e2.GDEF.parse = function(r3, t4, a7, n2) { var o2 = t4; t4 += 4; var s2 = e2._bin.readUshort(r3, t4); return { glyphClassDef: 0 === s2 ? null : e2._lctf.readClassDef(r3, o2 + s2) }; }, e2.GPOS = {}, e2.GPOS.parse = function(r3, t4, a7, n2) { return e2._lctf.parse(r3, t4, a7, n2, e2.GPOS.subt); }, e2.GPOS.subt = function(r3, t4, a7, n2) { var o2 = e2._bin, s2 = a7, i4 = {}; if (i4.fmt = o2.readUshort(r3, a7), a7 += 2, 1 == t4 || 2 == t4 || 3 == t4 || 7 == t4 || 8 == t4 && i4.fmt <= 2) { var h = o2.readUshort(r3, a7); a7 += 2, i4.coverage = e2._lctf.readCoverage(r3, h + s2); } if (1 == t4 && 1 == i4.fmt) { var d2 = o2.readUshort(r3, a7); a7 += 2, 0 != d2 && (i4.pos = e2.GPOS.readValueRecord(r3, a7, d2)); } else if (2 == t4 && i4.fmt >= 1 && i4.fmt <= 2) { d2 = o2.readUshort(r3, a7); a7 += 2; var f2 = o2.readUshort(r3, a7); a7 += 2; var u = e2._lctf.numOfOnes(d2), l2 = e2._lctf.numOfOnes(f2); if (1 == i4.fmt) { i4.pairsets = []; var v5 = o2.readUshort(r3, a7); a7 += 2; for (var c2 = 0; c2 < v5; c2++) { var p2 = s2 + o2.readUshort(r3, a7); a7 += 2; var U = o2.readUshort(r3, p2); p2 += 2; for (var g = [], S = 0; S < U; S++) { var m = o2.readUshort(r3, p2); p2 += 2, 0 != d2 && (P = e2.GPOS.readValueRecord(r3, p2, d2), p2 += 2 * u), 0 != f2 && (x = e2.GPOS.readValueRecord(r3, p2, f2), p2 += 2 * l2), g.push({ gid2: m, val1: P, val2: x }); } i4.pairsets.push(g); } } if (2 == i4.fmt) { var b5 = o2.readUshort(r3, a7); a7 += 2; var y = o2.readUshort(r3, a7); a7 += 2; var F = o2.readUshort(r3, a7); a7 += 2; var C = o2.readUshort(r3, a7); a7 += 2, i4.classDef1 = e2._lctf.readClassDef(r3, s2 + b5), i4.classDef2 = e2._lctf.readClassDef(r3, s2 + y), i4.matrix = []; for (c2 = 0; c2 < F; c2++) { var _ = []; for (S = 0; S < C; S++) { var P = null, x = null; 0 != d2 && (P = e2.GPOS.readValueRecord(r3, a7, d2), a7 += 2 * u), 0 != f2 && (x = e2.GPOS.readValueRecord(r3, a7, f2), a7 += 2 * l2), _.push({ val1: P, val2: x }); } i4.matrix.push(_); } } } else if (4 == t4 && 1 == i4.fmt) i4.markCoverage = e2._lctf.readCoverage(r3, o2.readUshort(r3, a7) + s2), i4.baseCoverage = e2._lctf.readCoverage(r3, o2.readUshort(r3, a7 + 2) + s2), i4.markClassCount = o2.readUshort(r3, a7 + 4), i4.markArray = e2.GPOS.readMarkArray(r3, o2.readUshort(r3, a7 + 6) + s2), i4.baseArray = e2.GPOS.readBaseArray(r3, o2.readUshort(r3, a7 + 8) + s2, i4.markClassCount); else if (6 == t4 && 1 == i4.fmt) i4.mark1Coverage = e2._lctf.readCoverage(r3, o2.readUshort(r3, a7) + s2), i4.mark2Coverage = e2._lctf.readCoverage(r3, o2.readUshort(r3, a7 + 2) + s2), i4.markClassCount = o2.readUshort(r3, a7 + 4), i4.mark1Array = e2.GPOS.readMarkArray(r3, o2.readUshort(r3, a7 + 6) + s2), i4.mark2Array = e2.GPOS.readBaseArray(r3, o2.readUshort(r3, a7 + 8) + s2, i4.markClassCount); else { if (9 == t4 && 1 == i4.fmt) { var I = o2.readUshort(r3, a7); a7 += 2; var w = o2.readUint(r3, a7); if (a7 += 4, 9 == n2.ltype) n2.ltype = I; else if (n2.ltype != I) throw "invalid extension substitution"; return e2.GPOS.subt(r3, n2.ltype, s2 + w); } console.debug("unsupported GPOS table LookupType", t4, "format", i4.fmt); } return i4; }, e2.GPOS.readValueRecord = function(r3, t4, a7) { var n2 = e2._bin, o2 = []; return o2.push(1 & a7 ? n2.readShort(r3, t4) : 0), t4 += 1 & a7 ? 2 : 0, o2.push(2 & a7 ? n2.readShort(r3, t4) : 0), t4 += 2 & a7 ? 2 : 0, o2.push(4 & a7 ? n2.readShort(r3, t4) : 0), t4 += 4 & a7 ? 2 : 0, o2.push(8 & a7 ? n2.readShort(r3, t4) : 0), t4 += 8 & a7 ? 2 : 0, o2; }, e2.GPOS.readBaseArray = function(r3, t4, a7) { var n2 = e2._bin, o2 = [], s2 = t4, i4 = n2.readUshort(r3, t4); t4 += 2; for (var h = 0; h < i4; h++) { for (var d2 = [], f2 = 0; f2 < a7; f2++) d2.push(e2.GPOS.readAnchorRecord(r3, s2 + n2.readUshort(r3, t4))), t4 += 2; o2.push(d2); } return o2; }, e2.GPOS.readMarkArray = function(r3, t4) { var a7 = e2._bin, n2 = [], o2 = t4, s2 = a7.readUshort(r3, t4); t4 += 2; for (var i4 = 0; i4 < s2; i4++) { var h = e2.GPOS.readAnchorRecord(r3, a7.readUshort(r3, t4 + 2) + o2); h.markClass = a7.readUshort(r3, t4), n2.push(h), t4 += 4; } return n2; }, e2.GPOS.readAnchorRecord = function(r3, t4) { var a7 = e2._bin, n2 = {}; return n2.fmt = a7.readUshort(r3, t4), n2.x = a7.readShort(r3, t4 + 2), n2.y = a7.readShort(r3, t4 + 4), n2; }, e2.GSUB = {}, e2.GSUB.parse = function(r3, t4, a7, n2) { return e2._lctf.parse(r3, t4, a7, n2, e2.GSUB.subt); }, e2.GSUB.subt = function(r3, t4, a7, n2) { var o2 = e2._bin, s2 = a7, i4 = {}; if (i4.fmt = o2.readUshort(r3, a7), a7 += 2, 1 != t4 && 2 != t4 && 4 != t4 && 5 != t4 && 6 != t4) return null; if (1 == t4 || 2 == t4 || 4 == t4 || 5 == t4 && i4.fmt <= 2 || 6 == t4 && i4.fmt <= 2) { var h = o2.readUshort(r3, a7); a7 += 2, i4.coverage = e2._lctf.readCoverage(r3, s2 + h); } if (1 == t4 && i4.fmt >= 1 && i4.fmt <= 2) { if (1 == i4.fmt) i4.delta = o2.readShort(r3, a7), a7 += 2; else if (2 == i4.fmt) { var d2 = o2.readUshort(r3, a7); a7 += 2, i4.newg = o2.readUshorts(r3, a7, d2), a7 += 2 * i4.newg.length; } } else if (2 == t4 && 1 == i4.fmt) { d2 = o2.readUshort(r3, a7); a7 += 2, i4.seqs = []; for (var f2 = 0; f2 < d2; f2++) { var u = o2.readUshort(r3, a7) + s2; a7 += 2; var l2 = o2.readUshort(r3, u); i4.seqs.push(o2.readUshorts(r3, u + 2, l2)); } } else if (4 == t4) { i4.vals = []; d2 = o2.readUshort(r3, a7); a7 += 2; for (f2 = 0; f2 < d2; f2++) { var v5 = o2.readUshort(r3, a7); a7 += 2, i4.vals.push(e2.GSUB.readLigatureSet(r3, s2 + v5)); } } else if (5 == t4 && 2 == i4.fmt) { if (2 == i4.fmt) { var c2 = o2.readUshort(r3, a7); a7 += 2, i4.cDef = e2._lctf.readClassDef(r3, s2 + c2), i4.scset = []; var p2 = o2.readUshort(r3, a7); a7 += 2; for (f2 = 0; f2 < p2; f2++) { var U = o2.readUshort(r3, a7); a7 += 2, i4.scset.push(0 == U ? null : e2.GSUB.readSubClassSet(r3, s2 + U)); } } } else if (6 == t4 && 3 == i4.fmt) { if (3 == i4.fmt) { for (f2 = 0; f2 < 3; f2++) { d2 = o2.readUshort(r3, a7); a7 += 2; for (var g = [], S = 0; S < d2; S++) g.push(e2._lctf.readCoverage(r3, s2 + o2.readUshort(r3, a7 + 2 * S))); a7 += 2 * d2, 0 == f2 && (i4.backCvg = g), 1 == f2 && (i4.inptCvg = g), 2 == f2 && (i4.ahedCvg = g); } d2 = o2.readUshort(r3, a7); a7 += 2, i4.lookupRec = e2.GSUB.readSubstLookupRecords(r3, a7, d2); } } else { if (7 == t4 && 1 == i4.fmt) { var m = o2.readUshort(r3, a7); a7 += 2; var b5 = o2.readUint(r3, a7); if (a7 += 4, 9 == n2.ltype) n2.ltype = m; else if (n2.ltype != m) throw "invalid extension substitution"; return e2.GSUB.subt(r3, n2.ltype, s2 + b5); } console.debug("unsupported GSUB table LookupType", t4, "format", i4.fmt); } return i4; }, e2.GSUB.readSubClassSet = function(r3, t4) { var a7 = e2._bin.readUshort, n2 = t4, o2 = [], s2 = a7(r3, t4); t4 += 2; for (var i4 = 0; i4 < s2; i4++) { var h = a7(r3, t4); t4 += 2, o2.push(e2.GSUB.readSubClassRule(r3, n2 + h)); } return o2; }, e2.GSUB.readSubClassRule = function(r3, t4) { var a7 = e2._bin.readUshort, n2 = {}, o2 = a7(r3, t4), s2 = a7(r3, t4 += 2); t4 += 2, n2.input = []; for (var i4 = 0; i4 < o2 - 1; i4++) n2.input.push(a7(r3, t4)), t4 += 2; return n2.substLookupRecords = e2.GSUB.readSubstLookupRecords(r3, t4, s2), n2; }, e2.GSUB.readSubstLookupRecords = function(r3, t4, a7) { for (var n2 = e2._bin.readUshort, o2 = [], s2 = 0; s2 < a7; s2++) o2.push(n2(r3, t4), n2(r3, t4 + 2)), t4 += 4; return o2; }, e2.GSUB.readChainSubClassSet = function(r3, t4) { var a7 = e2._bin, n2 = t4, o2 = [], s2 = a7.readUshort(r3, t4); t4 += 2; for (var i4 = 0; i4 < s2; i4++) { var h = a7.readUshort(r3, t4); t4 += 2, o2.push(e2.GSUB.readChainSubClassRule(r3, n2 + h)); } return o2; }, e2.GSUB.readChainSubClassRule = function(r3, t4) { for (var a7 = e2._bin, n2 = {}, o2 = ["backtrack", "input", "lookahead"], s2 = 0; s2 < o2.length; s2++) { var i4 = a7.readUshort(r3, t4); t4 += 2, 1 == s2 && i4--, n2[o2[s2]] = a7.readUshorts(r3, t4, i4), t4 += 2 * n2[o2[s2]].length; } i4 = a7.readUshort(r3, t4); return t4 += 2, n2.subst = a7.readUshorts(r3, t4, 2 * i4), t4 += 2 * n2.subst.length, n2; }, e2.GSUB.readLigatureSet = function(r3, t4) { var a7 = e2._bin, n2 = t4, o2 = [], s2 = a7.readUshort(r3, t4); t4 += 2; for (var i4 = 0; i4 < s2; i4++) { var h = a7.readUshort(r3, t4); t4 += 2, o2.push(e2.GSUB.readLigature(r3, n2 + h)); } return o2; }, e2.GSUB.readLigature = function(r3, t4) { var a7 = e2._bin, n2 = { chain: [] }; n2.nglyph = a7.readUshort(r3, t4), t4 += 2; var o2 = a7.readUshort(r3, t4); t4 += 2; for (var s2 = 0; s2 < o2 - 1; s2++) n2.chain.push(a7.readUshort(r3, t4)), t4 += 2; return n2; }, e2.head = {}, e2.head.parse = function(r3, t4, a7) { var n2 = e2._bin, o2 = {}; return n2.readFixed(r3, t4), t4 += 4, o2.fontRevision = n2.readFixed(r3, t4), t4 += 4, n2.readUint(r3, t4), t4 += 4, n2.readUint(r3, t4), t4 += 4, o2.flags = n2.readUshort(r3, t4), t4 += 2, o2.unitsPerEm = n2.readUshort(r3, t4), t4 += 2, o2.created = n2.readUint64(r3, t4), t4 += 8, o2.modified = n2.readUint64(r3, t4), t4 += 8, o2.xMin = n2.readShort(r3, t4), t4 += 2, o2.yMin = n2.readShort(r3, t4), t4 += 2, o2.xMax = n2.readShort(r3, t4), t4 += 2, o2.yMax = n2.readShort(r3, t4), t4 += 2, o2.macStyle = n2.readUshort(r3, t4), t4 += 2, o2.lowestRecPPEM = n2.readUshort(r3, t4), t4 += 2, o2.fontDirectionHint = n2.readShort(r3, t4), t4 += 2, o2.indexToLocFormat = n2.readShort(r3, t4), t4 += 2, o2.glyphDataFormat = n2.readShort(r3, t4), t4 += 2, o2; }, e2.hhea = {}, e2.hhea.parse = function(r3, t4, a7) { var n2 = e2._bin, o2 = {}; return n2.readFixed(r3, t4), t4 += 4, o2.ascender = n2.readShort(r3, t4), t4 += 2, o2.descender = n2.readShort(r3, t4), t4 += 2, o2.lineGap = n2.readShort(r3, t4), t4 += 2, o2.advanceWidthMax = n2.readUshort(r3, t4), t4 += 2, o2.minLeftSideBearing = n2.readShort(r3, t4), t4 += 2, o2.minRightSideBearing = n2.readShort(r3, t4), t4 += 2, o2.xMaxExtent = n2.readShort(r3, t4), t4 += 2, o2.caretSlopeRise = n2.readShort(r3, t4), t4 += 2, o2.caretSlopeRun = n2.readShort(r3, t4), t4 += 2, o2.caretOffset = n2.readShort(r3, t4), t4 += 2, t4 += 8, o2.metricDataFormat = n2.readShort(r3, t4), t4 += 2, o2.numberOfHMetrics = n2.readUshort(r3, t4), t4 += 2, o2; }, e2.hmtx = {}, e2.hmtx.parse = function(r3, t4, a7, n2) { for (var o2 = e2._bin, s2 = { aWidth: [], lsBearing: [] }, i4 = 0, h = 0, d2 = 0; d2 < n2.maxp.numGlyphs; d2++) d2 < n2.hhea.numberOfHMetrics && (i4 = o2.readUshort(r3, t4), t4 += 2, h = o2.readShort(r3, t4), t4 += 2), s2.aWidth.push(i4), s2.lsBearing.push(h); return s2; }, e2.kern = {}, e2.kern.parse = function(r3, t4, a7, n2) { var o2 = e2._bin, s2 = o2.readUshort(r3, t4); if (t4 += 2, 1 == s2) return e2.kern.parseV1(r3, t4 - 2, a7, n2); var i4 = o2.readUshort(r3, t4); t4 += 2; for (var h = { glyph1: [], rval: [] }, d2 = 0; d2 < i4; d2++) { t4 += 2; a7 = o2.readUshort(r3, t4); t4 += 2; var f2 = o2.readUshort(r3, t4); t4 += 2; var u = f2 >>> 8; if (0 != (u &= 15)) throw "unknown kern table format: " + u; t4 = e2.kern.readFormat0(r3, t4, h); } return h; }, e2.kern.parseV1 = function(r3, t4, a7, n2) { var o2 = e2._bin; o2.readFixed(r3, t4), t4 += 4; var s2 = o2.readUint(r3, t4); t4 += 4; for (var i4 = { glyph1: [], rval: [] }, h = 0; h < s2; h++) { o2.readUint(r3, t4), t4 += 4; var d2 = o2.readUshort(r3, t4); t4 += 2, o2.readUshort(r3, t4), t4 += 2; var f2 = d2 >>> 8; if (0 != (f2 &= 15)) throw "unknown kern table format: " + f2; t4 = e2.kern.readFormat0(r3, t4, i4); } return i4; }, e2.kern.readFormat0 = function(r3, t4, a7) { var n2 = e2._bin, o2 = -1, s2 = n2.readUshort(r3, t4); t4 += 2, n2.readUshort(r3, t4), t4 += 2, n2.readUshort(r3, t4), t4 += 2, n2.readUshort(r3, t4), t4 += 2; for (var i4 = 0; i4 < s2; i4++) { var h = n2.readUshort(r3, t4); t4 += 2; var d2 = n2.readUshort(r3, t4); t4 += 2; var f2 = n2.readShort(r3, t4); t4 += 2, h != o2 && (a7.glyph1.push(h), a7.rval.push({ glyph2: [], vals: [] })); var u = a7.rval[a7.rval.length - 1]; u.glyph2.push(d2), u.vals.push(f2), o2 = h; } return t4; }, e2.loca = {}, e2.loca.parse = function(r3, t4, a7, n2) { var o2 = e2._bin, s2 = [], i4 = n2.head.indexToLocFormat, h = n2.maxp.numGlyphs + 1; if (0 == i4) for (var d2 = 0; d2 < h; d2++) s2.push(o2.readUshort(r3, t4 + (d2 << 1)) << 1); if (1 == i4) for (d2 = 0; d2 < h; d2++) s2.push(o2.readUint(r3, t4 + (d2 << 2))); return s2; }, e2.maxp = {}, e2.maxp.parse = function(r3, t4, a7) { var n2 = e2._bin, o2 = {}, s2 = n2.readUint(r3, t4); return t4 += 4, o2.numGlyphs = n2.readUshort(r3, t4), t4 += 2, 65536 == s2 && (o2.maxPoints = n2.readUshort(r3, t4), t4 += 2, o2.maxContours = n2.readUshort(r3, t4), t4 += 2, o2.maxCompositePoints = n2.readUshort(r3, t4), t4 += 2, o2.maxCompositeContours = n2.readUshort(r3, t4), t4 += 2, o2.maxZones = n2.readUshort(r3, t4), t4 += 2, o2.maxTwilightPoints = n2.readUshort(r3, t4), t4 += 2, o2.maxStorage = n2.readUshort(r3, t4), t4 += 2, o2.maxFunctionDefs = n2.readUshort(r3, t4), t4 += 2, o2.maxInstructionDefs = n2.readUshort(r3, t4), t4 += 2, o2.maxStackElements = n2.readUshort(r3, t4), t4 += 2, o2.maxSizeOfInstructions = n2.readUshort(r3, t4), t4 += 2, o2.maxComponentElements = n2.readUshort(r3, t4), t4 += 2, o2.maxComponentDepth = n2.readUshort(r3, t4), t4 += 2), o2; }, e2.name = {}, e2.name.parse = function(r3, t4, a7) { var n2 = e2._bin, o2 = {}; n2.readUshort(r3, t4), t4 += 2; var s2 = n2.readUshort(r3, t4); t4 += 2, n2.readUshort(r3, t4); for (var i4, h = ["copyright", "fontFamily", "fontSubfamily", "ID", "fullName", "version", "postScriptName", "trademark", "manufacturer", "designer", "description", "urlVendor", "urlDesigner", "licence", "licenceURL", "---", "typoFamilyName", "typoSubfamilyName", "compatibleFull", "sampleText", "postScriptCID", "wwsFamilyName", "wwsSubfamilyName", "lightPalette", "darkPalette"], d2 = t4 += 2, f2 = 0; f2 < s2; f2++) { var u = n2.readUshort(r3, t4); t4 += 2; var l2 = n2.readUshort(r3, t4); t4 += 2; var v5 = n2.readUshort(r3, t4); t4 += 2; var c2 = n2.readUshort(r3, t4); t4 += 2; var p2 = n2.readUshort(r3, t4); t4 += 2; var U = n2.readUshort(r3, t4); t4 += 2; var g, S = h[c2], m = d2 + 12 * s2 + U; if (0 == u) g = n2.readUnicode(r3, m, p2 / 2); else if (3 == u && 0 == l2) g = n2.readUnicode(r3, m, p2 / 2); else if (0 == l2) g = n2.readASCII(r3, m, p2); else if (1 == l2) g = n2.readUnicode(r3, m, p2 / 2); else if (3 == l2) g = n2.readUnicode(r3, m, p2 / 2); else { if (1 != u) throw "unknown encoding " + l2 + ", platformID: " + u; g = n2.readASCII(r3, m, p2), console.debug("reading unknown MAC encoding " + l2 + " as ASCII"); } var b5 = "p" + u + "," + v5.toString(16); null == o2[b5] && (o2[b5] = {}), o2[b5][void 0 !== S ? S : c2] = g, o2[b5]._lang = v5; } for (var y in o2) if (null != o2[y].postScriptName && 1033 == o2[y]._lang) return o2[y]; for (var y in o2) if (null != o2[y].postScriptName && 0 == o2[y]._lang) return o2[y]; for (var y in o2) if (null != o2[y].postScriptName && 3084 == o2[y]._lang) return o2[y]; for (var y in o2) if (null != o2[y].postScriptName) return o2[y]; for (var y in o2) { i4 = y; break; } return console.debug("returning name table with languageID " + o2[i4]._lang), o2[i4]; }, e2["OS/2"] = {}, e2["OS/2"].parse = function(r3, t4, a7) { var n2 = e2._bin.readUshort(r3, t4); t4 += 2; var o2 = {}; if (0 == n2) e2["OS/2"].version0(r3, t4, o2); else if (1 == n2) e2["OS/2"].version1(r3, t4, o2); else if (2 == n2 || 3 == n2 || 4 == n2) e2["OS/2"].version2(r3, t4, o2); else { if (5 != n2) throw "unknown OS/2 table version: " + n2; e2["OS/2"].version5(r3, t4, o2); } return o2; }, e2["OS/2"].version0 = function(r3, t4, a7) { var n2 = e2._bin; return a7.xAvgCharWidth = n2.readShort(r3, t4), t4 += 2, a7.usWeightClass = n2.readUshort(r3, t4), t4 += 2, a7.usWidthClass = n2.readUshort(r3, t4), t4 += 2, a7.fsType = n2.readUshort(r3, t4), t4 += 2, a7.ySubscriptXSize = n2.readShort(r3, t4), t4 += 2, a7.ySubscriptYSize = n2.readShort(r3, t4), t4 += 2, a7.ySubscriptXOffset = n2.readShort(r3, t4), t4 += 2, a7.ySubscriptYOffset = n2.readShort(r3, t4), t4 += 2, a7.ySuperscriptXSize = n2.readShort(r3, t4), t4 += 2, a7.ySuperscriptYSize = n2.readShort(r3, t4), t4 += 2, a7.ySuperscriptXOffset = n2.readShort(r3, t4), t4 += 2, a7.ySuperscriptYOffset = n2.readShort(r3, t4), t4 += 2, a7.yStrikeoutSize = n2.readShort(r3, t4), t4 += 2, a7.yStrikeoutPosition = n2.readShort(r3, t4), t4 += 2, a7.sFamilyClass = n2.readShort(r3, t4), t4 += 2, a7.panose = n2.readBytes(r3, t4, 10), t4 += 10, a7.ulUnicodeRange1 = n2.readUint(r3, t4), t4 += 4, a7.ulUnicodeRange2 = n2.readUint(r3, t4), t4 += 4, a7.ulUnicodeRange3 = n2.readUint(r3, t4), t4 += 4, a7.ulUnicodeRange4 = n2.readUint(r3, t4), t4 += 4, a7.achVendID = [n2.readInt8(r3, t4), n2.readInt8(r3, t4 + 1), n2.readInt8(r3, t4 + 2), n2.readInt8(r3, t4 + 3)], t4 += 4, a7.fsSelection = n2.readUshort(r3, t4), t4 += 2, a7.usFirstCharIndex = n2.readUshort(r3, t4), t4 += 2, a7.usLastCharIndex = n2.readUshort(r3, t4), t4 += 2, a7.sTypoAscender = n2.readShort(r3, t4), t4 += 2, a7.sTypoDescender = n2.readShort(r3, t4), t4 += 2, a7.sTypoLineGap = n2.readShort(r3, t4), t4 += 2, a7.usWinAscent = n2.readUshort(r3, t4), t4 += 2, a7.usWinDescent = n2.readUshort(r3, t4), t4 += 2; }, e2["OS/2"].version1 = function(r3, t4, a7) { var n2 = e2._bin; return t4 = e2["OS/2"].version0(r3, t4, a7), a7.ulCodePageRange1 = n2.readUint(r3, t4), t4 += 4, a7.ulCodePageRange2 = n2.readUint(r3, t4), t4 += 4; }, e2["OS/2"].version2 = function(r3, t4, a7) { var n2 = e2._bin; return t4 = e2["OS/2"].version1(r3, t4, a7), a7.sxHeight = n2.readShort(r3, t4), t4 += 2, a7.sCapHeight = n2.readShort(r3, t4), t4 += 2, a7.usDefault = n2.readUshort(r3, t4), t4 += 2, a7.usBreak = n2.readUshort(r3, t4), t4 += 2, a7.usMaxContext = n2.readUshort(r3, t4), t4 += 2; }, e2["OS/2"].version5 = function(r3, t4, a7) { var n2 = e2._bin; return t4 = e2["OS/2"].version2(r3, t4, a7), a7.usLowerOpticalPointSize = n2.readUshort(r3, t4), t4 += 2, a7.usUpperOpticalPointSize = n2.readUshort(r3, t4), t4 += 2; }, e2.post = {}, e2.post.parse = function(r3, t4, a7) { var n2 = e2._bin, o2 = {}; return o2.version = n2.readFixed(r3, t4), t4 += 4, o2.italicAngle = n2.readFixed(r3, t4), t4 += 4, o2.underlinePosition = n2.readShort(r3, t4), t4 += 2, o2.underlineThickness = n2.readShort(r3, t4), t4 += 2, o2; }, null == e2 && (e2 = {}), null == e2.U && (e2.U = {}), e2.U.codeToGlyph = function(r3, e3) { var t4 = r3.cmap, a7 = -1; if (null != t4.p0e4 ? a7 = t4.p0e4 : null != t4.p3e1 ? a7 = t4.p3e1 : null != t4.p1e0 ? a7 = t4.p1e0 : null != t4.p0e3 && (a7 = t4.p0e3), -1 == a7) throw "no familiar platform and encoding!"; var n2 = t4.tables[a7]; if (0 == n2.format) return e3 >= n2.map.length ? 0 : n2.map[e3]; if (4 == n2.format) { for (var o2 = -1, s2 = 0; s2 < n2.endCount.length; s2++) if (e3 <= n2.endCount[s2]) { o2 = s2; break; } if (-1 == o2) return 0; if (n2.startCount[o2] > e3) return 0; return 65535 & (0 != n2.idRangeOffset[o2] ? n2.glyphIdArray[e3 - n2.startCount[o2] + (n2.idRangeOffset[o2] >> 1) - (n2.idRangeOffset.length - o2)] : e3 + n2.idDelta[o2]); } if (12 == n2.format) { if (e3 > n2.groups[n2.groups.length - 1][1]) return 0; for (s2 = 0; s2 < n2.groups.length; s2++) { var i4 = n2.groups[s2]; if (i4[0] <= e3 && e3 <= i4[1]) return i4[2] + (e3 - i4[0]); } return 0; } throw "unknown cmap table format " + n2.format; }, e2.U.glyphToPath = function(r3, t4) { var a7 = { cmds: [], crds: [] }; if (r3.SVG && r3.SVG.entries[t4]) { var n2 = r3.SVG.entries[t4]; return null == n2 ? a7 : ("string" == typeof n2 && (n2 = e2.SVG.toPath(n2), r3.SVG.entries[t4] = n2), n2); } if (r3.CFF) { var o2 = { x: 0, y: 0, stack: [], nStems: 0, haveWidth: false, width: r3.CFF.Private ? r3.CFF.Private.defaultWidthX : 0, open: false }, s2 = r3.CFF, i4 = r3.CFF.Private; if (s2.ROS) { for (var h = 0; s2.FDSelect[h + 2] <= t4; ) h += 2; i4 = s2.FDArray[s2.FDSelect[h + 1]].Private; } e2.U._drawCFF(r3.CFF.CharStrings[t4], o2, s2, i4, a7); } else r3.glyf && e2.U._drawGlyf(t4, r3, a7); return a7; }, e2.U._drawGlyf = function(r3, t4, a7) { var n2 = t4.glyf[r3]; null == n2 && (n2 = t4.glyf[r3] = e2.glyf._parseGlyf(t4, r3)), null != n2 && (n2.noc > -1 ? e2.U._simpleGlyph(n2, a7) : e2.U._compoGlyph(n2, t4, a7)); }, e2.U._simpleGlyph = function(r3, t4) { for (var a7 = 0; a7 < r3.noc; a7++) { for (var n2 = 0 == a7 ? 0 : r3.endPts[a7 - 1] + 1, o2 = r3.endPts[a7], s2 = n2; s2 <= o2; s2++) { var i4 = s2 == n2 ? o2 : s2 - 1, h = s2 == o2 ? n2 : s2 + 1, d2 = 1 & r3.flags[s2], f2 = 1 & r3.flags[i4], u = 1 & r3.flags[h], l2 = r3.xs[s2], v5 = r3.ys[s2]; if (s2 == n2) if (d2) { if (!f2) { e2.U.P.moveTo(t4, l2, v5); continue; } e2.U.P.moveTo(t4, r3.xs[i4], r3.ys[i4]); } else f2 ? e2.U.P.moveTo(t4, r3.xs[i4], r3.ys[i4]) : e2.U.P.moveTo(t4, (r3.xs[i4] + l2) / 2, (r3.ys[i4] + v5) / 2); d2 ? f2 && e2.U.P.lineTo(t4, l2, v5) : u ? e2.U.P.qcurveTo(t4, l2, v5, r3.xs[h], r3.ys[h]) : e2.U.P.qcurveTo(t4, l2, v5, (l2 + r3.xs[h]) / 2, (v5 + r3.ys[h]) / 2); } e2.U.P.closePath(t4); } }, e2.U._compoGlyph = function(r3, t4, a7) { for (var n2 = 0; n2 < r3.parts.length; n2++) { var o2 = { cmds: [], crds: [] }, s2 = r3.parts[n2]; e2.U._drawGlyf(s2.glyphIndex, t4, o2); for (var i4 = s2.m, h = 0; h < o2.crds.length; h += 2) { var d2 = o2.crds[h], f2 = o2.crds[h + 1]; a7.crds.push(d2 * i4.a + f2 * i4.b + i4.tx), a7.crds.push(d2 * i4.c + f2 * i4.d + i4.ty); } for (h = 0; h < o2.cmds.length; h++) a7.cmds.push(o2.cmds[h]); } }, e2.U._getGlyphClass = function(r3, t4) { var a7 = e2._lctf.getInterval(t4, r3); return -1 == a7 ? 0 : t4[a7 + 2]; }, e2.U._applySubs = function(r3, t4, a7, n2) { for (var o2 = r3.length - t4 - 1, s2 = 0; s2 < a7.tabs.length; s2++) if (null != a7.tabs[s2]) { var i4, h = a7.tabs[s2]; if (!h.coverage || -1 != (i4 = e2._lctf.coverageIndex(h.coverage, r3[t4]))) { if (1 == a7.ltype) r3[t4], 1 == h.fmt ? r3[t4] = r3[t4] + h.delta : r3[t4] = h.newg[i4]; else if (4 == a7.ltype) for (var d2 = h.vals[i4], f2 = 0; f2 < d2.length; f2++) { var u = d2[f2], l2 = u.chain.length; if (!(l2 > o2)) { for (var v5 = true, c2 = 0, p2 = 0; p2 < l2; p2++) { for (; -1 == r3[t4 + c2 + (1 + p2)]; ) c2++; u.chain[p2] != r3[t4 + c2 + (1 + p2)] && (v5 = false); } if (v5) { r3[t4] = u.nglyph; for (p2 = 0; p2 < l2 + c2; p2++) r3[t4 + p2 + 1] = -1; break; } } } else if (5 == a7.ltype && 2 == h.fmt) for (var U = e2._lctf.getInterval(h.cDef, r3[t4]), g = h.cDef[U + 2], S = h.scset[g], m = 0; m < S.length; m++) { var b5 = S[m], y = b5.input; if (!(y.length > o2)) { for (v5 = true, p2 = 0; p2 < y.length; p2++) { var F = e2._lctf.getInterval(h.cDef, r3[t4 + 1 + p2]); if (-1 == U && h.cDef[F + 2] != y[p2]) { v5 = false; break; } } if (v5) { var C = b5.substLookupRecords; for (f2 = 0; f2 < C.length; f2 += 2) C[f2], C[f2 + 1]; } } } else if (6 == a7.ltype && 3 == h.fmt) { if (!e2.U._glsCovered(r3, h.backCvg, t4 - h.backCvg.length)) continue; if (!e2.U._glsCovered(r3, h.inptCvg, t4)) continue; if (!e2.U._glsCovered(r3, h.ahedCvg, t4 + h.inptCvg.length)) continue; var _ = h.lookupRec; for (m = 0; m < _.length; m += 2) { U = _[m]; var P = n2[_[m + 1]]; e2.U._applySubs(r3, t4 + U, P, n2); } } } } }, e2.U._glsCovered = function(r3, t4, a7) { for (var n2 = 0; n2 < t4.length; n2++) { if (-1 == e2._lctf.coverageIndex(t4[n2], r3[a7 + n2])) return false; } return true; }, e2.U.glyphsToPath = function(r3, t4, a7) { for (var n2 = { cmds: [], crds: [] }, o2 = 0, s2 = 0; s2 < t4.length; s2++) { var i4 = t4[s2]; if (-1 != i4) { for (var h = s2 < t4.length - 1 && -1 != t4[s2 + 1] ? t4[s2 + 1] : 0, d2 = e2.U.glyphToPath(r3, i4), f2 = 0; f2 < d2.crds.length; f2 += 2) n2.crds.push(d2.crds[f2] + o2), n2.crds.push(d2.crds[f2 + 1]); a7 && n2.cmds.push(a7); for (f2 = 0; f2 < d2.cmds.length; f2++) n2.cmds.push(d2.cmds[f2]); a7 && n2.cmds.push("X"), o2 += r3.hmtx.aWidth[i4], s2 < t4.length - 1 && (o2 += e2.U.getPairAdjustment(r3, i4, h)); } } return n2; }, e2.U.P = {}, e2.U.P.moveTo = function(r3, e3, t4) { r3.cmds.push("M"), r3.crds.push(e3, t4); }, e2.U.P.lineTo = function(r3, e3, t4) { r3.cmds.push("L"), r3.crds.push(e3, t4); }, e2.U.P.curveTo = function(r3, e3, t4, a7, n2, o2, s2) { r3.cmds.push("C"), r3.crds.push(e3, t4, a7, n2, o2, s2); }, e2.U.P.qcurveTo = function(r3, e3, t4, a7, n2) { r3.cmds.push("Q"), r3.crds.push(e3, t4, a7, n2); }, e2.U.P.closePath = function(r3) { r3.cmds.push("Z"); }, e2.U._drawCFF = function(r3, t4, a7, n2, o2) { for (var s2 = t4.stack, i4 = t4.nStems, h = t4.haveWidth, d2 = t4.width, f2 = t4.open, u = 0, l2 = t4.x, v5 = t4.y, c2 = 0, p2 = 0, U = 0, g = 0, S = 0, m = 0, b5 = 0, y = 0, F = 0, C = 0, _ = { val: 0, size: 0 }; u < r3.length; ) { e2.CFF.getCharString(r3, u, _); var P = _.val; if (u += _.size, "o1" == P || "o18" == P) s2.length % 2 != 0 && !h && (d2 = s2.shift() + n2.nominalWidthX), i4 += s2.length >> 1, s2.length = 0, h = true; else if ("o3" == P || "o23" == P) { s2.length % 2 != 0 && !h && (d2 = s2.shift() + n2.nominalWidthX), i4 += s2.length >> 1, s2.length = 0, h = true; } else if ("o4" == P) s2.length > 1 && !h && (d2 = s2.shift() + n2.nominalWidthX, h = true), f2 && e2.U.P.closePath(o2), v5 += s2.pop(), e2.U.P.moveTo(o2, l2, v5), f2 = true; else if ("o5" == P) for (; s2.length > 0; ) l2 += s2.shift(), v5 += s2.shift(), e2.U.P.lineTo(o2, l2, v5); else if ("o6" == P || "o7" == P) for (var x = s2.length, I = "o6" == P, w = 0; w < x; w++) { var k = s2.shift(); I ? l2 += k : v5 += k, I = !I, e2.U.P.lineTo(o2, l2, v5); } else if ("o8" == P || "o24" == P) { x = s2.length; for (var G = 0; G + 6 <= x; ) c2 = l2 + s2.shift(), p2 = v5 + s2.shift(), U = c2 + s2.shift(), g = p2 + s2.shift(), l2 = U + s2.shift(), v5 = g + s2.shift(), e2.U.P.curveTo(o2, c2, p2, U, g, l2, v5), G += 6; "o24" == P && (l2 += s2.shift(), v5 += s2.shift(), e2.U.P.lineTo(o2, l2, v5)); } else { if ("o11" == P) break; if ("o1234" == P || "o1235" == P || "o1236" == P || "o1237" == P) "o1234" == P && (p2 = v5, U = (c2 = l2 + s2.shift()) + s2.shift(), C = g = p2 + s2.shift(), m = g, y = v5, l2 = (b5 = (S = (F = U + s2.shift()) + s2.shift()) + s2.shift()) + s2.shift(), e2.U.P.curveTo(o2, c2, p2, U, g, F, C), e2.U.P.curveTo(o2, S, m, b5, y, l2, v5)), "o1235" == P && (c2 = l2 + s2.shift(), p2 = v5 + s2.shift(), U = c2 + s2.shift(), g = p2 + s2.shift(), F = U + s2.shift(), C = g + s2.shift(), S = F + s2.shift(), m = C + s2.shift(), b5 = S + s2.shift(), y = m + s2.shift(), l2 = b5 + s2.shift(), v5 = y + s2.shift(), s2.shift(), e2.U.P.curveTo(o2, c2, p2, U, g, F, C), e2.U.P.curveTo(o2, S, m, b5, y, l2, v5)), "o1236" == P && (c2 = l2 + s2.shift(), p2 = v5 + s2.shift(), U = c2 + s2.shift(), C = g = p2 + s2.shift(), m = g, b5 = (S = (F = U + s2.shift()) + s2.shift()) + s2.shift(), y = m + s2.shift(), l2 = b5 + s2.shift(), e2.U.P.curveTo(o2, c2, p2, U, g, F, C), e2.U.P.curveTo(o2, S, m, b5, y, l2, v5)), "o1237" == P && (c2 = l2 + s2.shift(), p2 = v5 + s2.shift(), U = c2 + s2.shift(), g = p2 + s2.shift(), F = U + s2.shift(), C = g + s2.shift(), S = F + s2.shift(), m = C + s2.shift(), b5 = S + s2.shift(), y = m + s2.shift(), Math.abs(b5 - l2) > Math.abs(y - v5) ? l2 = b5 + s2.shift() : v5 = y + s2.shift(), e2.U.P.curveTo(o2, c2, p2, U, g, F, C), e2.U.P.curveTo(o2, S, m, b5, y, l2, v5)); else if ("o14" == P) { if (s2.length > 0 && !h && (d2 = s2.shift() + a7.nominalWidthX, h = true), 4 == s2.length) { var O = s2.shift(), T = s2.shift(), D = s2.shift(), B = s2.shift(), A = e2.CFF.glyphBySE(a7, D), R2 = e2.CFF.glyphBySE(a7, B); e2.U._drawCFF(a7.CharStrings[A], t4, a7, n2, o2), t4.x = O, t4.y = T, e2.U._drawCFF(a7.CharStrings[R2], t4, a7, n2, o2); } f2 && (e2.U.P.closePath(o2), f2 = false); } else if ("o19" == P || "o20" == P) { s2.length % 2 != 0 && !h && (d2 = s2.shift() + n2.nominalWidthX), i4 += s2.length >> 1, s2.length = 0, h = true, u += i4 + 7 >> 3; } else if ("o21" == P) s2.length > 2 && !h && (d2 = s2.shift() + n2.nominalWidthX, h = true), v5 += s2.pop(), l2 += s2.pop(), f2 && e2.U.P.closePath(o2), e2.U.P.moveTo(o2, l2, v5), f2 = true; else if ("o22" == P) s2.length > 1 && !h && (d2 = s2.shift() + n2.nominalWidthX, h = true), l2 += s2.pop(), f2 && e2.U.P.closePath(o2), e2.U.P.moveTo(o2, l2, v5), f2 = true; else if ("o25" == P) { for (; s2.length > 6; ) l2 += s2.shift(), v5 += s2.shift(), e2.U.P.lineTo(o2, l2, v5); c2 = l2 + s2.shift(), p2 = v5 + s2.shift(), U = c2 + s2.shift(), g = p2 + s2.shift(), l2 = U + s2.shift(), v5 = g + s2.shift(), e2.U.P.curveTo(o2, c2, p2, U, g, l2, v5); } else if ("o26" == P) for (s2.length % 2 && (l2 += s2.shift()); s2.length > 0; ) c2 = l2, p2 = v5 + s2.shift(), l2 = U = c2 + s2.shift(), v5 = (g = p2 + s2.shift()) + s2.shift(), e2.U.P.curveTo(o2, c2, p2, U, g, l2, v5); else if ("o27" == P) for (s2.length % 2 && (v5 += s2.shift()); s2.length > 0; ) p2 = v5, U = (c2 = l2 + s2.shift()) + s2.shift(), g = p2 + s2.shift(), l2 = U + s2.shift(), v5 = g, e2.U.P.curveTo(o2, c2, p2, U, g, l2, v5); else if ("o10" == P || "o29" == P) { var L = "o10" == P ? n2 : a7; if (0 == s2.length) console.debug("error: empty stack"); else { var W = s2.pop(), M = L.Subrs[W + L.Bias]; t4.x = l2, t4.y = v5, t4.nStems = i4, t4.haveWidth = h, t4.width = d2, t4.open = f2, e2.U._drawCFF(M, t4, a7, n2, o2), l2 = t4.x, v5 = t4.y, i4 = t4.nStems, h = t4.haveWidth, d2 = t4.width, f2 = t4.open; } } else if ("o30" == P || "o31" == P) { var V2 = s2.length, E = (G = 0, "o31" == P); for (G += V2 - (x = -3 & V2); G < x; ) E ? (p2 = v5, U = (c2 = l2 + s2.shift()) + s2.shift(), v5 = (g = p2 + s2.shift()) + s2.shift(), x - G == 5 ? (l2 = U + s2.shift(), G++) : l2 = U, E = false) : (c2 = l2, p2 = v5 + s2.shift(), U = c2 + s2.shift(), g = p2 + s2.shift(), l2 = U + s2.shift(), x - G == 5 ? (v5 = g + s2.shift(), G++) : v5 = g, E = true), e2.U.P.curveTo(o2, c2, p2, U, g, l2, v5), G += 4; } else { if ("o" == (P + "").charAt(0)) throw console.debug("Unknown operation: " + P, r3), P; s2.push(P); } } } t4.x = l2, t4.y = v5, t4.nStems = i4, t4.haveWidth = h, t4.width = d2, t4.open = f2; }; var t3 = e2, a6 = { Typr: t3 }; return r2.Typr = t3, r2.default = a6, Object.defineProperty(r2, "__esModule", { value: true }), r2; })({}).Typr; } function woff2otfFactory() { return (function(r2) { var e2 = Uint8Array, n2 = Uint16Array, t3 = Uint32Array, a6 = new e2([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]), i4 = new e2([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]), o2 = new e2([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]), f2 = function(r3, e3) { for (var a7 = new n2(31), i5 = 0; i5 < 31; ++i5) a7[i5] = e3 += 1 << r3[i5 - 1]; var o3 = new t3(a7[30]); for (i5 = 1; i5 < 30; ++i5) for (var f3 = a7[i5]; f3 < a7[i5 + 1]; ++f3) o3[f3] = f3 - a7[i5] << 5 | i5; return [a7, o3]; }, u = f2(a6, 2), v5 = u[0], s2 = u[1]; v5[28] = 258, s2[258] = 28; for (var l2 = f2(i4, 0)[0], c2 = new n2(32768), g = 0; g < 32768; ++g) { var h = (43690 & g) >>> 1 | (21845 & g) << 1; h = (61680 & (h = (52428 & h) >>> 2 | (13107 & h) << 2)) >>> 4 | (3855 & h) << 4, c2[g] = ((65280 & h) >>> 8 | (255 & h) << 8) >>> 1; } var w = function(r3, e3, t4) { for (var a7 = r3.length, i5 = 0, o3 = new n2(e3); i5 < a7; ++i5) ++o3[r3[i5] - 1]; var f3, u2 = new n2(e3); for (i5 = 0; i5 < e3; ++i5) u2[i5] = u2[i5 - 1] + o3[i5 - 1] << 1; if (t4) { f3 = new n2(1 << e3); var v6 = 15 - e3; for (i5 = 0; i5 < a7; ++i5) if (r3[i5]) for (var s3 = i5 << 4 | r3[i5], l3 = e3 - r3[i5], g2 = u2[r3[i5] - 1]++ << l3, h2 = g2 | (1 << l3) - 1; g2 <= h2; ++g2) f3[c2[g2] >>> v6] = s3; } else for (f3 = new n2(a7), i5 = 0; i5 < a7; ++i5) r3[i5] && (f3[i5] = c2[u2[r3[i5] - 1]++] >>> 15 - r3[i5]); return f3; }, d2 = new e2(288); for (g = 0; g < 144; ++g) d2[g] = 8; for (g = 144; g < 256; ++g) d2[g] = 9; for (g = 256; g < 280; ++g) d2[g] = 7; for (g = 280; g < 288; ++g) d2[g] = 8; var m = new e2(32); for (g = 0; g < 32; ++g) m[g] = 5; var b5 = w(d2, 9, 1), p2 = w(m, 5, 1), y = function(r3) { for (var e3 = r3[0], n3 = 1; n3 < r3.length; ++n3) r3[n3] > e3 && (e3 = r3[n3]); return e3; }, L = function(r3, e3, n3) { var t4 = e3 / 8 | 0; return (r3[t4] | r3[t4 + 1] << 8) >> (7 & e3) & n3; }, U = function(r3, e3) { var n3 = e3 / 8 | 0; return (r3[n3] | r3[n3 + 1] << 8 | r3[n3 + 2] << 16) >> (7 & e3); }, k = ["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"], T = function(r3, e3, n3) { var t4 = new Error(e3 || k[r3]); if (t4.code = r3, Error.captureStackTrace && Error.captureStackTrace(t4, T), !n3) throw t4; return t4; }, O = function(r3, f3, u2) { var s3 = r3.length; if (!s3 || u2 && !u2.l && s3 < 5) return f3 || new e2(0); var c5 = !f3 || u2, g2 = !u2 || u2.i; u2 || (u2 = {}), f3 || (f3 = new e2(3 * s3)); var h2, d3 = function(r4) { var n3 = f3.length; if (r4 > n3) { var t4 = new e2(Math.max(2 * n3, r4)); t4.set(f3), f3 = t4; } }, m2 = u2.f || 0, k2 = u2.p || 0, O2 = u2.b || 0, A2 = u2.l, x2 = u2.d, E = u2.m, D = u2.n, M = 8 * s3; do { if (!A2) { u2.f = m2 = L(r3, k2, 1); var S = L(r3, k2 + 1, 3); if (k2 += 3, !S) { var V2 = r3[(I = ((h2 = k2) / 8 | 0) + (7 & h2 && 1) + 4) - 4] | r3[I - 3] << 8, _ = I + V2; if (_ > s3) { g2 && T(0); break; } c5 && d3(O2 + V2), f3.set(r3.subarray(I, _), O2), u2.b = O2 += V2, u2.p = k2 = 8 * _; continue; } if (1 == S) A2 = b5, x2 = p2, E = 9, D = 5; else if (2 == S) { var j = L(r3, k2, 31) + 257, z = L(r3, k2 + 10, 15) + 4, C = j + L(r3, k2 + 5, 31) + 1; k2 += 14; for (var F = new e2(C), P = new e2(19), q = 0; q < z; ++q) P[o2[q]] = L(r3, k2 + 3 * q, 7); k2 += 3 * z; var B = y(P), G = (1 << B) - 1, H = w(P, B, 1); for (q = 0; q < C; ) { var I, J = H[L(r3, k2, G)]; if (k2 += 15 & J, (I = J >>> 4) < 16) F[q++] = I; else { var K = 0, N = 0; for (16 == I ? (N = 3 + L(r3, k2, 3), k2 += 2, K = F[q - 1]) : 17 == I ? (N = 3 + L(r3, k2, 7), k2 += 3) : 18 == I && (N = 11 + L(r3, k2, 127), k2 += 7); N--; ) F[q++] = K; } } var Q = F.subarray(0, j), R2 = F.subarray(j); E = y(Q), D = y(R2), A2 = w(Q, E, 1), x2 = w(R2, D, 1); } else T(1); if (k2 > M) { g2 && T(0); break; } } c5 && d3(O2 + 131072); for (var W = (1 << E) - 1, X = (1 << D) - 1, Y = k2; ; Y = k2) { var Z = (K = A2[U(r3, k2) & W]) >>> 4; if ((k2 += 15 & K) > M) { g2 && T(0); break; } if (K || T(2), Z < 256) f3[O2++] = Z; else { if (256 == Z) { Y = k2, A2 = null; break; } var $ = Z - 254; if (Z > 264) { var rr = a6[q = Z - 257]; $ = L(r3, k2, (1 << rr) - 1) + v5[q], k2 += rr; } var er = x2[U(r3, k2) & X], nr = er >>> 4; er || T(3), k2 += 15 & er; R2 = l2[nr]; if (nr > 3) { rr = i4[nr]; R2 += U(r3, k2) & (1 << rr) - 1, k2 += rr; } if (k2 > M) { g2 && T(0); break; } c5 && d3(O2 + 131072); for (var tr = O2 + $; O2 < tr; O2 += 4) f3[O2] = f3[O2 - R2], f3[O2 + 1] = f3[O2 + 1 - R2], f3[O2 + 2] = f3[O2 + 2 - R2], f3[O2 + 3] = f3[O2 + 3 - R2]; O2 = tr; } } u2.l = A2, u2.p = Y, u2.b = O2, A2 && (m2 = 1, u2.m = E, u2.d = x2, u2.n = D); } while (!m2); return O2 == f3.length ? f3 : (function(r4, a7, i5) { (null == a7 || a7 < 0) && (a7 = 0), (null == i5 || i5 > r4.length) && (i5 = r4.length); var o3 = new (r4 instanceof n2 ? n2 : r4 instanceof t3 ? t3 : e2)(i5 - a7); return o3.set(r4.subarray(a7, i5)), o3; })(f3, 0, O2); }, A = new e2(0); var x = "undefined" != typeof TextDecoder && new TextDecoder(); try { x.decode(A, { stream: true }), 1; } catch (r3) { } return r2.convert_streams = function(r3) { var e3 = new DataView(r3), n3 = 0; function t4() { var r4 = e3.getUint16(n3); return n3 += 2, r4; } function a7() { var r4 = e3.getUint32(n3); return n3 += 4, r4; } function i5(r4) { m2.setUint16(b6, r4), b6 += 2; } function o3(r4) { m2.setUint32(b6, r4), b6 += 4; } for (var f3 = { signature: a7(), flavor: a7(), length: a7(), numTables: t4(), reserved: t4(), totalSfntSize: a7(), majorVersion: t4(), minorVersion: t4(), metaOffset: a7(), metaLength: a7(), metaOrigLength: a7(), privOffset: a7(), privLength: a7() }, u2 = 0; Math.pow(2, u2) <= f3.numTables; ) u2++; u2--; for (var v6 = 16 * Math.pow(2, u2), s3 = 16 * f3.numTables - v6, l3 = 12, c5 = [], g2 = 0; g2 < f3.numTables; g2++) c5.push({ tag: a7(), offset: a7(), compLength: a7(), origLength: a7(), origChecksum: a7() }), l3 += 16; var h2, w2 = new Uint8Array(12 + 16 * c5.length + c5.reduce((function(r4, e4) { return r4 + e4.origLength + 4; }), 0)), d3 = w2.buffer, m2 = new DataView(d3), b6 = 0; return o3(f3.flavor), i5(f3.numTables), i5(v6), i5(u2), i5(s3), c5.forEach((function(r4) { o3(r4.tag), o3(r4.origChecksum), o3(l3), o3(r4.origLength), r4.outOffset = l3, (l3 += r4.origLength) % 4 != 0 && (l3 += 4 - l3 % 4); })), c5.forEach((function(e4) { var n4, t5 = r3.slice(e4.offset, e4.offset + e4.compLength); if (e4.compLength != e4.origLength) { var a8 = new Uint8Array(e4.origLength); n4 = new Uint8Array(t5, 2), O(n4, a8); } else a8 = new Uint8Array(t5); w2.set(a8, e4.outOffset); var i6 = 0; (l3 = e4.outOffset + e4.origLength) % 4 != 0 && (i6 = 4 - l3 % 4), w2.set(new Uint8Array(i6).buffer, e4.outOffset + e4.origLength), h2 = l3 + i6; })), d3.slice(0, h2); }, Object.defineProperty(r2, "__esModule", { value: true }), r2; })({}).convert_streams; } function parserFactory(Typr, woff2otf) { const cmdArgLengths = { M: 2, L: 2, Q: 4, C: 6, Z: 0 }; const joiningTypeRawData = { "C": "18g,ca,368,1kz", "D": "17k,6,2,2+4,5+c,2+6,2+1,10+1,9+f,j+11,2+1,a,2,2+1,15+2,3,j+2,6+3,2+8,2,2,2+1,w+a,4+e,3+3,2,3+2,3+5,23+w,2f+4,3,2+9,2,b,2+3,3,1k+9,6+1,3+1,2+2,2+d,30g,p+y,1,1+1g,f+x,2,sd2+1d,jf3+4,f+3,2+4,2+2,b+3,42,2,4+2,2+1,2,3,t+1,9f+w,2,el+2,2+g,d+2,2l,2+1,5,3+1,2+1,2,3,6,16wm+1v", "R": "17m+3,2,2,6+3,m,15+2,2+2,h+h,13,3+8,2,2,3+1,2,p+1,x,5+4,5,a,2,2,3,u,c+2,g+1,5,2+1,4+1,5j,6+1,2,b,2+2,f,2+1,1s+2,2,3+1,7,1ez0,2,2+1,4+4,b,4,3,b,42,2+2,4,3,2+1,2,o+3,ae,ep,x,2o+2,3+1,3,5+1,6", "L": "x9u,jff,a,fd,jv", "T": "4t,gj+33,7o+4,1+1,7c+18,2,2+1,2+1,2,21+a,2,1b+k,h,2u+6,3+5,3+1,2+3,y,2,v+q,2k+a,1n+8,a,p+3,2+8,2+2,2+4,18+2,3c+e,2+v,1k,2,5+7,5,4+6,b+1,u,1n,5+3,9,l+1,r,3+1,1m,5+1,5+1,3+2,4,v+1,4,c+1,1m,5+4,2+1,5,l+1,n+5,2,1n,3,2+3,9,8+1,c+1,v,1q,d,1f,4,1m+2,6+2,2+3,8+1,c+1,u,1n,3,7,6+1,l+1,t+1,1m+1,5+3,9,l+1,u,21,8+2,2,2j,3+6,d+7,2r,3+8,c+5,23+1,s,2,2,1k+d,2+4,2+1,6+a,2+z,a,2v+3,2+5,2+1,3+1,q+1,5+2,h+3,e,3+1,7,g,jk+2,qb+2,u+2,u+1,v+1,1t+1,2+6,9,3+a,a,1a+2,3c+1,z,3b+2,5+1,a,7+2,64+1,3,1n,2+6,2,2,3+7,7+9,3,1d+d,1,1+1,1s+3,1d,2+4,2,6,15+8,d+1,x+3,3+1,2+2,1l,2+1,4,2+2,1n+7,3+1,49+2,2+c,2+6,5,7,4+1,5j+1l,2+4,ek,3+1,r+4,1e+4,6+5,2p+c,1+3,1,1+2,1+b,2db+2,3y,2p+v,ff+3,30+1,n9x,1+2,2+9,x+1,29+1,7l,4,5,q+1,6,48+1,r+h,e,13+7,q+a,1b+2,1d,3+3,3+1,14,1w+5,3+1,3+1,d,9,1c,1g,2+2,3+1,6+1,2,17+1,9,6n,3,5,fn5,ki+f,h+f,5s,6y+2,ea,6b,46+4,1af+2,2+1,6+3,15+2,5,4m+1,fy+3,as+1,4a+a,4x,1j+e,1l+2,1e+3,3+1,1y+2,11+4,2+7,1r,d+1,1h+8,b+3,3,2o+2,3,2+1,7,4h,4+7,m+1,1m+1,4,12+6,4+4,5g+7,3+2,2,o,2d+5,2,5+1,2+1,6n+3,7+1,2+1,s+1,2e+7,3,2+1,2z,2,3+5,2,2u+2,3+3,2+4,78+8,2+1,75+1,2,5,41+3,3+1,5,x+9,15+5,3+3,9,a+5,3+2,1b+c,2+1,bb+6,2+5,2,2b+l,3+6,2+1,2+1,3f+5,4,2+1,2+6,2,21+1,4,2,9o+1,470+8,at4+4,1o+6,t5,1s+3,2a,f5l+1,2+3,43o+2,a+7,1+7,3+6,v+3,45+2,1j0+1i,5+1d,9,f,n+4,2+e,11t+6,2+g,3+6,2+1,2+4,7a+6,c6+3,15t+6,32+6,1,gzau,v+2n,3l+6n" }; const JT_LEFT = 1, JT_RIGHT = 2, JT_DUAL = 4, JT_TRANSPARENT = 8, JT_JOIN_CAUSING = 16, JT_NON_JOINING = 32; let joiningTypeMap; function getCharJoiningType(ch3) { if (!joiningTypeMap) { const m = { R: JT_RIGHT, L: JT_LEFT, D: JT_DUAL, C: JT_JOIN_CAUSING, U: JT_NON_JOINING, T: JT_TRANSPARENT }; joiningTypeMap = /* @__PURE__ */ new Map(); for (let type in joiningTypeRawData) { let lastCode = 0; joiningTypeRawData[type].split(",").forEach((range) => { let [skip, step] = range.split("+"); skip = parseInt(skip, 36); step = step ? parseInt(step, 36) : 0; joiningTypeMap.set(lastCode += skip, m[type]); for (let i4 = step; i4--; ) { joiningTypeMap.set(++lastCode, m[type]); } }); } } return joiningTypeMap.get(ch3) || JT_NON_JOINING; } const ISOL = 1, INIT = 2, FINA = 3, MEDI = 4; const formsToFeatures = [null, "isol", "init", "fina", "medi"]; function detectJoiningForms(str) { const joiningForms = new Uint8Array(str.length); let prevJoiningType = JT_NON_JOINING; let prevForm = ISOL; let prevIndex = -1; for (let i4 = 0; i4 < str.length; i4++) { const code = str.codePointAt(i4); let joiningType = getCharJoiningType(code) | 0; let form = ISOL; if (joiningType & JT_TRANSPARENT) { continue; } if (prevJoiningType & (JT_LEFT | JT_DUAL | JT_JOIN_CAUSING)) { if (joiningType & (JT_RIGHT | JT_DUAL | JT_JOIN_CAUSING)) { form = FINA; if (prevForm === ISOL || prevForm === FINA) { joiningForms[prevIndex]++; } } else if (joiningType & (JT_LEFT | JT_NON_JOINING)) { if (prevForm === INIT || prevForm === MEDI) { joiningForms[prevIndex]--; } } } else if (prevJoiningType & (JT_RIGHT | JT_NON_JOINING)) { if (prevForm === INIT || prevForm === MEDI) { joiningForms[prevIndex]--; } } prevForm = joiningForms[i4] = form; prevJoiningType = joiningType; prevIndex = i4; if (code > 65535) i4++; } return joiningForms; } function stringToGlyphs(font, str) { const glyphIds = []; for (let i4 = 0; i4 < str.length; i4++) { const cc = str.codePointAt(i4); if (cc > 65535) i4++; glyphIds.push(Typr.U.codeToGlyph(font, cc)); } const gsub = font["GSUB"]; if (gsub) { const { lookupList, featureList } = gsub; let joiningForms; const supportedFeatures = /^(rlig|liga|mset|isol|init|fina|medi|half|pres|blws|ccmp)$/; const usedLookups = []; featureList.forEach((feature) => { if (supportedFeatures.test(feature.tag)) { for (let ti = 0; ti < feature.tab.length; ti++) { if (usedLookups[feature.tab[ti]]) continue; usedLookups[feature.tab[ti]] = true; const tab = lookupList[feature.tab[ti]]; const isJoiningFeature = /^(isol|init|fina|medi)$/.test(feature.tag); if (isJoiningFeature && !joiningForms) { joiningForms = detectJoiningForms(str); } for (let ci = 0; ci < glyphIds.length; ci++) { if (!joiningForms || !isJoiningFeature || formsToFeatures[joiningForms[ci]] === feature.tag) { Typr.U._applySubs(glyphIds, ci, tab, lookupList); } } } } }); } return glyphIds; } function calcGlyphPositions(font, glyphIds) { const positions = new Int16Array(glyphIds.length * 3); let glyphIndex = 0; for (; glyphIndex < glyphIds.length; glyphIndex++) { const glyphId = glyphIds[glyphIndex]; if (glyphId === -1) continue; positions[glyphIndex * 3 + 2] = font.hmtx.aWidth[glyphId]; const gpos = font.GPOS; if (gpos) { const llist = gpos.lookupList; for (let i4 = 0; i4 < llist.length; i4++) { const lookup = llist[i4]; for (let j = 0; j < lookup.tabs.length; j++) { const tab = lookup.tabs[j]; if (lookup.ltype === 1) { const ind = Typr._lctf.coverageIndex(tab.coverage, glyphId); if (ind !== -1 && tab.pos) { applyValueRecord(tab.pos, glyphIndex); break; } } else if (lookup.ltype === 2) { let adj = null; let prevGlyphIndex = getPrevGlyphIndex(); if (prevGlyphIndex !== -1) { const coverageIndex = Typr._lctf.coverageIndex(tab.coverage, glyphIds[prevGlyphIndex]); if (coverageIndex !== -1) { if (tab.fmt === 1) { const right = tab.pairsets[coverageIndex]; for (let k = 0; k < right.length; k++) { if (right[k].gid2 === glyphId) adj = right[k]; } } else if (tab.fmt === 2) { const c1 = Typr.U._getGlyphClass(glyphIds[prevGlyphIndex], tab.classDef1); const c2 = Typr.U._getGlyphClass(glyphId, tab.classDef2); adj = tab.matrix[c1][c2]; } if (adj) { if (adj.val1) applyValueRecord(adj.val1, prevGlyphIndex); if (adj.val2) applyValueRecord(adj.val2, glyphIndex); break; } } } } else if (lookup.ltype === 4) { const markArrIndex = Typr._lctf.coverageIndex(tab.markCoverage, glyphId); if (markArrIndex !== -1) { const baseGlyphIndex = getPrevGlyphIndex(isBaseGlyph); const baseArrIndex = baseGlyphIndex === -1 ? -1 : Typr._lctf.coverageIndex(tab.baseCoverage, glyphIds[baseGlyphIndex]); if (baseArrIndex !== -1) { const markRecord = tab.markArray[markArrIndex]; const baseAnchor = tab.baseArray[baseArrIndex][markRecord.markClass]; positions[glyphIndex * 3] = baseAnchor.x - markRecord.x + positions[baseGlyphIndex * 3] - positions[baseGlyphIndex * 3 + 2]; positions[glyphIndex * 3 + 1] = baseAnchor.y - markRecord.y + positions[baseGlyphIndex * 3 + 1]; break; } } } else if (lookup.ltype === 6) { const mark1ArrIndex = Typr._lctf.coverageIndex(tab.mark1Coverage, glyphId); if (mark1ArrIndex !== -1) { const prevGlyphIndex = getPrevGlyphIndex(); if (prevGlyphIndex !== -1) { const prevGlyphId = glyphIds[prevGlyphIndex]; if (getGlyphClass(font, prevGlyphId) === 3) { const mark2ArrIndex = Typr._lctf.coverageIndex(tab.mark2Coverage, prevGlyphId); if (mark2ArrIndex !== -1) { const mark1Record = tab.mark1Array[mark1ArrIndex]; const mark2Anchor = tab.mark2Array[mark2ArrIndex][mark1Record.markClass]; positions[glyphIndex * 3] = mark2Anchor.x - mark1Record.x + positions[prevGlyphIndex * 3] - positions[prevGlyphIndex * 3 + 2]; positions[glyphIndex * 3 + 1] = mark2Anchor.y - mark1Record.y + positions[prevGlyphIndex * 3 + 1]; break; } } } } } } } } else if (font.kern && !font.cff) { const prevGlyphIndex = getPrevGlyphIndex(); if (prevGlyphIndex !== -1) { const ind1 = font.kern.glyph1.indexOf(glyphIds[prevGlyphIndex]); if (ind1 !== -1) { const ind2 = font.kern.rval[ind1].glyph2.indexOf(glyphId); if (ind2 !== -1) { positions[prevGlyphIndex * 3 + 2] += font.kern.rval[ind1].vals[ind2]; } } } } } return positions; function getPrevGlyphIndex(filter) { for (let i4 = glyphIndex - 1; i4 >= 0; i4--) { if (glyphIds[i4] !== -1 && (!filter || filter(glyphIds[i4]))) { return i4; } } return -1; } function isBaseGlyph(glyphId) { return getGlyphClass(font, glyphId) === 1; } function applyValueRecord(source, gi) { for (let i4 = 0; i4 < 3; i4++) { positions[gi * 3 + i4] += source[i4] || 0; } } } function getGlyphClass(font, glyphId) { const classDef = font.GDEF && font.GDEF.glyphClassDef; return classDef ? Typr.U._getGlyphClass(glyphId, classDef) : 0; } function firstNum(...args) { for (let i4 = 0; i4 < args.length; i4++) { if (typeof args[i4] === "number") { return args[i4]; } } } function wrapFontObj(typrFont) { const glyphMap = /* @__PURE__ */ Object.create(null); const os2 = typrFont["OS/2"]; const hhea = typrFont.hhea; const unitsPerEm = typrFont.head.unitsPerEm; const ascender = firstNum(os2 && os2.sTypoAscender, hhea && hhea.ascender, unitsPerEm); const fontObj = { unitsPerEm, ascender, descender: firstNum(os2 && os2.sTypoDescender, hhea && hhea.descender, 0), capHeight: firstNum(os2 && os2.sCapHeight, ascender), xHeight: firstNum(os2 && os2.sxHeight, ascender), lineGap: firstNum(os2 && os2.sTypoLineGap, hhea && hhea.lineGap), supportsCodePoint(code) { return Typr.U.codeToGlyph(typrFont, code) > 0; }, forEachGlyph(text, fontSize, letterSpacing, callback) { let penX = 0; const fontScale = 1 / fontObj.unitsPerEm * fontSize; const glyphIds = stringToGlyphs(typrFont, text); let charIndex = 0; const positions = calcGlyphPositions(typrFont, glyphIds); glyphIds.forEach((glyphId, i4) => { if (glyphId !== -1) { let glyphObj = glyphMap[glyphId]; if (!glyphObj) { const { cmds, crds } = Typr.U.glyphToPath(typrFont, glyphId); let path = ""; let crdsIdx = 0; for (let i5 = 0, len = cmds.length; i5 < len; i5++) { const numArgs = cmdArgLengths[cmds[i5]]; path += cmds[i5]; for (let j = 1; j <= numArgs; j++) { path += (j > 1 ? "," : "") + crds[crdsIdx++]; } } let xMin, yMin, xMax, yMax; if (crds.length) { xMin = yMin = Infinity; xMax = yMax = -Infinity; for (let i5 = 0, len = crds.length; i5 < len; i5 += 2) { let x = crds[i5]; let y = crds[i5 + 1]; if (x < xMin) xMin = x; if (y < yMin) yMin = y; if (x > xMax) xMax = x; if (y > yMax) yMax = y; } } else { xMin = xMax = yMin = yMax = 0; } glyphObj = glyphMap[glyphId] = { index: glyphId, advanceWidth: typrFont.hmtx.aWidth[glyphId], xMin, yMin, xMax, yMax, path }; } callback.call( null, glyphObj, penX + positions[i4 * 3] * fontScale, positions[i4 * 3 + 1] * fontScale, charIndex ); penX += positions[i4 * 3 + 2] * fontScale; if (letterSpacing) { penX += letterSpacing * fontSize; } } charIndex += text.codePointAt(charIndex) > 65535 ? 2 : 1; }); return penX; } }; return fontObj; } return function parse2(buffer2) { const peek = new Uint8Array(buffer2, 0, 4); const tag = Typr._bin.readASCII(peek, 0, 4); if (tag === "wOFF") { buffer2 = woff2otf(buffer2); } else if (tag === "wOF2") { throw new Error("woff2 fonts not supported"); } return wrapFontObj(Typr.parse(buffer2)[0]); }; } var workerModule = defineWorkerModule({ name: "Typr Font Parser", dependencies: [typrFactory, woff2otfFactory, parserFactory], init(typrFactory2, woff2otfFactory2, parserFactory2) { const Typr = typrFactory2(); const woff2otf = woff2otfFactory2(); return parserFactory2(Typr, woff2otf); } }); function unicodeFontResolverClientFactory() { return (function(t3) { var n2 = function() { this.buckets = /* @__PURE__ */ new Map(); }; n2.prototype.add = function(t4) { var n3 = t4 >> 5; this.buckets.set(n3, (this.buckets.get(n3) || 0) | 1 << (31 & t4)); }, n2.prototype.has = function(t4) { var n3 = this.buckets.get(t4 >> 5); return void 0 !== n3 && 0 != (n3 & 1 << (31 & t4)); }, n2.prototype.serialize = function() { var t4 = []; return this.buckets.forEach((function(n3, r3) { t4.push((+r3).toString(36) + ":" + n3.toString(36)); })), t4.join(","); }, n2.prototype.deserialize = function(t4) { var n3 = this; this.buckets.clear(), t4.split(",").forEach((function(t5) { var r3 = t5.split(":"); n3.buckets.set(parseInt(r3[0], 36), parseInt(r3[1], 36)); })); }; var r2 = Math.pow(2, 8), e2 = r2 - 1, o2 = ~e2; function a6(t4) { var n3 = (function(t5) { return t5 & o2; })(t4).toString(16), e3 = (function(t5) { return (t5 & o2) + r2 - 1; })(t4).toString(16); return "codepoint-index/plane" + (t4 >> 16) + "/" + n3 + "-" + e3 + ".json"; } function i4(t4, n3) { var r3 = t4 & e2, o3 = n3.codePointAt(r3 / 6 | 0); return 0 != ((o3 = (o3 || 48) - 48) & 1 << r3 % 6); } function u(t4, n3) { var r3; (r3 = t4, r3.replace(/U\+/gi, "").replace(/^,+|,+$/g, "").split(/,+/).map((function(t5) { return t5.split("-").map((function(t6) { return parseInt(t6.trim(), 16); })); }))).forEach((function(t5) { var r4 = t5[0], e3 = t5[1]; void 0 === e3 && (e3 = r4), n3(r4, e3); })); } function c2(t4, n3) { u(t4, (function(t5, r3) { for (var e3 = t5; e3 <= r3; e3++) n3(e3); })); } var s2 = {}, f2 = {}, l2 = /* @__PURE__ */ new WeakMap(), v5 = "https://cdn.jsdelivr.net/gh/lojjic/unicode-font-resolver@v1.0.1/packages/data"; function d2(t4) { var r3 = l2.get(t4); return r3 || (r3 = new n2(), c2(t4.ranges, (function(t5) { return r3.add(t5); })), l2.set(t4, r3)), r3; } var h, p2 = /* @__PURE__ */ new Map(); function g(t4, n3, r3) { return t4[n3] ? n3 : t4[r3] ? r3 : (function(t5) { for (var n4 in t5) return n4; })(t4); } function w(t4, n3) { var r3 = n3; if (!t4.includes(r3)) { r3 = 1 / 0; for (var e3 = 0; e3 < t4.length; e3++) Math.abs(t4[e3] - n3) < Math.abs(r3 - n3) && (r3 = t4[e3]); } return r3; } function k(t4) { return h || (h = /* @__PURE__ */ new Set(), c2("9-D,20,85,A0,1680,2000-200A,2028-202F,205F,3000", (function(t5) { h.add(t5); }))), h.has(t4); } return t3.CodePointSet = n2, t3.clearCache = function() { s2 = {}, f2 = {}; }, t3.getFontsForString = function(t4, n3) { void 0 === n3 && (n3 = {}); var r3, e3 = n3.lang; void 0 === e3 && (e3 = new RegExp("\\p{Script=Hangul}", "u").test(r3 = t4) ? "ko" : new RegExp("\\p{Script=Hiragana}|\\p{Script=Katakana}", "u").test(r3) ? "ja" : "en"); var o3 = n3.category; void 0 === o3 && (o3 = "sans-serif"); var u2 = n3.style; void 0 === u2 && (u2 = "normal"); var c5 = n3.weight; void 0 === c5 && (c5 = 400); var l3 = (n3.dataUrl || v5).replace(/\/$/g, ""), h2 = /* @__PURE__ */ new Map(), y = new Uint8Array(t4.length), b5 = {}, m = {}, A = new Array(t4.length), S = /* @__PURE__ */ new Map(), j = false; function M(t5) { var n4 = p2.get(t5); return n4 || (n4 = fetch(l3 + "/" + t5).then((function(t6) { if (!t6.ok) throw new Error(t6.statusText); return t6.json().then((function(t7) { if (!Array.isArray(t7) || 1 !== t7[0]) throw new Error("Incorrect schema version; need 1, got " + t7[0]); return t7[1]; })); })).catch((function(n5) { if (l3 !== v5) return j || (console.error('unicode-font-resolver: Failed loading from dataUrl "' + l3 + '", trying default CDN. ' + n5.message), j = true), l3 = v5, p2.delete(t5), M(t5); throw n5; })), p2.set(t5, n4)), n4; } for (var P = function(n4) { var r4 = t4.codePointAt(n4), e4 = a6(r4); A[n4] = e4, s2[e4] || S.has(e4) || S.set(e4, M(e4).then((function(t5) { s2[e4] = t5; }))), r4 > 65535 && (n4++, E = n4); }, E = 0; E < t4.length; E++) P(E); return Promise.all(S.values()).then((function() { S.clear(); for (var n4 = function(n5) { var o4 = t4.codePointAt(n5), a7 = null, u3 = s2[A[n5]], c6 = void 0; for (var l4 in u3) { var v6 = m[l4]; if (void 0 === v6 && (v6 = m[l4] = new RegExp(l4).test(e3 || "en")), v6) { for (var d3 in c6 = l4, u3[l4]) if (i4(o4, u3[l4][d3])) { a7 = d3; break; } break; } } if (!a7) { t: for (var h3 in u3) if (h3 !== c6) { for (var p3 in u3[h3]) if (i4(o4, u3[h3][p3])) { a7 = p3; break t; } } } a7 || (console.debug("No font coverage for U+" + o4.toString(16)), a7 = "latin"), A[n5] = a7, f2[a7] || S.has(a7) || S.set(a7, M("font-meta/" + a7 + ".json").then((function(t5) { f2[a7] = t5; }))), o4 > 65535 && (n5++, r4 = n5); }, r4 = 0; r4 < t4.length; r4++) n4(r4); return Promise.all(S.values()); })).then((function() { for (var n4, r4 = null, e4 = 0; e4 < t4.length; e4++) { var a7 = t4.codePointAt(e4); if (r4 && (k(a7) || d2(r4).has(a7))) y[e4] = y[e4 - 1]; else { r4 = f2[A[e4]]; var i5 = b5[r4.id]; if (!i5) { var s3 = r4.typeforms, v6 = g(s3, o3, "sans-serif"), p3 = g(s3[v6], u2, "normal"), m2 = w(null === (n4 = s3[v6]) || void 0 === n4 ? void 0 : n4[p3], c5); i5 = b5[r4.id] = l3 + "/font-files/" + r4.id + "/" + v6 + "." + p3 + "." + m2 + ".woff"; } var S2 = h2.get(i5); null == S2 && (S2 = h2.size, h2.set(i5, S2)), y[e4] = S2; } a7 > 65535 && (e4++, y[e4] = y[e4 - 1]); } return { fontUrls: Array.from(h2.keys()), chars: y }; })); }, Object.defineProperty(t3, "__esModule", { value: true }), t3; })({}); } function createFontResolver(fontParser, unicodeFontResolverClient) { const parsedFonts = /* @__PURE__ */ Object.create(null); const loadingFonts = /* @__PURE__ */ Object.create(null); function doLoadFont(url, callback) { const onError = (err) => { console.error(`Failure loading font ${url}`, err); }; try { const request = new XMLHttpRequest(); request.open("get", url, true); request.responseType = "arraybuffer"; request.onload = function() { if (request.status >= 400) { onError(new Error(request.statusText)); } else if (request.status > 0) { try { const fontObj = fontParser(request.response); fontObj.src = url; callback(fontObj); } catch (e2) { onError(e2); } } }; request.onerror = onError; request.send(); } catch (err) { onError(err); } } function loadFont(fontUrl, callback) { let font = parsedFonts[fontUrl]; if (font) { callback(font); } else if (loadingFonts[fontUrl]) { loadingFonts[fontUrl].push(callback); } else { loadingFonts[fontUrl] = [callback]; doLoadFont(fontUrl, (fontObj) => { fontObj.src = fontUrl; parsedFonts[fontUrl] = fontObj; loadingFonts[fontUrl].forEach((cb2) => cb2(fontObj)); delete loadingFonts[fontUrl]; }); } } return function(text, callback, { lang, fonts: userFonts = [], style = "normal", weight = "normal", unicodeFontsURL } = {}) { const charResolutions = new Uint8Array(text.length); const fontResolutions = []; if (!text.length) { allDone(); } const fontIndices = /* @__PURE__ */ new Map(); const fallbackRanges = []; if (style !== "italic") style = "normal"; if (typeof weight !== "number") { weight = weight === "bold" ? 700 : 400; } if (userFonts && !Array.isArray(userFonts)) { userFonts = [userFonts]; } userFonts = userFonts.slice().filter((def) => !def.lang || def.lang.test(lang)).reverse(); if (userFonts.length) { const UNKNOWN = 0; const RESOLVED = 1; const NEEDS_FALLBACK = 2; let prevCharResult = UNKNOWN; (function resolveUserFonts(startIndex = 0) { for (let i4 = startIndex, iLen = text.length; i4 < iLen; i4++) { const codePoint = text.codePointAt(i4); if (prevCharResult === RESOLVED && fontResolutions[charResolutions[i4 - 1]].supportsCodePoint(codePoint) || i4 > 0 && /\s/.test(text[i4])) { charResolutions[i4] = charResolutions[i4 - 1]; if (prevCharResult === NEEDS_FALLBACK) { fallbackRanges[fallbackRanges.length - 1][1] = i4; } } else { for (let j = charResolutions[i4], jLen = userFonts.length; j <= jLen; j++) { if (j === jLen) { const range = prevCharResult === NEEDS_FALLBACK ? fallbackRanges[fallbackRanges.length - 1] : fallbackRanges[fallbackRanges.length] = [i4, i4]; range[1] = i4; prevCharResult = NEEDS_FALLBACK; } else { charResolutions[i4] = j; const { src, unicodeRange } = userFonts[j]; if (!unicodeRange || isCodeInRanges(codePoint, unicodeRange)) { const fontObj = parsedFonts[src]; if (!fontObj) { loadFont(src, () => { resolveUserFonts(i4); }); return; } if (fontObj.supportsCodePoint(codePoint)) { let fontIndex = fontIndices.get(fontObj); if (typeof fontIndex !== "number") { fontIndex = fontResolutions.length; fontResolutions.push(fontObj); fontIndices.set(fontObj, fontIndex); } charResolutions[i4] = fontIndex; prevCharResult = RESOLVED; break; } } } } } if (codePoint > 65535 && i4 + 1 < iLen) { charResolutions[i4 + 1] = charResolutions[i4]; i4++; if (prevCharResult === NEEDS_FALLBACK) { fallbackRanges[fallbackRanges.length - 1][1] = i4; } } } resolveFallbacks(); })(); } else { fallbackRanges.push([0, text.length - 1]); resolveFallbacks(); } function resolveFallbacks() { if (fallbackRanges.length) { const fallbackString = fallbackRanges.map((range) => text.substring(range[0], range[1] + 1)).join("\n"); unicodeFontResolverClient.getFontsForString(fallbackString, { lang: lang || void 0, style, weight, dataUrl: unicodeFontsURL }).then(({ fontUrls, chars }) => { const fontIndexOffset = fontResolutions.length; let charIdx = 0; fallbackRanges.forEach((range) => { for (let i4 = 0, endIdx = range[1] - range[0]; i4 <= endIdx; i4++) { charResolutions[range[0] + i4] = chars[charIdx++] + fontIndexOffset; } charIdx++; }); let loadedCount = 0; fontUrls.forEach((url, i4) => { loadFont(url, (fontObj) => { fontResolutions[i4 + fontIndexOffset] = fontObj; if (++loadedCount === fontUrls.length) { allDone(); } }); }); }); } else { allDone(); } } function allDone() { callback({ chars: charResolutions, fonts: fontResolutions }); } function isCodeInRanges(code, ranges) { for (let k = 0; k < ranges.length; k++) { const [start, end = start] = ranges[k]; if (start <= code && code <= end) { return true; } } return false; } }; } var fontResolverWorkerModule = defineWorkerModule({ name: "FontResolver", dependencies: [ createFontResolver, workerModule, unicodeFontResolverClientFactory ], init(createFontResolver2, fontParser, unicodeFontResolverClientFactory2) { return createFontResolver2(fontParser, unicodeFontResolverClientFactory2()); } }); function createTypesetter(resolveFonts, bidi) { const INF = Infinity; const DEFAULT_IGNORABLE_CHARS = /[\u00AD\u034F\u061C\u115F-\u1160\u17B4-\u17B5\u180B-\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\u3164\uFE00-\uFE0F\uFEFF\uFFA0\uFFF0-\uFFF8]/; const lineBreakingWhiteSpace = `[^\\S\\u00A0]`; const BREAK_AFTER_CHARS = new RegExp(`${lineBreakingWhiteSpace}|[\\-\\u007C\\u00AD\\u2010\\u2012-\\u2014\\u2027\\u2056\\u2E17\\u2E40]`); function calculateFontRuns({ text, lang, fonts, style, weight, preResolvedFonts, unicodeFontsURL }, onDone) { const onResolved = ({ chars, fonts: parsedFonts }) => { let curRun, prevVal; const runs = []; for (let i4 = 0; i4 < chars.length; i4++) { if (chars[i4] !== prevVal) { prevVal = chars[i4]; runs.push(curRun = { start: i4, end: i4, fontObj: parsedFonts[chars[i4]] }); } else { curRun.end = i4; } } onDone(runs); }; if (preResolvedFonts) { onResolved(preResolvedFonts); } else { resolveFonts( text, onResolved, { lang, fonts, style, weight, unicodeFontsURL } ); } } function typeset({ text = "", font, lang, sdfGlyphSize = 64, fontSize = 400, fontWeight = 1, fontStyle = "normal", letterSpacing = 0, lineHeight = "normal", maxWidth = INF, direction: direction2, textAlign = "left", textIndent = 0, whiteSpace = "normal", overflowWrap = "normal", anchorX = 0, anchorY = 0, metricsOnly = false, unicodeFontsURL, preResolvedFonts = null, includeCaretPositions = false, chunkedBoundsSize = 8192, colorRanges = null }, callback) { const mainStart = now2(); const timings = { fontLoad: 0, typesetting: 0 }; if (text.indexOf("\r") > -1) { console.info("Typesetter: got text with \\r chars; normalizing to \\n"); text = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); } fontSize = +fontSize; letterSpacing = +letterSpacing; maxWidth = +maxWidth; lineHeight = lineHeight || "normal"; textIndent = +textIndent; calculateFontRuns({ text, lang, style: fontStyle, weight: fontWeight, fonts: typeof font === "string" ? [{ src: font }] : font, unicodeFontsURL, preResolvedFonts }, (runs) => { timings.fontLoad = now2() - mainStart; const hasMaxWidth = isFinite(maxWidth); let glyphIds = null; let glyphFontIndices = null; let glyphPositions = null; let glyphData = null; let glyphColors = null; let caretPositions = null; let visibleBounds = null; let chunkedBounds = null; let maxLineWidth = 0; let renderableGlyphCount = 0; let canWrap = whiteSpace !== "nowrap"; const metricsByFont = /* @__PURE__ */ new Map(); const typesetStart = now2(); let lineXOffset = textIndent; let prevRunEndX = 0; let currentLine = new TextLine(); const lines = [currentLine]; runs.forEach((run) => { const { fontObj } = run; const { ascender, descender, unitsPerEm, lineGap, capHeight, xHeight } = fontObj; let fontData2 = metricsByFont.get(fontObj); if (!fontData2) { const fontSizeMult2 = fontSize / unitsPerEm; const calcLineHeight = lineHeight === "normal" ? (ascender - descender + lineGap) * fontSizeMult2 : lineHeight * fontSize; const halfLeading = (calcLineHeight - (ascender - descender) * fontSizeMult2) / 2; const caretHeight = Math.min(calcLineHeight, (ascender - descender) * fontSizeMult2); const caretTop = (ascender + descender) / 2 * fontSizeMult2 + caretHeight / 2; fontData2 = { index: metricsByFont.size, src: fontObj.src, fontObj, fontSizeMult: fontSizeMult2, unitsPerEm, ascender: ascender * fontSizeMult2, descender: descender * fontSizeMult2, capHeight: capHeight * fontSizeMult2, xHeight: xHeight * fontSizeMult2, lineHeight: calcLineHeight, baseline: -halfLeading - ascender * fontSizeMult2, // baseline offset from top of line height // cap: -halfLeading - capHeight * fontSizeMult, // cap from top of line height // ex: -halfLeading - xHeight * fontSizeMult, // ex from top of line height caretTop, caretBottom: caretTop - caretHeight }; metricsByFont.set(fontObj, fontData2); } const { fontSizeMult } = fontData2; const runText = text.slice(run.start, run.end + 1); let prevGlyphX, prevGlyphObj; fontObj.forEachGlyph(runText, fontSize, letterSpacing, (glyphObj, glyphX, glyphY, charIndex) => { glyphX += prevRunEndX; charIndex += run.start; prevGlyphX = glyphX; prevGlyphObj = glyphObj; const char = text.charAt(charIndex); const glyphWidth = glyphObj.advanceWidth * fontSizeMult; const curLineCount = currentLine.count; let nextLine; if (!("isEmpty" in glyphObj)) { glyphObj.isWhitespace = !!char && new RegExp(lineBreakingWhiteSpace).test(char); glyphObj.canBreakAfter = !!char && BREAK_AFTER_CHARS.test(char); glyphObj.isEmpty = glyphObj.xMin === glyphObj.xMax || glyphObj.yMin === glyphObj.yMax || DEFAULT_IGNORABLE_CHARS.test(char); } if (!glyphObj.isWhitespace && !glyphObj.isEmpty) { renderableGlyphCount++; } if (canWrap && hasMaxWidth && !glyphObj.isWhitespace && glyphX + glyphWidth + lineXOffset > maxWidth && curLineCount) { if (currentLine.glyphAt(curLineCount - 1).glyphObj.canBreakAfter) { nextLine = new TextLine(); lineXOffset = -glyphX; } else { for (let i4 = curLineCount; i4--; ) { if (i4 === 0 && overflowWrap === "break-word") { nextLine = new TextLine(); lineXOffset = -glyphX; break; } else if (currentLine.glyphAt(i4).glyphObj.canBreakAfter) { nextLine = currentLine.splitAt(i4 + 1); const adjustX = nextLine.glyphAt(0).x; lineXOffset -= adjustX; for (let j = nextLine.count; j--; ) { nextLine.glyphAt(j).x -= adjustX; } break; } } } if (nextLine) { currentLine.isSoftWrapped = true; currentLine = nextLine; lines.push(currentLine); maxLineWidth = maxWidth; } } let fly = currentLine.glyphAt(currentLine.count); fly.glyphObj = glyphObj; fly.x = glyphX + lineXOffset; fly.y = glyphY; fly.width = glyphWidth; fly.charIndex = charIndex; fly.fontData = fontData2; if (char === "\n") { currentLine = new TextLine(); lines.push(currentLine); lineXOffset = -(glyphX + glyphWidth + letterSpacing * fontSize) + textIndent; } }); prevRunEndX = prevGlyphX + prevGlyphObj.advanceWidth * fontSizeMult + letterSpacing * fontSize; }); let totalHeight = 0; lines.forEach((line) => { let isTrailingWhitespace = true; for (let i4 = line.count; i4--; ) { const glyphInfo = line.glyphAt(i4); if (isTrailingWhitespace && !glyphInfo.glyphObj.isWhitespace) { line.width = glyphInfo.x + glyphInfo.width; if (line.width > maxLineWidth) { maxLineWidth = line.width; } isTrailingWhitespace = false; } let { lineHeight: lineHeight2, capHeight, xHeight, baseline } = glyphInfo.fontData; if (lineHeight2 > line.lineHeight) line.lineHeight = lineHeight2; const baselineDiff = baseline - line.baseline; if (baselineDiff < 0) { line.baseline += baselineDiff; line.cap += baselineDiff; line.ex += baselineDiff; } line.cap = Math.max(line.cap, line.baseline + capHeight); line.ex = Math.max(line.ex, line.baseline + xHeight); } line.baseline -= totalHeight; line.cap -= totalHeight; line.ex -= totalHeight; totalHeight += line.lineHeight; }); let anchorXOffset = 0; let anchorYOffset = 0; if (anchorX) { if (typeof anchorX === "number") { anchorXOffset = -anchorX; } else if (typeof anchorX === "string") { anchorXOffset = -maxLineWidth * (anchorX === "left" ? 0 : anchorX === "center" ? 0.5 : anchorX === "right" ? 1 : parsePercent(anchorX)); } } if (anchorY) { if (typeof anchorY === "number") { anchorYOffset = -anchorY; } else if (typeof anchorY === "string") { anchorYOffset = anchorY === "top" ? 0 : anchorY === "top-baseline" ? -lines[0].baseline : anchorY === "top-cap" ? -lines[0].cap : anchorY === "top-ex" ? -lines[0].ex : anchorY === "middle" ? totalHeight / 2 : anchorY === "bottom" ? totalHeight : anchorY === "bottom-baseline" ? -lines[lines.length - 1].baseline : parsePercent(anchorY) * totalHeight; } } if (!metricsOnly) { const bidiLevelsResult = bidi.getEmbeddingLevels(text, direction2); glyphIds = new Uint16Array(renderableGlyphCount); glyphFontIndices = new Uint8Array(renderableGlyphCount); glyphPositions = new Float32Array(renderableGlyphCount * 2); glyphData = {}; visibleBounds = [INF, INF, -INF, -INF]; chunkedBounds = []; if (includeCaretPositions) { caretPositions = new Float32Array(text.length * 4); } if (colorRanges) { glyphColors = new Uint8Array(renderableGlyphCount * 3); } let renderableGlyphIndex = 0; let prevCharIndex = -1; let colorCharIndex = -1; let chunk; let currentColor; lines.forEach((line, lineIndex) => { let { count: lineGlyphCount, width: lineWidth } = line; if (lineGlyphCount > 0) { let trailingWhitespaceCount = 0; for (let i4 = lineGlyphCount; i4-- && line.glyphAt(i4).glyphObj.isWhitespace; ) { trailingWhitespaceCount++; } let lineXOffset2 = 0; let justifyAdjust = 0; if (textAlign === "center") { lineXOffset2 = (maxLineWidth - lineWidth) / 2; } else if (textAlign === "right") { lineXOffset2 = maxLineWidth - lineWidth; } else if (textAlign === "justify" && line.isSoftWrapped) { let whitespaceCount = 0; for (let i4 = lineGlyphCount - trailingWhitespaceCount; i4--; ) { if (line.glyphAt(i4).glyphObj.isWhitespace) { whitespaceCount++; } } justifyAdjust = (maxLineWidth - lineWidth) / whitespaceCount; } if (justifyAdjust || lineXOffset2) { let justifyOffset = 0; for (let i4 = 0; i4 < lineGlyphCount; i4++) { let glyphInfo = line.glyphAt(i4); const glyphObj2 = glyphInfo.glyphObj; glyphInfo.x += lineXOffset2 + justifyOffset; if (justifyAdjust !== 0 && glyphObj2.isWhitespace && i4 < lineGlyphCount - trailingWhitespaceCount) { justifyOffset += justifyAdjust; glyphInfo.width += justifyAdjust; } } } const flips = bidi.getReorderSegments( text, bidiLevelsResult, line.glyphAt(0).charIndex, line.glyphAt(line.count - 1).charIndex ); for (let fi = 0; fi < flips.length; fi++) { const [start, end] = flips[fi]; let left = Infinity, right = -Infinity; for (let i4 = 0; i4 < lineGlyphCount; i4++) { if (line.glyphAt(i4).charIndex >= start) { let startInLine = i4, endInLine = i4; for (; endInLine < lineGlyphCount; endInLine++) { let info = line.glyphAt(endInLine); if (info.charIndex > end) { break; } if (endInLine < lineGlyphCount - trailingWhitespaceCount) { left = Math.min(left, info.x); right = Math.max(right, info.x + info.width); } } for (let j = startInLine; j < endInLine; j++) { const glyphInfo = line.glyphAt(j); glyphInfo.x = right - (glyphInfo.x + glyphInfo.width - left); } break; } } } let glyphObj; const setGlyphObj = (g) => glyphObj = g; for (let i4 = 0; i4 < lineGlyphCount; i4++) { const glyphInfo = line.glyphAt(i4); glyphObj = glyphInfo.glyphObj; const glyphId = glyphObj.index; const rtl = bidiLevelsResult.levels[glyphInfo.charIndex] & 1; if (rtl) { const mirrored = bidi.getMirroredCharacter(text[glyphInfo.charIndex]); if (mirrored) { glyphInfo.fontData.fontObj.forEachGlyph(mirrored, 0, 0, setGlyphObj); } } if (includeCaretPositions) { const { charIndex, fontData: fontData2 } = glyphInfo; const caretLeft = glyphInfo.x + anchorXOffset; const caretRight = glyphInfo.x + glyphInfo.width + anchorXOffset; caretPositions[charIndex * 4] = rtl ? caretRight : caretLeft; caretPositions[charIndex * 4 + 1] = rtl ? caretLeft : caretRight; caretPositions[charIndex * 4 + 2] = line.baseline + fontData2.caretBottom + anchorYOffset; caretPositions[charIndex * 4 + 3] = line.baseline + fontData2.caretTop + anchorYOffset; const ligCount = charIndex - prevCharIndex; if (ligCount > 1) { fillLigatureCaretPositions(caretPositions, prevCharIndex, ligCount); } prevCharIndex = charIndex; } if (colorRanges) { const { charIndex } = glyphInfo; while (charIndex > colorCharIndex) { colorCharIndex++; if (colorRanges.hasOwnProperty(colorCharIndex)) { currentColor = colorRanges[colorCharIndex]; } } } if (!glyphObj.isWhitespace && !glyphObj.isEmpty) { const idx = renderableGlyphIndex++; const { fontSizeMult, src: fontSrc, index: fontIndex } = glyphInfo.fontData; const fontGlyphData = glyphData[fontSrc] || (glyphData[fontSrc] = {}); if (!fontGlyphData[glyphId]) { fontGlyphData[glyphId] = { path: glyphObj.path, pathBounds: [glyphObj.xMin, glyphObj.yMin, glyphObj.xMax, glyphObj.yMax] }; } const glyphX = glyphInfo.x + anchorXOffset; const glyphY = glyphInfo.y + line.baseline + anchorYOffset; glyphPositions[idx * 2] = glyphX; glyphPositions[idx * 2 + 1] = glyphY; const visX0 = glyphX + glyphObj.xMin * fontSizeMult; const visY0 = glyphY + glyphObj.yMin * fontSizeMult; const visX1 = glyphX + glyphObj.xMax * fontSizeMult; const visY1 = glyphY + glyphObj.yMax * fontSizeMult; if (visX0 < visibleBounds[0]) visibleBounds[0] = visX0; if (visY0 < visibleBounds[1]) visibleBounds[1] = visY0; if (visX1 > visibleBounds[2]) visibleBounds[2] = visX1; if (visY1 > visibleBounds[3]) visibleBounds[3] = visY1; if (idx % chunkedBoundsSize === 0) { chunk = { start: idx, end: idx, rect: [INF, INF, -INF, -INF] }; chunkedBounds.push(chunk); } chunk.end++; const chunkRect = chunk.rect; if (visX0 < chunkRect[0]) chunkRect[0] = visX0; if (visY0 < chunkRect[1]) chunkRect[1] = visY0; if (visX1 > chunkRect[2]) chunkRect[2] = visX1; if (visY1 > chunkRect[3]) chunkRect[3] = visY1; glyphIds[idx] = glyphId; glyphFontIndices[idx] = fontIndex; if (colorRanges) { const start = idx * 3; glyphColors[start] = currentColor >> 16 & 255; glyphColors[start + 1] = currentColor >> 8 & 255; glyphColors[start + 2] = currentColor & 255; } } } } }); if (caretPositions) { const ligCount = text.length - prevCharIndex; if (ligCount > 1) { fillLigatureCaretPositions(caretPositions, prevCharIndex, ligCount); } } } const fontData = []; metricsByFont.forEach(({ index: index2, src, unitsPerEm, ascender, descender, lineHeight: lineHeight2, capHeight, xHeight }) => { fontData[index2] = { src, unitsPerEm, ascender, descender, lineHeight: lineHeight2, capHeight, xHeight }; }); timings.typesetting = now2() - typesetStart; callback({ glyphIds, //id for each glyph, specific to that glyph's font glyphFontIndices, //index into fontData for each glyph glyphPositions, //x,y of each glyph's origin in layout glyphData, //dict holding data about each glyph appearing in the text fontData, //data about each font used in the text caretPositions, //startX,endX,bottomY caret positions for each char // caretHeight, //height of cursor from bottom to top - todo per glyph? glyphColors, //color for each glyph, if color ranges supplied chunkedBounds, //total rects per (n=chunkedBoundsSize) consecutive glyphs fontSize, //calculated em height topBaseline: anchorYOffset + lines[0].baseline, //y coordinate of the top line's baseline blockBounds: [ //bounds for the whole block of text, including vertical padding for lineHeight anchorXOffset, anchorYOffset - totalHeight, anchorXOffset + maxLineWidth, anchorYOffset ], visibleBounds, //total bounds of visible text paths, may be larger or smaller than blockBounds timings }); }); } function measure(args, callback) { typeset({ ...args, metricsOnly: true }, (result) => { const [x0, y0, x1, y1] = result.blockBounds; callback({ width: x1 - x0, height: y1 - y0 }); }); } function parsePercent(str) { let match = str.match(/^([\d.]+)%$/); let pct = match ? parseFloat(match[1]) : NaN; return isNaN(pct) ? 0 : pct / 100; } function fillLigatureCaretPositions(caretPositions, ligStartIndex, ligCount) { const ligStartX = caretPositions[ligStartIndex * 4]; const ligEndX = caretPositions[ligStartIndex * 4 + 1]; const ligBottom = caretPositions[ligStartIndex * 4 + 2]; const ligTop = caretPositions[ligStartIndex * 4 + 3]; const guessedAdvanceX = (ligEndX - ligStartX) / ligCount; for (let i4 = 0; i4 < ligCount; i4++) { const startIndex = (ligStartIndex + i4) * 4; caretPositions[startIndex] = ligStartX + guessedAdvanceX * i4; caretPositions[startIndex + 1] = ligStartX + guessedAdvanceX * (i4 + 1); caretPositions[startIndex + 2] = ligBottom; caretPositions[startIndex + 3] = ligTop; } } function now2() { return (self.performance || Date).now(); } function TextLine() { this.data = []; } const textLineProps = ["glyphObj", "x", "y", "width", "charIndex", "fontData"]; TextLine.prototype = { width: 0, lineHeight: 0, baseline: 0, cap: 0, ex: 0, isSoftWrapped: false, get count() { return Math.ceil(this.data.length / textLineProps.length); }, glyphAt(i4) { let fly = TextLine.flyweight; fly.data = this.data; fly.index = i4; return fly; }, splitAt(i4) { let newLine = new TextLine(); newLine.data = this.data.splice(i4 * textLineProps.length); return newLine; } }; TextLine.flyweight = textLineProps.reduce((obj, prop, i4, all) => { Object.defineProperty(obj, prop, { get() { return this.data[this.index * textLineProps.length + i4]; }, set(val) { this.data[this.index * textLineProps.length + i4] = val; } }); return obj; }, { data: null, index: 0 }); return { typeset, measure }; } var now = () => (self.performance || Date).now(); var mainThreadGenerator = SDFGenerator(); var warned; function generateSDF(width, height, path, viewBox, distance3, exponent, canvas, x, y, channel, useWebGL = true) { if (!useWebGL) { return generateSDF_JS_Worker(width, height, path, viewBox, distance3, exponent, canvas, x, y, channel); } return generateSDF_GL(width, height, path, viewBox, distance3, exponent, canvas, x, y, channel).then( null, (err) => { if (!warned) { console.warn(`WebGL SDF generation failed, falling back to JS`, err); warned = true; } return generateSDF_JS_Worker(width, height, path, viewBox, distance3, exponent, canvas, x, y, channel); } ); } var queue = []; var chunkTimeBudget = 5; var timer = 0; function nextChunk() { const start = now(); while (queue.length && now() - start < chunkTimeBudget) { queue.shift()(); } timer = queue.length ? setTimeout(nextChunk, 0) : 0; } var generateSDF_GL = (...args) => { return new Promise((resolve, reject) => { queue.push(() => { const start = now(); try { mainThreadGenerator.webgl.generateIntoCanvas(...args); resolve({ timing: now() - start }); } catch (err) { reject(err); } }); if (!timer) { timer = setTimeout(nextChunk, 0); } }); }; var threadCount = 4; var idleTimeout = 2e3; var threads = {}; var callNum = 0; function generateSDF_JS_Worker(width, height, path, viewBox, distance3, exponent, canvas, x, y, channel) { const workerId = "TroikaTextSDFGenerator_JS_" + callNum++ % threadCount; let thread = threads[workerId]; if (!thread) { thread = threads[workerId] = { workerModule: defineWorkerModule({ name: workerId, workerId, dependencies: [ SDFGenerator, now ], init(_createSDFGenerator, now2) { const generate = _createSDFGenerator().javascript.generate; return function(...args) { const start = now2(); const textureData = generate(...args); return { textureData, timing: now2() - start }; }; }, getTransferables(result) { return [result.textureData.buffer]; } }), requests: 0, idleTimer: null }; } thread.requests++; clearTimeout(thread.idleTimer); return thread.workerModule(width, height, path, viewBox, distance3, exponent).then(({ textureData, timing }) => { const start = now(); const imageData = new Uint8Array(textureData.length * 4); for (let i4 = 0; i4 < textureData.length; i4++) { imageData[i4 * 4 + channel] = textureData[i4]; } mainThreadGenerator.webglUtils.renderImageData(canvas, imageData, x, y, width, height, 1 << 3 - channel); timing += now() - start; if (--thread.requests === 0) { thread.idleTimer = setTimeout(() => { terminateWorker(workerId); }, idleTimeout); } return { timing }; }); } function warmUpSDFCanvas(canvas) { if (!canvas._warm) { mainThreadGenerator.webgl.isSupported(canvas); canvas._warm = true; } } var resizeWebGLCanvasWithoutClearing = mainThreadGenerator.webglUtils.resizeWebGLCanvasWithoutClearing; var CONFIG = { defaultFontURL: null, unicodeFontsURL: null, sdfGlyphSize: 64, sdfMargin: 1 / 16, sdfExponent: 9, textureWidth: 2048, useWorker: true }; var tempColor = new Color(); var hasRequested = false; function now$1() { return (self.performance || Date).now(); } var atlases = /* @__PURE__ */ Object.create(null); function getTextRenderInfo(args, callback) { hasRequested = true; args = assign2({}, args); const totalStart = now$1(); const { defaultFontURL } = CONFIG; const fonts = []; if (defaultFontURL) { fonts.push({ label: "default", src: toAbsoluteURL(defaultFontURL) }); } if (args.font) { fonts.push({ label: "user", src: toAbsoluteURL(args.font) }); } args.font = fonts; args.text = "" + args.text; args.sdfGlyphSize = args.sdfGlyphSize || CONFIG.sdfGlyphSize; args.unicodeFontsURL = args.unicodeFontsURL || CONFIG.unicodeFontsURL; if (args.colorRanges != null) { let colors2 = {}; for (let key in args.colorRanges) { if (args.colorRanges.hasOwnProperty(key)) { let val = args.colorRanges[key]; if (typeof val !== "number") { val = tempColor.set(val).getHex(); } colors2[key] = val; } } args.colorRanges = colors2; } Object.freeze(args); const { textureWidth, sdfExponent } = CONFIG; const { sdfGlyphSize } = args; const glyphsPerRow = textureWidth / sdfGlyphSize * 4; let atlas = atlases[sdfGlyphSize]; if (!atlas) { const canvas = document.createElement("canvas"); canvas.width = textureWidth; canvas.height = sdfGlyphSize * 256 / glyphsPerRow; atlas = atlases[sdfGlyphSize] = { glyphCount: 0, sdfGlyphSize, sdfCanvas: canvas, sdfTexture: new Texture( canvas, void 0, void 0, void 0, LinearFilter, LinearFilter ), contextLost: false, glyphsByFont: /* @__PURE__ */ new Map() }; atlas.sdfTexture.generateMipmaps = false; initContextLossHandling(atlas); } const { sdfTexture, sdfCanvas } = atlas; const typeset = CONFIG.useWorker ? typesetInWorker : typesetOnMainThread; typeset(args).then((result) => { const { glyphIds, glyphFontIndices, fontData, glyphPositions, fontSize, timings } = result; const neededSDFs = []; const glyphBounds = new Float32Array(glyphIds.length * 4); let boundsIdx = 0; let positionsIdx = 0; const quadsStart = now$1(); const fontGlyphMaps = fontData.map((font) => { let map2 = atlas.glyphsByFont.get(font.src); if (!map2) { atlas.glyphsByFont.set(font.src, map2 = /* @__PURE__ */ new Map()); } return map2; }); glyphIds.forEach((glyphId, i4) => { const fontIndex = glyphFontIndices[i4]; const { src: fontSrc, unitsPerEm } = fontData[fontIndex]; let glyphInfo = fontGlyphMaps[fontIndex].get(glyphId); if (!glyphInfo) { const { path, pathBounds } = result.glyphData[fontSrc][glyphId]; const fontUnitsMargin = Math.max(pathBounds[2] - pathBounds[0], pathBounds[3] - pathBounds[1]) / sdfGlyphSize * (CONFIG.sdfMargin * sdfGlyphSize + 0.5); const atlasIndex = atlas.glyphCount++; const sdfViewBox2 = [ pathBounds[0] - fontUnitsMargin, pathBounds[1] - fontUnitsMargin, pathBounds[2] + fontUnitsMargin, pathBounds[3] + fontUnitsMargin ]; fontGlyphMaps[fontIndex].set(glyphId, glyphInfo = { path, atlasIndex, sdfViewBox: sdfViewBox2 }); neededSDFs.push(glyphInfo); } const { sdfViewBox } = glyphInfo; const posX = glyphPositions[positionsIdx++]; const posY = glyphPositions[positionsIdx++]; const fontSizeMult = fontSize / unitsPerEm; glyphBounds[boundsIdx++] = posX + sdfViewBox[0] * fontSizeMult; glyphBounds[boundsIdx++] = posY + sdfViewBox[1] * fontSizeMult; glyphBounds[boundsIdx++] = posX + sdfViewBox[2] * fontSizeMult; glyphBounds[boundsIdx++] = posY + sdfViewBox[3] * fontSizeMult; glyphIds[i4] = glyphInfo.atlasIndex; }); timings.quads = (timings.quads || 0) + (now$1() - quadsStart); const sdfStart = now$1(); timings.sdf = {}; const currentHeight = sdfCanvas.height; const neededRows = Math.ceil(atlas.glyphCount / glyphsPerRow); const neededHeight = Math.pow(2, Math.ceil(Math.log2(neededRows * sdfGlyphSize))); if (neededHeight > currentHeight) { console.info(`Increasing SDF texture size ${currentHeight}->${neededHeight}`); resizeWebGLCanvasWithoutClearing(sdfCanvas, textureWidth, neededHeight); sdfTexture.dispose(); } Promise.all(neededSDFs.map( (glyphInfo) => generateGlyphSDF(glyphInfo, atlas, args.gpuAccelerateSDF).then(({ timing }) => { timings.sdf[glyphInfo.atlasIndex] = timing; }) )).then(() => { if (neededSDFs.length && !atlas.contextLost) { safariPre15Workaround(atlas); sdfTexture.needsUpdate = true; } timings.sdfTotal = now$1() - sdfStart; timings.total = now$1() - totalStart; callback(Object.freeze({ parameters: args, sdfTexture, sdfGlyphSize, sdfExponent, glyphBounds, glyphAtlasIndices: glyphIds, glyphColors: result.glyphColors, caretPositions: result.caretPositions, chunkedBounds: result.chunkedBounds, ascender: result.ascender, descender: result.descender, lineHeight: result.lineHeight, capHeight: result.capHeight, xHeight: result.xHeight, topBaseline: result.topBaseline, blockBounds: result.blockBounds, visibleBounds: result.visibleBounds, timings: result.timings })); }); }); Promise.resolve().then(() => { if (!atlas.contextLost) { warmUpSDFCanvas(sdfCanvas); } }); } function generateGlyphSDF({ path, atlasIndex, sdfViewBox }, { sdfGlyphSize, sdfCanvas, contextLost }, useGPU) { if (contextLost) { return Promise.resolve({ timing: -1 }); } const { textureWidth, sdfExponent } = CONFIG; const maxDist = Math.max(sdfViewBox[2] - sdfViewBox[0], sdfViewBox[3] - sdfViewBox[1]); const squareIndex = Math.floor(atlasIndex / 4); const x = squareIndex % (textureWidth / sdfGlyphSize) * sdfGlyphSize; const y = Math.floor(squareIndex / (textureWidth / sdfGlyphSize)) * sdfGlyphSize; const channel = atlasIndex % 4; return generateSDF(sdfGlyphSize, sdfGlyphSize, path, sdfViewBox, maxDist, sdfExponent, sdfCanvas, x, y, channel, useGPU); } function initContextLossHandling(atlas) { const canvas = atlas.sdfCanvas; canvas.addEventListener("webglcontextlost", (event) => { console.log("Context Lost", event); event.preventDefault(); atlas.contextLost = true; }); canvas.addEventListener("webglcontextrestored", (event) => { console.log("Context Restored", event); atlas.contextLost = false; const promises = []; atlas.glyphsByFont.forEach((glyphMap) => { glyphMap.forEach((glyph) => { promises.push(generateGlyphSDF(glyph, atlas, true)); }); }); Promise.all(promises).then(() => { safariPre15Workaround(atlas); atlas.sdfTexture.needsUpdate = true; }); }); } function preloadFont({ font, characters, sdfGlyphSize }, callback) { let text = Array.isArray(characters) ? characters.join("\n") : "" + characters; getTextRenderInfo({ font, sdfGlyphSize, text }, callback); } function assign2(toObj, fromObj) { for (let key in fromObj) { if (fromObj.hasOwnProperty(key)) { toObj[key] = fromObj[key]; } } return toObj; } var linkEl; function toAbsoluteURL(path) { if (!linkEl) { linkEl = typeof document === "undefined" ? {} : document.createElement("a"); } linkEl.href = path; return linkEl.href; } function safariPre15Workaround(atlas) { if (typeof createImageBitmap !== "function") { console.info("Safari<15: applying SDF canvas workaround"); const { sdfCanvas, sdfTexture } = atlas; const { width, height } = sdfCanvas; const gl = atlas.sdfCanvas.getContext("webgl"); let pixels = sdfTexture.image.data; if (!pixels || pixels.length !== width * height * 4) { pixels = new Uint8Array(width * height * 4); sdfTexture.image = { width, height, data: pixels }; sdfTexture.flipY = false; sdfTexture.isDataTexture = true; } gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); } } var typesetterWorkerModule = defineWorkerModule({ name: "Typesetter", dependencies: [ createTypesetter, fontResolverWorkerModule, bidi_default ], init(createTypesetter2, fontResolver, bidiFactory2) { return createTypesetter2(fontResolver, bidiFactory2()); } }); var typesetInWorker = defineWorkerModule({ name: "Typesetter", dependencies: [ typesetterWorkerModule ], init(typesetter) { return function(args) { return new Promise((resolve) => { typesetter.typeset(args, resolve); }); }; }, getTransferables(result) { const transferables = []; for (let p2 in result) { if (result[p2] && result[p2].buffer) { transferables.push(result[p2].buffer); } } return transferables; } }); var typesetOnMainThread = typesetInWorker.onMainThread; var templateGeometries = {}; function getTemplateGeometry(detail) { let geom = templateGeometries[detail]; if (!geom) { geom = templateGeometries[detail] = new PlaneGeometry(1, 1, detail, detail).translate(0.5, 0.5, 0); } return geom; } var glyphBoundsAttrName = "aTroikaGlyphBounds"; var glyphIndexAttrName = "aTroikaGlyphIndex"; var glyphColorAttrName = "aTroikaGlyphColor"; var GlyphsGeometry = class extends InstancedBufferGeometry { constructor() { super(); this.detail = 1; this.curveRadius = 0; this.groups = [ { start: 0, count: Infinity, materialIndex: 0 }, { start: 0, count: Infinity, materialIndex: 1 } ]; this.boundingSphere = new Sphere(); this.boundingBox = new Box3(); } computeBoundingSphere() { } computeBoundingBox() { } set detail(detail) { if (detail !== this._detail) { this._detail = detail; if (typeof detail !== "number" || detail < 1) { detail = 1; } let tpl = getTemplateGeometry(detail); ["position", "normal", "uv"].forEach((attr) => { this.attributes[attr] = tpl.attributes[attr].clone(); }); this.setIndex(tpl.getIndex().clone()); } } get detail() { return this._detail; } set curveRadius(r2) { if (r2 !== this._curveRadius) { this._curveRadius = r2; this._updateBounds(); } } get curveRadius() { return this._curveRadius; } /** * Update the geometry for a new set of glyphs. * @param {Float32Array} glyphBounds - An array holding the planar bounds for all glyphs * to be rendered, 4 entries for each glyph: x1,x2,y1,y1 * @param {Float32Array} glyphAtlasIndices - An array holding the index of each glyph within * the SDF atlas texture. * @param {Array} blockBounds - An array holding the [minX, minY, maxX, maxY] across all glyphs * @param {Array} [chunkedBounds] - An array of objects describing bounds for each chunk of N * consecutive glyphs: `{start:N, end:N, rect:[minX, minY, maxX, maxY]}`. This can be * used with `applyClipRect` to choose an optimized `instanceCount`. * @param {Uint8Array} [glyphColors] - An array holding r,g,b values for each glyph. */ updateGlyphs(glyphBounds, glyphAtlasIndices, blockBounds, chunkedBounds, glyphColors) { this.updateAttributeData(glyphBoundsAttrName, glyphBounds, 4); this.updateAttributeData(glyphIndexAttrName, glyphAtlasIndices, 1); this.updateAttributeData(glyphColorAttrName, glyphColors, 3); this._blockBounds = blockBounds; this._chunkedBounds = chunkedBounds; this.instanceCount = glyphAtlasIndices.length; this._updateBounds(); } _updateBounds() { const bounds = this._blockBounds; if (bounds) { const { curveRadius, boundingBox: bbox } = this; if (curveRadius) { const { PI, floor, min, max: max2, sin, cos } = Math; const halfPi = PI / 2; const twoPi = PI * 2; const absR = Math.abs(curveRadius); const leftAngle = bounds[0] / absR; const rightAngle = bounds[2] / absR; const minX = floor((leftAngle + halfPi) / twoPi) !== floor((rightAngle + halfPi) / twoPi) ? -absR : min(sin(leftAngle) * absR, sin(rightAngle) * absR); const maxX = floor((leftAngle - halfPi) / twoPi) !== floor((rightAngle - halfPi) / twoPi) ? absR : max2(sin(leftAngle) * absR, sin(rightAngle) * absR); const maxZ = floor((leftAngle + PI) / twoPi) !== floor((rightAngle + PI) / twoPi) ? absR * 2 : max2(absR - cos(leftAngle) * absR, absR - cos(rightAngle) * absR); bbox.min.set(minX, bounds[1], curveRadius < 0 ? -maxZ : 0); bbox.max.set(maxX, bounds[3], curveRadius < 0 ? 0 : maxZ); } else { bbox.min.set(bounds[0], bounds[1], 0); bbox.max.set(bounds[2], bounds[3], 0); } bbox.getBoundingSphere(this.boundingSphere); } } /** * Given a clipping rect, and the chunkedBounds from the last updateGlyphs call, choose the lowest * `instanceCount` that will show all glyphs within the clipped view. This is an optimization * for long blocks of text that are clipped, to skip vertex shader evaluation for glyphs that would * be clipped anyway. * * Note that since `drawElementsInstanced[ANGLE]` only accepts an instance count and not a starting * offset, this optimization becomes less effective as the clipRect moves closer to the end of the * text block. We could fix that by switching from instancing to a full geometry with a drawRange, * but at the expense of much larger attribute buffers (see classdoc above.) * * @param {Vector4} clipRect */ applyClipRect(clipRect) { let count = this.getAttribute(glyphIndexAttrName).count; let chunks = this._chunkedBounds; if (chunks) { for (let i4 = chunks.length; i4--; ) { count = chunks[i4].end; let rect = chunks[i4].rect; if (rect[1] < clipRect.w && rect[3] > clipRect.y && rect[0] < clipRect.z && rect[2] > clipRect.x) { break; } } } this.instanceCount = count; } /** * Utility for updating instance attributes with automatic resizing */ updateAttributeData(attrName, newArray, itemSize) { const attr = this.getAttribute(attrName); if (newArray) { if (attr && attr.array.length === newArray.length) { attr.array.set(newArray); attr.needsUpdate = true; } else { this.setAttribute(attrName, new InstancedBufferAttribute(newArray, itemSize)); delete this._maxInstanceCount; this.dispose(); } } else if (attr) { this.deleteAttribute(attrName); } } }; var VERTEX_DEFS = ` uniform vec2 uTroikaSDFTextureSize; uniform float uTroikaSDFGlyphSize; uniform vec4 uTroikaTotalBounds; uniform vec4 uTroikaClipRect; uniform mat3 uTroikaOrient; uniform bool uTroikaUseGlyphColors; uniform float uTroikaEdgeOffset; uniform float uTroikaBlurRadius; uniform vec2 uTroikaPositionOffset; uniform float uTroikaCurveRadius; attribute vec4 aTroikaGlyphBounds; attribute float aTroikaGlyphIndex; attribute vec3 aTroikaGlyphColor; varying vec2 vTroikaGlyphUV; varying vec4 vTroikaTextureUVBounds; varying float vTroikaTextureChannel; varying vec3 vTroikaGlyphColor; varying vec2 vTroikaGlyphDimensions; `; var VERTEX_TRANSFORM = ` vec4 bounds = aTroikaGlyphBounds; bounds.xz += uTroikaPositionOffset.x; bounds.yw -= uTroikaPositionOffset.y; vec4 outlineBounds = vec4( bounds.xy - uTroikaEdgeOffset - uTroikaBlurRadius, bounds.zw + uTroikaEdgeOffset + uTroikaBlurRadius ); vec4 clippedBounds = vec4( clamp(outlineBounds.xy, uTroikaClipRect.xy, uTroikaClipRect.zw), clamp(outlineBounds.zw, uTroikaClipRect.xy, uTroikaClipRect.zw) ); vec2 clippedXY = (mix(clippedBounds.xy, clippedBounds.zw, position.xy) - bounds.xy) / (bounds.zw - bounds.xy); position.xy = mix(bounds.xy, bounds.zw, clippedXY); uv = (position.xy - uTroikaTotalBounds.xy) / (uTroikaTotalBounds.zw - uTroikaTotalBounds.xy); float rad = uTroikaCurveRadius; if (rad != 0.0) { float angle = position.x / rad; position.xz = vec2(sin(angle) * rad, rad - cos(angle) * rad); normal.xz = vec2(sin(angle), cos(angle)); } position = uTroikaOrient * position; normal = uTroikaOrient * normal; vTroikaGlyphUV = clippedXY.xy; vTroikaGlyphDimensions = vec2(bounds[2] - bounds[0], bounds[3] - bounds[1]); ${""} float txCols = uTroikaSDFTextureSize.x / uTroikaSDFGlyphSize; vec2 txUvPerSquare = uTroikaSDFGlyphSize / uTroikaSDFTextureSize; vec2 txStartUV = txUvPerSquare * vec2( mod(floor(aTroikaGlyphIndex / 4.0), txCols), floor(floor(aTroikaGlyphIndex / 4.0) / txCols) ); vTroikaTextureUVBounds = vec4(txStartUV, vec2(txStartUV) + txUvPerSquare); vTroikaTextureChannel = mod(aTroikaGlyphIndex, 4.0); `; var FRAGMENT_DEFS = ` uniform sampler2D uTroikaSDFTexture; uniform vec2 uTroikaSDFTextureSize; uniform float uTroikaSDFGlyphSize; uniform float uTroikaSDFExponent; uniform float uTroikaEdgeOffset; uniform float uTroikaFillOpacity; uniform float uTroikaBlurRadius; uniform vec3 uTroikaStrokeColor; uniform float uTroikaStrokeWidth; uniform float uTroikaStrokeOpacity; uniform bool uTroikaSDFDebug; varying vec2 vTroikaGlyphUV; varying vec4 vTroikaTextureUVBounds; varying float vTroikaTextureChannel; varying vec2 vTroikaGlyphDimensions; float troikaSdfValueToSignedDistance(float alpha) { // Inverse of exponential encoding in webgl-sdf-generator ${""} float maxDimension = max(vTroikaGlyphDimensions.x, vTroikaGlyphDimensions.y); float absDist = (1.0 - pow(2.0 * (alpha > 0.5 ? 1.0 - alpha : alpha), 1.0 / uTroikaSDFExponent)) * maxDimension; float signedDist = absDist * (alpha > 0.5 ? -1.0 : 1.0); return signedDist; } float troikaGlyphUvToSdfValue(vec2 glyphUV) { vec2 textureUV = mix(vTroikaTextureUVBounds.xy, vTroikaTextureUVBounds.zw, glyphUV); vec4 rgba = texture2D(uTroikaSDFTexture, textureUV); float ch = floor(vTroikaTextureChannel + 0.5); //NOTE: can't use round() in WebGL1 return ch == 0.0 ? rgba.r : ch == 1.0 ? rgba.g : ch == 2.0 ? rgba.b : rgba.a; } float troikaGlyphUvToDistance(vec2 uv) { return troikaSdfValueToSignedDistance(troikaGlyphUvToSdfValue(uv)); } float troikaGetAADist() { ${""} #if defined(GL_OES_standard_derivatives) || __VERSION__ >= 300 return length(fwidth(vTroikaGlyphUV * vTroikaGlyphDimensions)) * 0.5; #else return vTroikaGlyphDimensions.x / 64.0; #endif } float troikaGetFragDistValue() { vec2 clampedGlyphUV = clamp(vTroikaGlyphUV, 0.5 / uTroikaSDFGlyphSize, 1.0 - 0.5 / uTroikaSDFGlyphSize); float distance = troikaGlyphUvToDistance(clampedGlyphUV); // Extrapolate distance when outside bounds: distance += clampedGlyphUV == vTroikaGlyphUV ? 0.0 : length((vTroikaGlyphUV - clampedGlyphUV) * vTroikaGlyphDimensions); ${""} return distance; } float troikaGetEdgeAlpha(float distance, float distanceOffset, float aaDist) { #if defined(IS_DEPTH_MATERIAL) || defined(IS_DISTANCE_MATERIAL) float alpha = step(-distanceOffset, -distance); #else float alpha = smoothstep( distanceOffset + aaDist, distanceOffset - aaDist, distance ); #endif return alpha; } `; var FRAGMENT_TRANSFORM = ` float aaDist = troikaGetAADist(); float fragDistance = troikaGetFragDistValue(); float edgeAlpha = uTroikaSDFDebug ? troikaGlyphUvToSdfValue(vTroikaGlyphUV) : troikaGetEdgeAlpha(fragDistance, uTroikaEdgeOffset, max(aaDist, uTroikaBlurRadius)); #if !defined(IS_DEPTH_MATERIAL) && !defined(IS_DISTANCE_MATERIAL) vec4 fillRGBA = gl_FragColor; fillRGBA.a *= uTroikaFillOpacity; vec4 strokeRGBA = uTroikaStrokeWidth == 0.0 ? fillRGBA : vec4(uTroikaStrokeColor, uTroikaStrokeOpacity); if (fillRGBA.a == 0.0) fillRGBA.rgb = strokeRGBA.rgb; gl_FragColor = mix(fillRGBA, strokeRGBA, smoothstep( -uTroikaStrokeWidth - aaDist, -uTroikaStrokeWidth + aaDist, fragDistance )); gl_FragColor.a *= edgeAlpha; #endif if (edgeAlpha == 0.0) { discard; } `; function createTextDerivedMaterial(baseMaterial) { const textMaterial = createDerivedMaterial(baseMaterial, { chained: true, extensions: { derivatives: true }, uniforms: { uTroikaSDFTexture: { value: null }, uTroikaSDFTextureSize: { value: new Vector2() }, uTroikaSDFGlyphSize: { value: 0 }, uTroikaSDFExponent: { value: 0 }, uTroikaTotalBounds: { value: new Vector4(0, 0, 0, 0) }, uTroikaClipRect: { value: new Vector4(0, 0, 0, 0) }, uTroikaEdgeOffset: { value: 0 }, uTroikaFillOpacity: { value: 1 }, uTroikaPositionOffset: { value: new Vector2() }, uTroikaCurveRadius: { value: 0 }, uTroikaBlurRadius: { value: 0 }, uTroikaStrokeWidth: { value: 0 }, uTroikaStrokeColor: { value: new Color() }, uTroikaStrokeOpacity: { value: 1 }, uTroikaOrient: { value: new Matrix3() }, uTroikaUseGlyphColors: { value: true }, uTroikaSDFDebug: { value: false } }, vertexDefs: VERTEX_DEFS, vertexTransform: VERTEX_TRANSFORM, fragmentDefs: FRAGMENT_DEFS, fragmentColorTransform: FRAGMENT_TRANSFORM, customRewriter({ vertexShader: vertexShader3, fragmentShader: fragmentShader3 }) { let uDiffuseRE = /\buniform\s+vec3\s+diffuse\b/; if (uDiffuseRE.test(fragmentShader3)) { fragmentShader3 = fragmentShader3.replace(uDiffuseRE, "varying vec3 vTroikaGlyphColor").replace(/\bdiffuse\b/g, "vTroikaGlyphColor"); if (!uDiffuseRE.test(vertexShader3)) { vertexShader3 = vertexShader3.replace( voidMainRegExp, "uniform vec3 diffuse;\n$&\nvTroikaGlyphColor = uTroikaUseGlyphColors ? aTroikaGlyphColor / 255.0 : diffuse;\n" ); } } return { vertexShader: vertexShader3, fragmentShader: fragmentShader3 }; } }); textMaterial.transparent = true; textMaterial.forceSinglePass = true; Object.defineProperties(textMaterial, { isTroikaTextMaterial: { value: true }, // WebGLShadowMap reverses the side of the shadow material by default, which fails // for planes, so here we force the `shadowSide` to always match the main side. shadowSide: { get() { return this.side; }, set() { } } }); return textMaterial; } var defaultMaterial = new MeshBasicMaterial({ color: 16777215, side: DoubleSide, transparent: true }); var defaultStrokeColor = 8421504; var tempMat4 = new Matrix4(); var tempVec3a = new Vector3(); var tempVec3b = new Vector3(); var tempArray = []; var origin = new Vector3(); var defaultOrient = "+x+y"; function first(o2) { return Array.isArray(o2) ? o2[0] : o2; } var getFlatRaycastMesh = () => { const mesh = new Mesh( new PlaneGeometry(1, 1), defaultMaterial ); getFlatRaycastMesh = () => mesh; return mesh; }; var getCurvedRaycastMesh = () => { const mesh = new Mesh( new PlaneGeometry(1, 1, 32, 1), defaultMaterial ); getCurvedRaycastMesh = () => mesh; return mesh; }; var syncStartEvent = { type: "syncstart" }; var syncCompleteEvent = { type: "synccomplete" }; var SYNCABLE_PROPS = [ "font", "fontSize", "fontStyle", "fontWeight", "lang", "letterSpacing", "lineHeight", "maxWidth", "overflowWrap", "text", "direction", "textAlign", "textIndent", "whiteSpace", "anchorX", "anchorY", "colorRanges", "sdfGlyphSize" ]; var COPYABLE_PROPS = SYNCABLE_PROPS.concat( "material", "color", "depthOffset", "clipRect", "curveRadius", "orientation", "glyphGeometryDetail" ); var Text = class extends Mesh { constructor() { const geometry3 = new GlyphsGeometry(); super(geometry3, null); this.text = ""; this.anchorX = 0; this.anchorY = 0; this.curveRadius = 0; this.direction = "auto"; this.font = null; this.unicodeFontsURL = null; this.fontSize = 0.1; this.fontWeight = "normal"; this.fontStyle = "normal"; this.lang = null; this.letterSpacing = 0; this.lineHeight = "normal"; this.maxWidth = Infinity; this.overflowWrap = "normal"; this.textAlign = "left"; this.textIndent = 0; this.whiteSpace = "normal"; this.material = null; this.color = null; this.colorRanges = null; this.outlineWidth = 0; this.outlineColor = 0; this.outlineOpacity = 1; this.outlineBlur = 0; this.outlineOffsetX = 0; this.outlineOffsetY = 0; this.strokeWidth = 0; this.strokeColor = defaultStrokeColor; this.strokeOpacity = 1; this.fillOpacity = 1; this.depthOffset = 0; this.clipRect = null; this.orientation = defaultOrient; this.glyphGeometryDetail = 1; this.sdfGlyphSize = null; this.gpuAccelerateSDF = true; this.debugSDF = false; } /** * Updates the text rendering according to the current text-related configuration properties. * This is an async process, so you can pass in a callback function to be executed when it * finishes. * @param {function} [callback] */ sync(callback) { if (this._needsSync) { this._needsSync = false; if (this._isSyncing) { (this._queuedSyncs || (this._queuedSyncs = [])).push(callback); } else { this._isSyncing = true; this.dispatchEvent(syncStartEvent); getTextRenderInfo({ text: this.text, font: this.font, lang: this.lang, fontSize: this.fontSize || 0.1, fontWeight: this.fontWeight || "normal", fontStyle: this.fontStyle || "normal", letterSpacing: this.letterSpacing || 0, lineHeight: this.lineHeight || "normal", maxWidth: this.maxWidth, direction: this.direction || "auto", textAlign: this.textAlign, textIndent: this.textIndent, whiteSpace: this.whiteSpace, overflowWrap: this.overflowWrap, anchorX: this.anchorX, anchorY: this.anchorY, colorRanges: this.colorRanges, includeCaretPositions: true, //TODO parameterize sdfGlyphSize: this.sdfGlyphSize, gpuAccelerateSDF: this.gpuAccelerateSDF, unicodeFontsURL: this.unicodeFontsURL }, (textRenderInfo) => { this._isSyncing = false; this._textRenderInfo = textRenderInfo; this.geometry.updateGlyphs( textRenderInfo.glyphBounds, textRenderInfo.glyphAtlasIndices, textRenderInfo.blockBounds, textRenderInfo.chunkedBounds, textRenderInfo.glyphColors ); const queued = this._queuedSyncs; if (queued) { this._queuedSyncs = null; this._needsSync = true; this.sync(() => { queued.forEach((fn) => fn && fn()); }); } this.dispatchEvent(syncCompleteEvent); if (callback) { callback(); } }); } } } /** * Initiate a sync if needed - note it won't complete until next frame at the * earliest so if possible it's a good idea to call sync() manually as soon as * all the properties have been set. * @override */ onBeforeRender(renderer, scene, camera, geometry3, material, group) { this.sync(); if (material.isTroikaTextMaterial) { this._prepareForRender(material); } } /** * Shortcut to dispose the geometry specific to this instance. * Note: we don't also dispose the derived material here because if anything else is * sharing the same base material it will result in a pause next frame as the program * is recompiled. Instead users can dispose the base material manually, like normal, * and we'll also dispose the derived material at that time. */ dispose() { this.geometry.dispose(); } /** * @property {TroikaTextRenderInfo|null} textRenderInfo * @readonly * The current processed rendering data for this TextMesh, returned by the TextBuilder after * a `sync()` call. This will be `null` initially, and may be stale for a short period until * the asynchrous `sync()` process completes. */ get textRenderInfo() { return this._textRenderInfo || null; } /** * Create the text derived material from the base material. Can be overridden to use a custom * derived material. */ createDerivedMaterial(baseMaterial) { return createTextDerivedMaterial(baseMaterial); } // Handler for automatically wrapping the base material with our upgrades. We do the wrapping // lazily on _read_ rather than write to avoid unnecessary wrapping on transient values. get material() { let derivedMaterial = this._derivedMaterial; const baseMaterial = this._baseMaterial || this._defaultMaterial || (this._defaultMaterial = defaultMaterial.clone()); if (!derivedMaterial || !derivedMaterial.isDerivedFrom(baseMaterial)) { derivedMaterial = this._derivedMaterial = this.createDerivedMaterial(baseMaterial); baseMaterial.addEventListener("dispose", function onDispose() { baseMaterial.removeEventListener("dispose", onDispose); derivedMaterial.dispose(); }); } if (this.hasOutline()) { let outlineMaterial = derivedMaterial._outlineMtl; if (!outlineMaterial) { outlineMaterial = derivedMaterial._outlineMtl = Object.create(derivedMaterial, { id: { value: derivedMaterial.id + 0.1 } }); outlineMaterial.isTextOutlineMaterial = true; outlineMaterial.depthWrite = false; outlineMaterial.map = null; derivedMaterial.addEventListener("dispose", function onDispose() { derivedMaterial.removeEventListener("dispose", onDispose); outlineMaterial.dispose(); }); } return [ outlineMaterial, derivedMaterial ]; } else { return derivedMaterial; } } set material(baseMaterial) { if (baseMaterial && baseMaterial.isTroikaTextMaterial) { this._derivedMaterial = baseMaterial; this._baseMaterial = baseMaterial.baseMaterial; } else { this._baseMaterial = baseMaterial; } } hasOutline() { return !!(this.outlineWidth || this.outlineBlur || this.outlineOffsetX || this.outlineOffsetY); } get glyphGeometryDetail() { return this.geometry.detail; } set glyphGeometryDetail(detail) { this.geometry.detail = detail; } get curveRadius() { return this.geometry.curveRadius; } set curveRadius(r2) { this.geometry.curveRadius = r2; } // Create and update material for shadows upon request: get customDepthMaterial() { return first(this.material).getDepthMaterial(); } set customDepthMaterial(m) { } get customDistanceMaterial() { return first(this.material).getDistanceMaterial(); } set customDistanceMaterial(m) { } _prepareForRender(material) { const isOutline = material.isTextOutlineMaterial; const uniforms = material.uniforms; const textInfo = this.textRenderInfo; if (textInfo) { const { sdfTexture, blockBounds } = textInfo; uniforms.uTroikaSDFTexture.value = sdfTexture; uniforms.uTroikaSDFTextureSize.value.set(sdfTexture.image.width, sdfTexture.image.height); uniforms.uTroikaSDFGlyphSize.value = textInfo.sdfGlyphSize; uniforms.uTroikaSDFExponent.value = textInfo.sdfExponent; uniforms.uTroikaTotalBounds.value.fromArray(blockBounds); uniforms.uTroikaUseGlyphColors.value = !isOutline && !!textInfo.glyphColors; let distanceOffset = 0; let blurRadius = 0; let strokeWidth = 0; let fillOpacity; let strokeOpacity; let strokeColor; let offsetX = 0; let offsetY = 0; if (isOutline) { let { outlineWidth, outlineOffsetX, outlineOffsetY, outlineBlur, outlineOpacity } = this; distanceOffset = this._parsePercent(outlineWidth) || 0; blurRadius = Math.max(0, this._parsePercent(outlineBlur) || 0); fillOpacity = outlineOpacity; offsetX = this._parsePercent(outlineOffsetX) || 0; offsetY = this._parsePercent(outlineOffsetY) || 0; } else { strokeWidth = Math.max(0, this._parsePercent(this.strokeWidth) || 0); if (strokeWidth) { strokeColor = this.strokeColor; uniforms.uTroikaStrokeColor.value.set(strokeColor == null ? defaultStrokeColor : strokeColor); strokeOpacity = this.strokeOpacity; if (strokeOpacity == null) strokeOpacity = 1; } fillOpacity = this.fillOpacity; } uniforms.uTroikaEdgeOffset.value = distanceOffset; uniforms.uTroikaPositionOffset.value.set(offsetX, offsetY); uniforms.uTroikaBlurRadius.value = blurRadius; uniforms.uTroikaStrokeWidth.value = strokeWidth; uniforms.uTroikaStrokeOpacity.value = strokeOpacity; uniforms.uTroikaFillOpacity.value = fillOpacity == null ? 1 : fillOpacity; uniforms.uTroikaCurveRadius.value = this.curveRadius || 0; let clipRect = this.clipRect; if (clipRect && Array.isArray(clipRect) && clipRect.length === 4) { uniforms.uTroikaClipRect.value.fromArray(clipRect); } else { const pad = (this.fontSize || 0.1) * 100; uniforms.uTroikaClipRect.value.set( blockBounds[0] - pad, blockBounds[1] - pad, blockBounds[2] + pad, blockBounds[3] + pad ); } this.geometry.applyClipRect(uniforms.uTroikaClipRect.value); } uniforms.uTroikaSDFDebug.value = !!this.debugSDF; material.polygonOffset = !!this.depthOffset; material.polygonOffsetFactor = material.polygonOffsetUnits = this.depthOffset || 0; const color = isOutline ? this.outlineColor || 0 : this.color; if (color == null) { delete material.color; } else { const colorObj = material.hasOwnProperty("color") ? material.color : material.color = new Color(); if (color !== colorObj._input || typeof color === "object") { colorObj.set(colorObj._input = color); } } let orient = this.orientation || defaultOrient; if (orient !== material._orientation) { let rotMat = uniforms.uTroikaOrient.value; orient = orient.replace(/[^-+xyz]/g, ""); let match = orient !== defaultOrient && orient.match(/^([-+])([xyz])([-+])([xyz])$/); if (match) { let [, hSign, hAxis, vSign, vAxis] = match; tempVec3a.set(0, 0, 0)[hAxis] = hSign === "-" ? 1 : -1; tempVec3b.set(0, 0, 0)[vAxis] = vSign === "-" ? -1 : 1; tempMat4.lookAt(origin, tempVec3a.cross(tempVec3b), tempVec3b); rotMat.setFromMatrix4(tempMat4); } else { rotMat.identity(); } material._orientation = orient; } } _parsePercent(value) { if (typeof value === "string") { let match = value.match(/^(-?[\d.]+)%$/); let pct = match ? parseFloat(match[1]) : NaN; value = (isNaN(pct) ? 0 : pct / 100) * this.fontSize; } return value; } /** * Translate a point in local space to an x/y in the text plane. */ localPositionToTextCoords(position2, target2 = new Vector2()) { target2.copy(position2); const r2 = this.curveRadius; if (r2) { target2.x = Math.atan2(position2.x, Math.abs(r2) - Math.abs(position2.z)) * Math.abs(r2); } return target2; } /** * Translate a point in world space to an x/y in the text plane. */ worldPositionToTextCoords(position2, target2 = new Vector2()) { tempVec3a.copy(position2); return this.localPositionToTextCoords(this.worldToLocal(tempVec3a), target2); } /** * @override Custom raycasting to test against the whole text block's max rectangular bounds * TODO is there any reason to make this more granular, like within individual line or glyph rects? */ raycast(raycaster, intersects) { const { textRenderInfo, curveRadius } = this; if (textRenderInfo) { const bounds = textRenderInfo.blockBounds; const raycastMesh = curveRadius ? getCurvedRaycastMesh() : getFlatRaycastMesh(); const geom = raycastMesh.geometry; const { position: position2, uv } = geom.attributes; for (let i4 = 0; i4 < uv.count; i4++) { let x = bounds[0] + uv.getX(i4) * (bounds[2] - bounds[0]); const y = bounds[1] + uv.getY(i4) * (bounds[3] - bounds[1]); let z = 0; if (curveRadius) { z = curveRadius - Math.cos(x / curveRadius) * curveRadius; x = Math.sin(x / curveRadius) * curveRadius; } position2.setXYZ(i4, x, y, z); } geom.boundingSphere = this.geometry.boundingSphere; geom.boundingBox = this.geometry.boundingBox; raycastMesh.matrixWorld = this.matrixWorld; raycastMesh.material.side = this.material.side; tempArray.length = 0; raycastMesh.raycast(raycaster, tempArray); for (let i4 = 0; i4 < tempArray.length; i4++) { tempArray[i4].object = this; intersects.push(tempArray[i4]); } } } copy(source) { const geom = this.geometry; super.copy(source); this.geometry = geom; COPYABLE_PROPS.forEach((prop) => { this[prop] = source[prop]; }); return this; } clone() { return new this.constructor().copy(this); } }; SYNCABLE_PROPS.forEach((prop) => { const privateKey = "_private_" + prop; Object.defineProperty(Text.prototype, prop, { get() { return this[privateKey]; }, set(value) { if (value !== this[privateKey]) { this[privateKey] = value; this._needsSync = true; } } }); }); var tempBox3 = new Box3(); var tempColor$1 = new Color(); // node_modules/@react-three/drei/core/Text.js var Text2 = React21.forwardRef(({ sdfGlyphSize = 64, anchorX = "center", anchorY = "middle", font, fontSize = 1, children, characters, onSync, ...props }, ref) => { const invalidate = useThree(({ invalidate: invalidate2 }) => invalidate2); const [troikaMesh] = React21.useState(() => new Text()); const [nodes, text] = React21.useMemo(() => { const n2 = []; let t3 = ""; React21.Children.forEach(children, (child) => { if (typeof child === "string" || typeof child === "number") { t3 += child; } else { n2.push(child); } }); return [n2, t3]; }, [children]); suspend(() => new Promise((res) => preloadFont({ font, characters }, res)), ["troika-text", font, characters]); React21.useLayoutEffect(() => void troikaMesh.sync(() => { invalidate(); if (onSync) onSync(troikaMesh); })); React21.useEffect(() => { return () => troikaMesh.dispose(); }, [troikaMesh]); return React21.createElement("primitive", _extends({ object: troikaMesh, ref, font, text, anchorX, anchorY, fontSize, sdfGlyphSize }, props), nodes); }); // node_modules/@react-three/drei/core/Text3D.js var React22 = __toESM(require_react()); var import_react6 = __toESM(require_react()); // node_modules/@react-three/drei/core/useFont.js var fontLoader = null; async function loadFontData(font) { return typeof font === "string" ? await (await fetch(font)).json() : font; } function parseFontData(fontData) { if (!fontLoader) { fontLoader = new FontLoader(); } return fontLoader.parse(fontData); } async function loader(font) { const data = await loadFontData(font); return parseFontData(data); } function useFont(font) { return suspend(loader, [font]); } useFont.preload = (font) => preload(loader, [font]); useFont.clear = (font) => clear([font]); // node_modules/@react-three/drei/core/Text3D.js var types = ["string", "number"]; var getTextFromChildren = (children) => { let label = ""; const rest = []; React22.Children.forEach(children, (child) => { if (types.includes(typeof child)) label += child + ""; else rest.push(child); }); return [label, ...rest]; }; var Text3D = React22.forwardRef(({ font: _font, letterSpacing = 0, lineHeight = 1, size: size2 = 1, height = 0.2, bevelThickness = 0.1, bevelSize = 0.01, bevelEnabled = false, bevelOffset = 0, bevelSegments = 4, curveSegments = 8, smooth, children, ...props }, fref) => { React22.useMemo(() => extend({ RenamedTextGeometry: TextGeometry }), []); const ref = React22.useRef(null); const font = useFont(_font); const opts = (0, import_react6.useMemo)(() => { return { font, size: size2, height, bevelThickness, bevelSize, bevelEnabled, bevelSegments, bevelOffset, curveSegments, letterSpacing, lineHeight }; }, [font, size2, height, bevelThickness, bevelSize, bevelEnabled, bevelSegments, bevelOffset, curveSegments, letterSpacing, lineHeight]); const [label, ...rest] = (0, import_react6.useMemo)(() => getTextFromChildren(children), [children]); const args = React22.useMemo(() => [label, opts], [label, opts]); React22.useLayoutEffect(() => { if (smooth) { ref.current.geometry = mergeVertices(ref.current.geometry, smooth); ref.current.geometry.computeVertexNormals(); } }, [args, smooth]); React22.useImperativeHandle(fref, () => ref.current, []); return React22.createElement("mesh", _extends({}, props, { ref }), React22.createElement("renamedTextGeometry", { args }), rest); }); // node_modules/@react-three/drei/core/Effects.js var React23 = __toESM(require_react()); var isWebGL2Available2 = () => { try { var canvas = document.createElement("canvas"); return !!(window.WebGL2RenderingContext && canvas.getContext("webgl2")); } catch (e2) { return false; } }; var Effects = React23.forwardRef(({ children, multisamping = 8, renderIndex = 1, disableRender, disableGamma, disableRenderPass, depthBuffer = true, stencilBuffer = false, anisotropy = 1, colorSpace, type, ...props }, ref) => { React23.useMemo(() => extend({ EffectComposer, RenderPass, ShaderPass }), []); const composer = React23.useRef(null); React23.useImperativeHandle(ref, () => composer.current, []); const { scene, camera, gl, size: size2, viewport } = useThree(); const [target2] = React23.useState(() => { const t3 = new WebGLRenderTarget(size2.width, size2.height, { type: type || HalfFloatType, format: RGBAFormat, depthBuffer, stencilBuffer, anisotropy }); if (type === UnsignedByteType && colorSpace != null) { t3.texture.colorSpace = colorSpace; } t3.samples = multisamping; return t3; }); React23.useEffect(() => { var _composer$current, _composer$current2; (_composer$current = composer.current) == null || _composer$current.setSize(size2.width, size2.height); (_composer$current2 = composer.current) == null || _composer$current2.setPixelRatio(viewport.dpr); }, [gl, size2, viewport.dpr]); useFrame(() => { var _composer$current3; if (!disableRender) (_composer$current3 = composer.current) == null || _composer$current3.render(); }, renderIndex); const passes = []; if (!disableRenderPass) passes.push(React23.createElement("renderPass", { key: "renderpass", attach: `passes-${passes.length}`, args: [scene, camera] })); if (!disableGamma) passes.push(React23.createElement("shaderPass", { attach: `passes-${passes.length}`, key: "gammapass", args: [GammaCorrectionShader] })); React23.Children.forEach(children, (el) => { el && passes.push(React23.cloneElement(el, { key: passes.length, attach: `passes-${passes.length}` })); }); return React23.createElement("effectComposer", _extends({ ref: composer, args: [gl, target2] }, props), passes); }); // node_modules/@react-three/drei/core/GradientTexture.js var React24 = __toESM(require_react()); var GradientType = (function(GradientType2) { GradientType2["Linear"] = "linear"; GradientType2["Radial"] = "radial"; return GradientType2; })({}); function GradientTexture({ stops, colors: colors2, size: size2 = 1024, width = 16, type = GradientType.Linear, innerCircleRadius = 0, outerCircleRadius = "auto", ...props }) { const gl = useThree((state) => state.gl); const canvas = React24.useMemo(() => { const canvas2 = document.createElement("canvas"); const context12 = canvas2.getContext("2d"); canvas2.width = width; canvas2.height = size2; let gradient; if (type === GradientType.Linear) { gradient = context12.createLinearGradient(0, 0, 0, size2); } else { const canvasCenterX = canvas2.width / 2; const canvasCenterY = canvas2.height / 2; const radius = outerCircleRadius !== "auto" ? Math.abs(Number(outerCircleRadius)) : Math.sqrt(canvasCenterX ** 2 + canvasCenterY ** 2); gradient = context12.createRadialGradient(canvasCenterX, canvasCenterY, Math.abs(innerCircleRadius), canvasCenterX, canvasCenterY, radius); } const tempColor2 = new Color(); let i4 = stops.length; while (i4--) { gradient.addColorStop(stops[i4], tempColor2.set(colors2[i4]).getStyle()); } context12.save(); context12.fillStyle = gradient; context12.fillRect(0, 0, width, size2); context12.restore(); return canvas2; }, [stops]); return React24.createElement("canvasTexture", _extends({ colorSpace: gl.outputColorSpace, args: [canvas], attach: "map" }, props)); } // node_modules/@react-three/drei/core/Image.js var React26 = __toESM(require_react()); // node_modules/@react-three/drei/core/shaderMaterial.js function shaderMaterial(uniforms, vertexShader3, fragmentShader3, onInit) { var _Class; return _Class = class extends ShaderMaterial { constructor(parameters) { super({ vertexShader: vertexShader3, fragmentShader: fragmentShader3, ...parameters }); for (const key in uniforms) { this.uniforms[key] = new Uniform(uniforms[key]); Object.defineProperty(this, key, { get() { return this.uniforms[key].value; }, set(value) { this.uniforms[key].value = value; } }); } this.uniforms = UniformsUtils.clone(this.uniforms); onInit == null || onInit(this); } }, _Class.key = MathUtils.generateUUID(), _Class; } // node_modules/@react-three/drei/core/Texture.js var React25 = __toESM(require_react()); var import_react7 = __toESM(require_react()); var IsObject = (url) => url === Object(url) && !Array.isArray(url) && typeof url !== "function"; function useTexture(input, onLoad) { const gl = useThree((state) => state.gl); const textures = useLoader(TextureLoader, IsObject(input) ? Object.values(input) : input); (0, import_react7.useLayoutEffect)(() => { onLoad == null || onLoad(textures); }, [onLoad]); (0, import_react7.useEffect)(() => { if ("initTexture" in gl) { let textureArray = []; if (Array.isArray(textures)) { textureArray = textures; } else if (textures instanceof Texture) { textureArray = [textures]; } else if (IsObject(textures)) { textureArray = Object.values(textures); } textureArray.forEach((texture) => { if (texture instanceof Texture) { gl.initTexture(texture); } }); } }, [gl, textures]); const mappedTextures = (0, import_react7.useMemo)(() => { if (IsObject(input)) { const keyed = {}; let i4 = 0; for (const key in input) keyed[key] = textures[i4++]; return keyed; } else { return textures; } }, [input, textures]); return mappedTextures; } useTexture.preload = (url) => useLoader.preload(TextureLoader, url); useTexture.clear = (input) => useLoader.clear(TextureLoader, input); var Texture2 = ({ children, input, onLoad }) => { const ret = useTexture(input, onLoad); return React25.createElement(React25.Fragment, null, children == null ? void 0 : children(ret)); }; // node_modules/@react-three/drei/helpers/constants.js var getVersion = () => parseInt(REVISION.replace(/\D+/g, "")); var version2 = getVersion(); // node_modules/@react-three/drei/core/Image.js var ImageMaterialImpl = shaderMaterial( { color: new Color("white"), scale: new Vector2(1, 1), imageBounds: new Vector2(1, 1), resolution: 1024, map: null, zoom: 1, radius: 0, grayscale: 0, opacity: 1 }, /* glsl */ ` varying vec2 vUv; varying vec2 vPos; void main() { gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.); vUv = uv; vPos = position.xy; } `, /* glsl */ ` // mostly from https://gist.github.com/statico/df64c5d167362ecf7b34fca0b1459a44 varying vec2 vUv; varying vec2 vPos; uniform vec2 scale; uniform vec2 imageBounds; uniform float resolution; uniform vec3 color; uniform sampler2D map; uniform float radius; uniform float zoom; uniform float grayscale; uniform float opacity; const vec3 luma = vec3(.299, 0.587, 0.114); vec4 toGrayscale(vec4 color, float intensity) { return vec4(mix(color.rgb, vec3(dot(color.rgb, luma)), intensity), color.a); } vec2 aspect(vec2 size) { return size / min(size.x, size.y); } const float PI = 3.14159265; // from https://iquilezles.org/articles/distfunctions float udRoundBox( vec2 p, vec2 b, float r ) { return length(max(abs(p)-b+r,0.0))-r; } void main() { vec2 s = aspect(scale); vec2 i = aspect(imageBounds); float rs = s.x / s.y; float ri = i.x / i.y; vec2 new = rs < ri ? vec2(i.x * s.y / i.y, s.y) : vec2(s.x, i.y * s.x / i.x); vec2 offset = (rs < ri ? vec2((new.x - s.x) / 2.0, 0.0) : vec2(0.0, (new.y - s.y) / 2.0)) / new; vec2 uv = vUv * s / new + offset; vec2 zUv = (uv - vec2(0.5, 0.5)) / zoom + vec2(0.5, 0.5); vec2 res = vec2(scale * resolution); vec2 halfRes = 0.5 * res; float b = udRoundBox(vUv.xy * res - halfRes, halfRes, resolution * radius); vec3 a = mix(vec3(1.0,0.0,0.0), vec3(0.0,0.0,0.0), smoothstep(0.0, 1.0, b)); gl_FragColor = toGrayscale(texture2D(map, zUv) * vec4(color, opacity * a), grayscale); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> } ` ); var ImageBase = React26.forwardRef(({ children, color, segments = 1, scale: scale5 = 1, zoom = 1, grayscale = 0, opacity = 1, radius = 0, texture, toneMapped, transparent, side, ...props }, fref) => { extend({ ImageMaterial: ImageMaterialImpl }); const ref = React26.useRef(null); const size2 = useThree((state) => state.size); const planeBounds = Array.isArray(scale5) ? [scale5[0], scale5[1]] : [scale5, scale5]; const imageBounds = [texture.image.width, texture.image.height]; const resolution = Math.max(size2.width, size2.height); React26.useImperativeHandle(fref, () => ref.current, []); React26.useLayoutEffect(() => { if (ref.current.geometry.parameters) { ref.current.material.scale.set( // @ts-ignore planeBounds[0] * ref.current.geometry.parameters.width, // @ts-ignore planeBounds[1] * ref.current.geometry.parameters.height ); } }, [planeBounds[0], planeBounds[1]]); return React26.createElement("mesh", _extends({ ref, scale: Array.isArray(scale5) ? [...scale5, 1] : scale5 }, props), React26.createElement("planeGeometry", { args: [1, 1, segments, segments] }), React26.createElement("imageMaterial", { color, map: texture, zoom, grayscale, opacity, scale: planeBounds, imageBounds, resolution, radius, toneMapped, transparent, side, key: ImageMaterialImpl.key }), children); }); var ImageWithUrl = React26.forwardRef(({ url, ...props }, ref) => { const texture = useTexture(url); return React26.createElement(ImageBase, _extends({}, props, { texture, ref })); }); var ImageWithTexture = React26.forwardRef(({ url: _url, ...props }, ref) => { return React26.createElement(ImageBase, _extends({}, props, { ref })); }); var Image2 = React26.forwardRef((props, ref) => { if (props.url) return React26.createElement(ImageWithUrl, _extends({}, props, { ref })); else if (props.texture) return React26.createElement(ImageWithTexture, _extends({}, props, { ref })); else throw new Error(" requires a url or texture"); }); // node_modules/@react-three/drei/core/Edges.js var React27 = __toESM(require_react()); var Edges = React27.forwardRef(({ threshold = 15, geometry: explicitGeometry, ...props }, fref) => { const ref = React27.useRef(null); React27.useImperativeHandle(fref, () => ref.current, []); const tmpPoints = React27.useMemo(() => [0, 0, 0, 1, 0, 0], []); const memoizedGeometry = React27.useRef(null); const memoizedThreshold = React27.useRef(null); React27.useLayoutEffect(() => { const parent = ref.current.parent; const geometry3 = explicitGeometry !== null && explicitGeometry !== void 0 ? explicitGeometry : parent == null ? void 0 : parent.geometry; if (!geometry3) return; const cached = memoizedGeometry.current === geometry3 && memoizedThreshold.current === threshold; if (cached) return; memoizedGeometry.current = geometry3; memoizedThreshold.current = threshold; const points = new EdgesGeometry(geometry3, threshold).attributes.position.array; ref.current.geometry.setPositions(points); ref.current.geometry.attributes.instanceStart.needsUpdate = true; ref.current.geometry.attributes.instanceEnd.needsUpdate = true; ref.current.computeLineDistances(); }); return React27.createElement(Line4, _extends({ segments: true, points: tmpPoints, ref, raycast: () => null }, props)); }); // node_modules/@react-three/drei/core/Outlines.js var React28 = __toESM(require_react()); var OutlinesMaterial = shaderMaterial({ screenspace: false, color: new Color("black"), opacity: 1, thickness: 0.05, size: new Vector2() }, `#include #include #include #include uniform float thickness; uniform bool screenspace; uniform vec2 size; void main() { #if defined (USE_SKINNING) #include #include #include #include #include #endif #include #include #include #include #include vec4 tNormal = vec4(normal, 0.0); vec4 tPosition = vec4(transformed, 1.0); #ifdef USE_INSTANCING tNormal = instanceMatrix * tNormal; tPosition = instanceMatrix * tPosition; #endif if (screenspace) { vec3 newPosition = tPosition.xyz + tNormal.xyz * thickness; gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0); } else { vec4 clipPosition = projectionMatrix * modelViewMatrix * tPosition; vec4 clipNormal = projectionMatrix * modelViewMatrix * tNormal; vec2 offset = normalize(clipNormal.xy) * thickness / size * clipPosition.w * 2.0; clipPosition.xy += offset; gl_Position = clipPosition; } }`, `uniform vec3 color; uniform float opacity; #include void main(){ #include gl_FragColor = vec4(color, opacity); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }`); function Outlines({ color = "black", opacity = 1, transparent = false, screenspace = false, toneMapped = true, polygonOffset = false, polygonOffsetFactor = 0, renderOrder = 0, thickness = 0.05, angle = Math.PI, clippingPlanes, ...props }) { const ref = React28.useRef(null); const [material] = React28.useState(() => new OutlinesMaterial({ side: BackSide })); const { gl } = useThree(); const contextSize = gl.getDrawingBufferSize(new Vector2()); React28.useMemo(() => extend({ OutlinesMaterial }), []); const oldAngle = React28.useRef(0); const oldGeometry = React28.useRef(null); React28.useLayoutEffect(() => { const group = ref.current; if (!group) return; const parent = group.parent; if (parent && parent.geometry) { if (oldAngle.current !== angle || oldGeometry.current !== parent.geometry) { var _group$children; oldAngle.current = angle; oldGeometry.current = parent.geometry; let mesh = (_group$children = group.children) == null ? void 0 : _group$children[0]; if (mesh) { if (angle) mesh.geometry.dispose(); group.remove(mesh); } if (parent.skeleton) { mesh = new SkinnedMesh(); mesh.material = material; mesh.bind(parent.skeleton, parent.bindMatrix); group.add(mesh); } else if (parent.isInstancedMesh) { mesh = new InstancedMesh(parent.geometry, material, parent.count); mesh.instanceMatrix = parent.instanceMatrix; group.add(mesh); } else { mesh = new Mesh(); mesh.material = material; group.add(mesh); } mesh.geometry = angle ? toCreasedNormals(parent.geometry, angle) : parent.geometry; mesh.morphTargetInfluences = parent.morphTargetInfluences; mesh.morphTargetDictionary = parent.morphTargetDictionary; } } }); React28.useLayoutEffect(() => { const group = ref.current; if (!group) return; const mesh = group.children[0]; if (mesh) { mesh.renderOrder = renderOrder; const parent = group.parent; applyProps(mesh, { morphTargetInfluences: parent.morphTargetInfluences, morphTargetDictionary: parent.morphTargetDictionary }); applyProps(mesh.material, { transparent, thickness, color, opacity, size: contextSize, screenspace, toneMapped, polygonOffset, polygonOffsetFactor, clippingPlanes, clipping: clippingPlanes && clippingPlanes.length > 0 }); } }); React28.useEffect(() => { return () => { const group = ref.current; if (!group) return; const mesh = group.children[0]; if (mesh) { if (angle) mesh.geometry.dispose(); group.remove(mesh); } }; }, []); return React28.createElement("group", _extends({ ref }, props)); } // node_modules/@react-three/drei/core/Trail.js var React29 = __toESM(require_react()); // node_modules/meshline/dist/index.js var __defProp33 = Object.defineProperty; var __defNormalProp33 = (obj, key, value) => key in obj ? __defProp33(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField33 = (obj, key, value) => { __defNormalProp33(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; function memcpy(src, srcOffset, dst, dstOffset, length3) { let i4; src = src.subarray || src.slice ? src : src.buffer; dst = dst.subarray || dst.slice ? dst : dst.buffer; src = srcOffset ? src.subarray ? src.subarray(srcOffset, length3 && srcOffset + length3) : src.slice(srcOffset, length3 && srcOffset + length3) : src; if (dst.set) { dst.set(src, dstOffset); } else { for (i4 = 0; i4 < src.length; i4++) dst[i4 + dstOffset] = src[i4]; } return dst; } function convertPoints(points) { if (points instanceof Float32Array) return points; if (points instanceof BufferGeometry) return points.getAttribute("position").array; return points.map((p2) => { const isArray3 = Array.isArray(p2); return p2 instanceof Vector3 ? [p2.x, p2.y, p2.z] : p2 instanceof Vector2 ? [p2.x, p2.y, 0] : isArray3 && p2.length === 3 ? [p2[0], p2[1], p2[2]] : isArray3 && p2.length === 2 ? [p2[0], p2[1], 0] : p2; }).flat(); } var MeshLineGeometry = class extends BufferGeometry { constructor() { super(); __publicField33(this, "type", "MeshLine"); __publicField33(this, "isMeshLine", true); __publicField33(this, "positions", []); __publicField33(this, "previous", []); __publicField33(this, "next", []); __publicField33(this, "side", []); __publicField33(this, "width", []); __publicField33(this, "indices_array", []); __publicField33(this, "uvs", []); __publicField33(this, "counters", []); __publicField33(this, "widthCallback", null); __publicField33(this, "_attributes"); __publicField33(this, "_points", []); __publicField33(this, "points"); __publicField33(this, "matrixWorld", new Matrix4()); Object.defineProperties(this, { points: { enumerable: true, get() { return this._points; }, set(value) { this.setPoints(value, this.widthCallback); } } }); } setMatrixWorld(matrixWorld) { this.matrixWorld = matrixWorld; } setPoints(points, wcb) { points = convertPoints(points); this._points = points; this.widthCallback = wcb != null ? wcb : null; this.positions = []; this.counters = []; if (points.length && points[0] instanceof Vector3) { for (let j = 0; j < points.length; j++) { const p2 = points[j]; const c2 = j / (points.length - 1); this.positions.push(p2.x, p2.y, p2.z); this.positions.push(p2.x, p2.y, p2.z); this.counters.push(c2); this.counters.push(c2); } } else { for (let j = 0; j < points.length; j += 3) { const c2 = j / (points.length - 1); this.positions.push(points[j], points[j + 1], points[j + 2]); this.positions.push(points[j], points[j + 1], points[j + 2]); this.counters.push(c2); this.counters.push(c2); } } this.process(); } compareV3(a6, b5) { const aa = a6 * 6; const ab2 = b5 * 6; return this.positions[aa] === this.positions[ab2] && this.positions[aa + 1] === this.positions[ab2 + 1] && this.positions[aa + 2] === this.positions[ab2 + 2]; } copyV3(a6) { const aa = a6 * 6; return [this.positions[aa], this.positions[aa + 1], this.positions[aa + 2]]; } process() { const l2 = this.positions.length / 6; this.previous = []; this.next = []; this.side = []; this.width = []; this.indices_array = []; this.uvs = []; let w; let v5; if (this.compareV3(0, l2 - 1)) { v5 = this.copyV3(l2 - 2); } else { v5 = this.copyV3(0); } this.previous.push(v5[0], v5[1], v5[2]); this.previous.push(v5[0], v5[1], v5[2]); for (let j = 0; j < l2; j++) { this.side.push(1); this.side.push(-1); if (this.widthCallback) w = this.widthCallback(j / (l2 - 1)); else w = 1; this.width.push(w); this.width.push(w); this.uvs.push(j / (l2 - 1), 0); this.uvs.push(j / (l2 - 1), 1); if (j < l2 - 1) { v5 = this.copyV3(j); this.previous.push(v5[0], v5[1], v5[2]); this.previous.push(v5[0], v5[1], v5[2]); const n2 = j * 2; this.indices_array.push(n2, n2 + 1, n2 + 2); this.indices_array.push(n2 + 2, n2 + 1, n2 + 3); } if (j > 0) { v5 = this.copyV3(j); this.next.push(v5[0], v5[1], v5[2]); this.next.push(v5[0], v5[1], v5[2]); } } if (this.compareV3(l2 - 1, 0)) { v5 = this.copyV3(1); } else { v5 = this.copyV3(l2 - 1); } this.next.push(v5[0], v5[1], v5[2]); this.next.push(v5[0], v5[1], v5[2]); if (!this._attributes || this._attributes.position.count !== this.counters.length) { this._attributes = { position: new BufferAttribute(new Float32Array(this.positions), 3), previous: new BufferAttribute(new Float32Array(this.previous), 3), next: new BufferAttribute(new Float32Array(this.next), 3), side: new BufferAttribute(new Float32Array(this.side), 1), width: new BufferAttribute(new Float32Array(this.width), 1), uv: new BufferAttribute(new Float32Array(this.uvs), 2), index: new BufferAttribute(new Uint16Array(this.indices_array), 1), counters: new BufferAttribute(new Float32Array(this.counters), 1) }; } else { this._attributes.position.copyArray(new Float32Array(this.positions)); this._attributes.position.needsUpdate = true; this._attributes.previous.copyArray(new Float32Array(this.previous)); this._attributes.previous.needsUpdate = true; this._attributes.next.copyArray(new Float32Array(this.next)); this._attributes.next.needsUpdate = true; this._attributes.side.copyArray(new Float32Array(this.side)); this._attributes.side.needsUpdate = true; this._attributes.width.copyArray(new Float32Array(this.width)); this._attributes.width.needsUpdate = true; this._attributes.uv.copyArray(new Float32Array(this.uvs)); this._attributes.uv.needsUpdate = true; this._attributes.index.copyArray(new Uint16Array(this.indices_array)); this._attributes.index.needsUpdate = true; } this.setAttribute("position", this._attributes.position); this.setAttribute("previous", this._attributes.previous); this.setAttribute("next", this._attributes.next); this.setAttribute("side", this._attributes.side); this.setAttribute("width", this._attributes.width); this.setAttribute("uv", this._attributes.uv); this.setAttribute("counters", this._attributes.counters); this.setAttribute("position", this._attributes.position); this.setAttribute("previous", this._attributes.previous); this.setAttribute("next", this._attributes.next); this.setAttribute("side", this._attributes.side); this.setAttribute("width", this._attributes.width); this.setAttribute("uv", this._attributes.uv); this.setAttribute("counters", this._attributes.counters); this.setIndex(this._attributes.index); this.computeBoundingSphere(); this.computeBoundingBox(); } advance({ x, y, z }) { const positions = this._attributes.position.array; const previous = this._attributes.previous.array; const next = this._attributes.next.array; const l2 = positions.length; memcpy(positions, 0, previous, 0, l2); memcpy(positions, 6, positions, 0, l2 - 6); positions[l2 - 6] = x; positions[l2 - 5] = y; positions[l2 - 4] = z; positions[l2 - 3] = x; positions[l2 - 2] = y; positions[l2 - 1] = z; memcpy(positions, 6, next, 0, l2 - 6); next[l2 - 6] = x; next[l2 - 5] = y; next[l2 - 4] = z; next[l2 - 3] = x; next[l2 - 2] = y; next[l2 - 1] = z; this._attributes.position.needsUpdate = true; this._attributes.previous.needsUpdate = true; this._attributes.next.needsUpdate = true; } }; var vertexShader = ` #include #include #include #include attribute vec3 previous; attribute vec3 next; attribute float side; attribute float width; attribute float counters; uniform vec2 resolution; uniform float lineWidth; uniform vec3 color; uniform float opacity; uniform float sizeAttenuation; varying vec2 vUV; varying vec4 vColor; varying float vCounters; vec2 fix(vec4 i, float aspect) { vec2 res = i.xy / i.w; res.x *= aspect; return res; } void main() { float aspect = resolution.x / resolution.y; vColor = vec4(color, opacity); vUV = uv; vCounters = counters; mat4 m = projectionMatrix * modelViewMatrix; vec4 finalPosition = m * vec4(position, 1.0) * aspect; vec4 prevPos = m * vec4(previous, 1.0); vec4 nextPos = m * vec4(next, 1.0); vec2 currentP = fix(finalPosition, aspect); vec2 prevP = fix(prevPos, aspect); vec2 nextP = fix(nextPos, aspect); float w = lineWidth * width; vec2 dir; if (nextP == currentP) dir = normalize(currentP - prevP); else if (prevP == currentP) dir = normalize(nextP - currentP); else { vec2 dir1 = normalize(currentP - prevP); vec2 dir2 = normalize(nextP - currentP); dir = normalize(dir1 + dir2); vec2 perp = vec2(-dir1.y, dir1.x); vec2 miter = vec2(-dir.y, dir.x); //w = clamp(w / dot(miter, perp), 0., 4. * lineWidth * width); } //vec2 normal = (cross(vec3(dir, 0.), vec3(0., 0., 1.))).xy; vec4 normal = vec4(-dir.y, dir.x, 0., 1.); normal.xy *= .5 * w; //normal *= projectionMatrix; if (sizeAttenuation == 0.) { normal.xy *= finalPosition.w; normal.xy /= (vec4(resolution, 0., 1.) * projectionMatrix).xy * aspect; } finalPosition.xy += normal.xy * side; gl_Position = finalPosition; #include #include vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); #include #include } `; var version3 = (() => parseInt(REVISION.replace(/\D+/g, "")))(); var colorspace_fragment = version3 >= 154 ? "colorspace_fragment" : "encodings_fragment"; var fragmentShader = ` #include #include #include uniform sampler2D map; uniform sampler2D alphaMap; uniform float useGradient; uniform float useMap; uniform float useAlphaMap; uniform float useDash; uniform float dashArray; uniform float dashOffset; uniform float dashRatio; uniform float visibility; uniform float alphaTest; uniform vec2 repeat; uniform vec3 gradient[2]; varying vec2 vUV; varying vec4 vColor; varying float vCounters; void main() { #include vec4 diffuseColor = vColor; if (useGradient == 1.) diffuseColor = vec4(mix(gradient[0], gradient[1], vCounters), 1.0); if (useMap == 1.) diffuseColor *= texture2D(map, vUV * repeat); if (useAlphaMap == 1.) diffuseColor.a *= texture2D(alphaMap, vUV * repeat).a; if (diffuseColor.a < alphaTest) discard; if (useDash == 1.) diffuseColor.a *= ceil(mod(vCounters + dashOffset, dashArray) - (dashArray * dashRatio)); diffuseColor.a *= step(vCounters, visibility); #include gl_FragColor = diffuseColor; #include #include #include <${colorspace_fragment}> } `; var MeshLineMaterial = class extends ShaderMaterial { constructor(parameters) { super({ uniforms: { ...UniformsLib.fog, lineWidth: { value: 1 }, map: { value: null }, useMap: { value: 0 }, alphaMap: { value: null }, useAlphaMap: { value: 0 }, color: { value: new Color(16777215) }, gradient: { value: [new Color(16711680), new Color(65280)] }, opacity: { value: 1 }, resolution: { value: new Vector2(1, 1) }, sizeAttenuation: { value: 1 }, dashArray: { value: 0 }, dashOffset: { value: 0 }, dashRatio: { value: 0.5 }, useDash: { value: 0 }, useGradient: { value: 0 }, visibility: { value: 1 }, alphaTest: { value: 0 }, repeat: { value: new Vector2(1, 1) } }, vertexShader, fragmentShader }); __publicField33(this, "lineWidth"); __publicField33(this, "map"); __publicField33(this, "useMap"); __publicField33(this, "alphaMap"); __publicField33(this, "useAlphaMap"); __publicField33(this, "color"); __publicField33(this, "gradient"); __publicField33(this, "resolution"); __publicField33(this, "sizeAttenuation"); __publicField33(this, "dashArray"); __publicField33(this, "dashOffset"); __publicField33(this, "dashRatio"); __publicField33(this, "useDash"); __publicField33(this, "useGradient"); __publicField33(this, "visibility"); __publicField33(this, "repeat"); this.type = "MeshLineMaterial"; Object.defineProperties(this, { lineWidth: { enumerable: true, get() { return this.uniforms.lineWidth.value; }, set(value) { this.uniforms.lineWidth.value = value; } }, map: { enumerable: true, get() { return this.uniforms.map.value; }, set(value) { this.uniforms.map.value = value; } }, useMap: { enumerable: true, get() { return this.uniforms.useMap.value; }, set(value) { this.uniforms.useMap.value = value; } }, alphaMap: { enumerable: true, get() { return this.uniforms.alphaMap.value; }, set(value) { this.uniforms.alphaMap.value = value; } }, useAlphaMap: { enumerable: true, get() { return this.uniforms.useAlphaMap.value; }, set(value) { this.uniforms.useAlphaMap.value = value; } }, color: { enumerable: true, get() { return this.uniforms.color.value; }, set(value) { this.uniforms.color.value = value; } }, gradient: { enumerable: true, get() { return this.uniforms.gradient.value; }, set(value) { this.uniforms.gradient.value = value; } }, opacity: { enumerable: true, get() { return this.uniforms.opacity.value; }, set(value) { this.uniforms.opacity.value = value; } }, resolution: { enumerable: true, get() { return this.uniforms.resolution.value; }, set(value) { this.uniforms.resolution.value.copy(value); } }, sizeAttenuation: { enumerable: true, get() { return this.uniforms.sizeAttenuation.value; }, set(value) { this.uniforms.sizeAttenuation.value = value; } }, dashArray: { enumerable: true, get() { return this.uniforms.dashArray.value; }, set(value) { this.uniforms.dashArray.value = value; this.useDash = value !== 0 ? 1 : 0; } }, dashOffset: { enumerable: true, get() { return this.uniforms.dashOffset.value; }, set(value) { this.uniforms.dashOffset.value = value; } }, dashRatio: { enumerable: true, get() { return this.uniforms.dashRatio.value; }, set(value) { this.uniforms.dashRatio.value = value; } }, useDash: { enumerable: true, get() { return this.uniforms.useDash.value; }, set(value) { this.uniforms.useDash.value = value; } }, useGradient: { enumerable: true, get() { return this.uniforms.useGradient.value; }, set(value) { this.uniforms.useGradient.value = value; } }, visibility: { enumerable: true, get() { return this.uniforms.visibility.value; }, set(value) { this.uniforms.visibility.value = value; } }, alphaTest: { enumerable: true, get() { return this.uniforms.alphaTest.value; }, set(value) { this.uniforms.alphaTest.value = value; } }, repeat: { enumerable: true, get() { return this.uniforms.repeat.value; }, set(value) { this.uniforms.repeat.value.copy(value); } } }); this.setValues(parameters); } copy(source) { super.copy(source); this.lineWidth = source.lineWidth; this.map = source.map; this.useMap = source.useMap; this.alphaMap = source.alphaMap; this.useAlphaMap = source.useAlphaMap; this.color.copy(source.color); this.gradient = source.gradient; this.opacity = source.opacity; this.resolution.copy(source.resolution); this.sizeAttenuation = source.sizeAttenuation; this.dashArray = source.dashArray; this.dashOffset = source.dashOffset; this.dashRatio = source.dashRatio; this.useDash = source.useDash; this.useGradient = source.useGradient; this.visibility = source.visibility; this.alphaTest = source.alphaTest; this.repeat.copy(source.repeat); return this; } }; // node_modules/@react-three/drei/core/Trail.js var defaults = { width: 0.2, length: 1, decay: 1, local: false, stride: 0, interval: 1 }; var shiftLeft = (collection, steps = 1) => { collection.set(collection.subarray(steps)); collection.fill(-Infinity, -steps); return collection; }; function useTrail(target2, settings) { const { length: length3, local, decay, interval, stride } = { ...defaults, ...settings }; const points = React29.useRef(null); const [worldPosition] = React29.useState(() => new Vector3()); React29.useLayoutEffect(() => { if (target2) { points.current = Float32Array.from({ length: length3 * 10 * 3 }, (_, i4) => target2.position.getComponent(i4 % 3)); } }, [length3, target2]); const prevPosition = React29.useRef(new Vector3()); const frameCount = React29.useRef(0); useFrame(() => { if (!target2) return; if (!points.current) return; if (frameCount.current === 0) { let newPosition; if (local) { newPosition = target2.position; } else { target2.getWorldPosition(worldPosition); newPosition = worldPosition; } const steps = 1 * decay; for (let i4 = 0; i4 < steps; i4++) { if (newPosition.distanceTo(prevPosition.current) < stride) continue; shiftLeft(points.current, 3); points.current.set(newPosition.toArray(), points.current.length - 3); } prevPosition.current.copy(newPosition); } frameCount.current++; frameCount.current = frameCount.current % interval; }); return points; } var Trail = React29.forwardRef((props, forwardRef82) => { const { children } = props; const { width, length: length3, decay, local, stride, interval } = { ...defaults, ...props }; const { color = "hotpink", attenuation, target: target2 } = props; const size2 = useThree((s2) => s2.size); const scene = useThree((s2) => s2.scene); const ref = React29.useRef(null); const [anchor, setAnchor] = React29.useState(null); const points = useTrail(anchor, { length: length3, decay, local, stride, interval }); React29.useEffect(() => { const t3 = (target2 == null ? void 0 : target2.current) || ref.current.children.find((o2) => { return o2 instanceof Object3D; }); if (t3) { setAnchor(t3); } }, [points, target2]); const geo = React29.useMemo(() => new MeshLineGeometry(), []); const mat2 = React29.useMemo(() => { var _matOverride, _matOverride2; const m = new MeshLineMaterial({ lineWidth: 0.1 * width, color, sizeAttenuation: 1, resolution: new Vector2(size2.width, size2.height) }); let matOverride; if (children) { if (Array.isArray(children)) { matOverride = children.find((child) => { const c2 = child; return typeof c2.type === "string" && c2.type === "meshLineMaterial"; }); } else { const c2 = children; if (typeof c2.type === "string" && c2.type === "meshLineMaterial") { matOverride = c2; } } } if (typeof ((_matOverride = matOverride) == null ? void 0 : _matOverride.props) === "object" && ((_matOverride2 = matOverride) == null ? void 0 : _matOverride2.props) !== null) { m.setValues(matOverride.props); } return m; }, [width, color, size2, children]); React29.useEffect(() => { mat2.uniforms.resolution.value.set(size2.width, size2.height); }, [size2]); useFrame(() => { if (!points.current) return; geo.setPoints(points.current, attenuation); }); return React29.createElement("group", null, createPortal(React29.createElement("mesh", { ref: forwardRef82, geometry: geo, material: mat2 }), scene), React29.createElement("group", { ref }, children)); }); // node_modules/@react-three/drei/core/Sampler.js var React30 = __toESM(require_react()); function useSurfaceSampler(mesh, count = 16, transform, weight, instanceMesh) { const [buffer2, setBuffer] = React30.useState(() => { const arr = Array.from({ length: count }, () => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).flat(); return new InstancedBufferAttribute(Float32Array.from(arr), 16); }); React30.useLayoutEffect(() => { if (typeof mesh.current === "undefined") return; const sampler = new MeshSurfaceSampler(mesh.current); if (weight) { sampler.setWeightAttribute(weight); } sampler.build(); const position2 = new Vector3(); const normal2 = new Vector3(); const color = new Color(); const dummy2 = new Object3D(); mesh.current.updateMatrixWorld(true); for (let i4 = 0; i4 < count; i4++) { sampler.sample(position2, normal2, color); if (typeof transform === "function") { transform({ dummy: dummy2, sampledMesh: mesh.current, position: position2, normal: normal2, color }, i4); } else { dummy2.position.copy(position2); } dummy2.updateMatrix(); if (instanceMesh != null && instanceMesh.current) { instanceMesh.current.setMatrixAt(i4, dummy2.matrix); } dummy2.matrix.toArray(buffer2.array, i4 * 16); } if (instanceMesh != null && instanceMesh.current) { instanceMesh.current.instanceMatrix.needsUpdate = true; } buffer2.needsUpdate = true; setBuffer(new InstancedBufferAttribute(buffer2.array, buffer2.itemSize).copy(buffer2)); }, [mesh, instanceMesh, weight, count, transform]); return buffer2; } function Sampler({ children, weight, transform, instances, mesh, count = 16, ...props }) { const group = React30.useRef(null); const instancedRef = React30.useRef(null); const meshToSampleRef = React30.useRef(null); React30.useLayoutEffect(() => { var _instances$current, _mesh$current; instancedRef.current = (_instances$current = instances == null ? void 0 : instances.current) !== null && _instances$current !== void 0 ? _instances$current : group.current.children.find((c2) => c2.hasOwnProperty("instanceMatrix")); meshToSampleRef.current = (_mesh$current = mesh == null ? void 0 : mesh.current) !== null && _mesh$current !== void 0 ? _mesh$current : group.current.children.find((c2) => c2.type === "Mesh"); }, [children, mesh == null ? void 0 : mesh.current, instances == null ? void 0 : instances.current]); useSurfaceSampler(meshToSampleRef, count, transform, weight, instancedRef); return React30.createElement("group", _extends({ ref: group }, props), children); } // node_modules/@react-three/drei/core/ComputedAttribute.js var React31 = __toESM(require_react()); var ComputedAttribute = ({ compute, name, ...props }) => { const [bufferAttribute] = React31.useState(() => new BufferAttribute(new Float32Array(0), 1)); const primitive = React31.useRef(null); React31.useLayoutEffect(() => { if (primitive.current) { var _ref; const parent = (_ref = primitive.current.parent) !== null && _ref !== void 0 ? _ref : primitive.current.__r3f.parent.object; const attr = compute(parent); primitive.current.copy(attr); } }, [compute]); return React31.createElement("primitive", _extends({ ref: primitive, object: bufferAttribute, attach: `attributes-${name}` }, props)); }; // node_modules/@react-three/drei/core/Clone.js var React32 = __toESM(require_react()); function createSpread(child, { keys = ["near", "far", "color", "distance", "decay", "penumbra", "angle", "intensity", "skeleton", "visible", "castShadow", "receiveShadow", "morphTargetDictionary", "morphTargetInfluences", "name", "geometry", "material", "position", "rotation", "scale", "up", "userData", "bindMode", "bindMatrix", "bindMatrixInverse", "skeleton"], deep, inject: inject2, castShadow, receiveShadow }) { let spread = {}; for (const key of keys) { spread[key] = child[key]; } if (deep) { if (spread.geometry && deep !== "materialsOnly") spread.geometry = spread.geometry.clone(); if (spread.material && deep !== "geometriesOnly") spread.material = spread.material.clone(); } if (inject2) { if (typeof inject2 === "function") spread = { ...spread, children: inject2(child) }; else if (React32.isValidElement(inject2)) spread = { ...spread, children: inject2 }; else spread = { ...spread, ...inject2 }; } if (child instanceof Mesh) { if (castShadow) spread.castShadow = true; if (receiveShadow) spread.receiveShadow = true; } return spread; } var Clone = React32.forwardRef(({ isChild = false, object, children, deep, castShadow, receiveShadow, inject: inject2, keys, ...props }, forwardRef82) => { const config = { keys, deep, inject: inject2, castShadow, receiveShadow }; object = React32.useMemo(() => { if (isChild === false && !Array.isArray(object)) { let isSkinned = false; object.traverse((object2) => { if (object2.isSkinnedMesh) isSkinned = true; }); if (isSkinned) return SkeletonUtils.clone(object); } return object; }, [object, isChild]); if (Array.isArray(object)) { return React32.createElement("group", _extends({}, props, { ref: forwardRef82 }), object.map((o2) => React32.createElement(Clone, _extends({ key: o2.uuid, object: o2 }, config))), children); } const { children: injectChildren, ...spread } = createSpread(object, config); const Element2 = object.type[0].toLowerCase() + object.type.slice(1); return React32.createElement(Element2, _extends({}, spread, props, { ref: forwardRef82 }), object.children.map((child) => { if (child.type === "Bone") return React32.createElement("primitive", _extends({ key: child.uuid, object: child }, config)); return React32.createElement(Clone, _extends({ key: child.uuid, object: child }, config, { isChild: true })); }), children, injectChildren); }); // node_modules/@react-three/drei/core/MarchingCubes.js var React33 = __toESM(require_react()); var globalContext = React33.createContext(null); var MarchingCubes2 = React33.forwardRef(({ resolution = 28, maxPolyCount = 1e4, enableUvs = false, enableColors = false, children, ...props }, ref) => { const marchingCubesRef = React33.useRef(null); React33.useImperativeHandle(ref, () => marchingCubesRef.current, []); const marchingCubes = React33.useMemo(() => new MarchingCubes(resolution, null, enableUvs, enableColors, maxPolyCount), [resolution, maxPolyCount, enableUvs, enableColors]); const api = React33.useMemo(() => ({ getParent: () => marchingCubesRef }), []); useFrame(() => { marchingCubes.update(); marchingCubes.reset(); }, -1); return React33.createElement(React33.Fragment, null, React33.createElement("primitive", _extends({ object: marchingCubes, ref: marchingCubesRef }, props), React33.createElement(globalContext.Provider, { value: api }, children))); }); var MarchingCube = React33.forwardRef(({ strength = 0.5, subtract = 12, color, ...props }, ref) => { const { getParent } = React33.useContext(globalContext); const parentRef = React33.useMemo(() => getParent(), [getParent]); const cubeRef = React33.useRef(null); React33.useImperativeHandle(ref, () => cubeRef.current, []); const vec = new Vector3(); useFrame((state) => { if (!parentRef.current || !cubeRef.current) return; cubeRef.current.getWorldPosition(vec); parentRef.current.addBall(0.5 + vec.x * 0.5, 0.5 + vec.y * 0.5, 0.5 + vec.z * 0.5, strength, subtract, color); }); return React33.createElement("group", _extends({ ref: cubeRef }, props)); }); var MarchingPlane = React33.forwardRef(({ planeType: _planeType = "x", strength = 0.5, subtract = 12, ...props }, ref) => { const { getParent } = React33.useContext(globalContext); const parentRef = React33.useMemo(() => getParent(), [getParent]); const wallRef = React33.useRef(null); React33.useImperativeHandle(ref, () => wallRef.current, []); const planeType = React33.useMemo(() => _planeType === "x" ? "addPlaneX" : _planeType === "y" ? "addPlaneY" : "addPlaneZ", [_planeType]); useFrame(() => { if (!parentRef.current || !wallRef.current) return; parentRef.current[planeType](strength, subtract); }); return React33.createElement("group", _extends({ ref: wallRef }, props)); }); // node_modules/@react-three/drei/core/Decal.js var React34 = __toESM(require_react()); function isArray(vec) { return Array.isArray(vec); } function vecToArray(vec = [0, 0, 0]) { if (isArray(vec)) { return vec; } else if (vec instanceof Vector3 || vec instanceof Euler) { return [vec.x, vec.y, vec.z]; } else { return [vec, vec, vec]; } } var Decal = React34.forwardRef(function Decal2({ debug, depthTest = false, polygonOffsetFactor = -10, map: map2, mesh, children, position: position2, rotation: rotation3, scale: scale5, ...props }, forwardRef82) { const ref = React34.useRef(null); React34.useImperativeHandle(forwardRef82, () => ref.current); const helper = React34.useRef(null); const state = React34.useRef({ position: new Vector3(), rotation: new Euler(), scale: new Vector3(1, 1, 1) }); React34.useLayoutEffect(() => { const parent = (mesh == null ? void 0 : mesh.current) || ref.current.parent; const target2 = ref.current; if (!(parent instanceof Mesh)) { throw new Error('Decal must have a Mesh as parent or specify its "mesh" prop'); } if (parent) { applyProps(state.current, { position: position2, scale: scale5 }); const matrixWorld = parent.matrixWorld.clone(); parent.matrixWorld.identity(); if (!rotation3 || typeof rotation3 === "number") { const o2 = new Object3D(); o2.position.copy(state.current.position); const vertices = parent.geometry.attributes.position.array; if (parent.geometry.attributes.normal === void 0) parent.geometry.computeVertexNormals(); const normal2 = parent.geometry.attributes.normal.array; let distance3 = Infinity; let closestNormal = new Vector3(); const ox = o2.position.x; const oy = o2.position.y; const oz = o2.position.z; const vLength = vertices.length; let chosenIdx = -1; for (let i4 = 0; i4 < vLength; i4 += 3) { const x = vertices[i4]; const y = vertices[i4 + 1]; const z = vertices[i4 + 2]; const xDiff = x - ox; const yDiff = y - oy; const zDiff = z - oz; const distSquared = xDiff * xDiff + yDiff * yDiff + zDiff * zDiff; if (distSquared < distance3) { distance3 = distSquared; chosenIdx = i4; } } closestNormal.fromArray(normal2, chosenIdx); o2.lookAt(o2.position.clone().add(closestNormal)); o2.rotateZ(Math.PI); o2.rotateY(Math.PI); if (typeof rotation3 === "number") o2.rotateZ(rotation3); applyProps(state.current, { rotation: o2.rotation }); } else { applyProps(state.current, { rotation: rotation3 }); } if (helper.current) { applyProps(helper.current, state.current); } target2.geometry = new DecalGeometry(parent, state.current.position, state.current.rotation, state.current.scale); parent.matrixWorld = matrixWorld; return () => { target2.geometry.dispose(); }; } }, [mesh, ...vecToArray(position2), ...vecToArray(scale5), ...vecToArray(rotation3)]); React34.useLayoutEffect(() => { if (helper.current) { helper.current.traverse((child) => child.raycast = () => null); } }, [debug]); return React34.createElement("mesh", _extends({ ref, "material-transparent": true, "material-polygonOffset": true, "material-polygonOffsetFactor": polygonOffsetFactor, "material-depthTest": depthTest, "material-map": map2 }, props), children, debug && React34.createElement("mesh", { ref: helper }, React34.createElement("boxGeometry", null), React34.createElement("meshNormalMaterial", { wireframe: true }), React34.createElement("axesHelper", null))); }); // node_modules/@react-three/drei/core/Svg.js var React35 = __toESM(require_react()); var import_react8 = __toESM(require_react()); var Svg = (0, import_react8.forwardRef)(function R3FSvg({ src, skipFill, skipStrokes, fillMaterial, strokeMaterial, fillMeshProps, strokeMeshProps, ...props }, ref) { const svg = useLoader(SVGLoader, !src.startsWith(" skipStrokes ? [] : svg.paths.map((path) => { var _path$userData; return ((_path$userData = path.userData) == null ? void 0 : _path$userData.style.stroke) === void 0 || path.userData.style.stroke === "none" ? null : path.subPaths.map((subPath) => SVGLoader.pointsToStroke(subPath.getPoints(), path.userData.style)); }), [svg, skipStrokes]); (0, import_react8.useEffect)(() => { return () => strokeGeometries.forEach((group) => group && group.map((g) => g.dispose())); }, [strokeGeometries]); let renderOrder = 0; return React35.createElement("object3D", _extends({ ref }, props), React35.createElement("object3D", { scale: [1, -1, 1] }, svg.paths.map((path, p2) => { var _path$userData2, _path$userData3; return React35.createElement(import_react8.Fragment, { key: p2 }, !skipFill && ((_path$userData2 = path.userData) == null ? void 0 : _path$userData2.style.fill) !== void 0 && path.userData.style.fill !== "none" && SVGLoader.createShapes(path).map((shape, s2) => React35.createElement("mesh", _extends({ key: s2 }, fillMeshProps, { renderOrder: renderOrder++ }), React35.createElement("shapeGeometry", { args: [shape] }), React35.createElement("meshBasicMaterial", _extends({ color: path.userData.style.fill, opacity: path.userData.style.fillOpacity, transparent: true, side: DoubleSide, depthWrite: false }, fillMaterial)))), !skipStrokes && ((_path$userData3 = path.userData) == null ? void 0 : _path$userData3.style.stroke) !== void 0 && path.userData.style.stroke !== "none" && path.subPaths.map((_subPath, s2) => React35.createElement("mesh", _extends({ key: s2, geometry: strokeGeometries[p2][s2] }, strokeMeshProps, { renderOrder: renderOrder++ }), React35.createElement("meshBasicMaterial", _extends({ color: path.userData.style.stroke, opacity: path.userData.style.strokeOpacity, transparent: true, side: DoubleSide, depthWrite: false }, strokeMaterial))))); }))); }); // node_modules/@react-three/drei/core/Gltf.js var React36 = __toESM(require_react()); var dracoLoader = null; var decoderPath = "https://www.gstatic.com/draco/versioned/decoders/1.5.5/"; function extensions(useDraco = true, useMeshopt = true, extendLoader) { return (loader2) => { if (extendLoader) { extendLoader(loader2); } if (useDraco) { if (!dracoLoader) { dracoLoader = new DRACOLoader(); } dracoLoader.setDecoderPath(typeof useDraco === "string" ? useDraco : decoderPath); loader2.setDRACOLoader(dracoLoader); } if (useMeshopt) { loader2.setMeshoptDecoder(typeof MeshoptDecoder === "function" ? MeshoptDecoder() : MeshoptDecoder); } }; } var useGLTF = (path, useDraco, useMeshopt, extendLoader) => useLoader(GLTFLoader, path, extensions(useDraco, useMeshopt, extendLoader)); useGLTF.preload = (path, useDraco, useMeshopt, extendLoader) => useLoader.preload(GLTFLoader, path, extensions(useDraco, useMeshopt, extendLoader)); useGLTF.clear = (path) => useLoader.clear(GLTFLoader, path); useGLTF.setDecoderPath = (path) => { decoderPath = path; }; var Gltf = React36.forwardRef(({ src, useDraco, useMeshOpt, extendLoader, ...props }, ref) => { const { scene } = useGLTF(src, useDraco, useMeshOpt, extendLoader); return React36.createElement(Clone, _extends({ ref }, props, { object: scene })); }); // node_modules/@react-three/drei/core/AsciiRenderer.js var React37 = __toESM(require_react()); function AsciiRenderer({ renderIndex = 1, bgColor = "black", fgColor = "white", characters = " .:-+*=%@#", invert = true, color = false, resolution = 0.15 }) { const { size: size2, gl, scene, camera } = useThree(); const effect = React37.useMemo(() => { const effect2 = new AsciiEffect(gl, characters, { invert, color, resolution }); effect2.domElement.style.position = "absolute"; effect2.domElement.style.top = "0px"; effect2.domElement.style.left = "0px"; effect2.domElement.style.pointerEvents = "none"; return effect2; }, [characters, invert, color, resolution]); React37.useLayoutEffect(() => { effect.domElement.style.color = fgColor; effect.domElement.style.backgroundColor = bgColor; }, [fgColor, bgColor]); React37.useEffect(() => { gl.domElement.style.opacity = "0"; gl.domElement.parentNode.appendChild(effect.domElement); return () => { gl.domElement.style.opacity = "1"; gl.domElement.parentNode.removeChild(effect.domElement); }; }, [effect]); React37.useEffect(() => { effect.setSize(size2.width, size2.height); }, [effect, size2]); useFrame((state) => { effect.render(scene, camera); }, renderIndex); return React37.createElement(React37.Fragment, null); } // node_modules/@react-three/drei/core/Splat.js var React38 = __toESM(require_react()); var SplatMaterial = shaderMaterial( { alphaTest: 0, viewport: new Vector2(1980, 1080), focal: 1e3, centerAndScaleTexture: null, covAndColorTexture: null }, /*glsl*/ ` precision highp sampler2D; precision highp usampler2D; out vec4 vColor; out vec3 vPosition; uniform vec2 resolution; uniform vec2 viewport; uniform float focal; attribute uint splatIndex; uniform sampler2D centerAndScaleTexture; uniform usampler2D covAndColorTexture; vec2 unpackInt16(in uint value) { int v = int(value); int v0 = v >> 16; int v1 = (v & 0xFFFF); if((v & 0x8000) != 0) v1 |= 0xFFFF0000; return vec2(float(v1), float(v0)); } void main () { ivec2 texSize = textureSize(centerAndScaleTexture, 0); ivec2 texPos = ivec2(splatIndex%uint(texSize.x), splatIndex/uint(texSize.x)); vec4 centerAndScaleData = texelFetch(centerAndScaleTexture, texPos, 0); vec4 center = vec4(centerAndScaleData.xyz, 1); vec4 camspace = modelViewMatrix * center; vec4 pos2d = projectionMatrix * camspace; float bounds = 1.2 * pos2d.w; if (pos2d.z < -pos2d.w || pos2d.x < -bounds || pos2d.x > bounds || pos2d.y < -bounds || pos2d.y > bounds) { gl_Position = vec4(0.0, 0.0, 2.0, 1.0); return; } uvec4 covAndColorData = texelFetch(covAndColorTexture, texPos, 0); vec2 cov3D_M11_M12 = unpackInt16(covAndColorData.x) * centerAndScaleData.w; vec2 cov3D_M13_M22 = unpackInt16(covAndColorData.y) * centerAndScaleData.w; vec2 cov3D_M23_M33 = unpackInt16(covAndColorData.z) * centerAndScaleData.w; mat3 Vrk = mat3( cov3D_M11_M12.x, cov3D_M11_M12.y, cov3D_M13_M22.x, cov3D_M11_M12.y, cov3D_M13_M22.y, cov3D_M23_M33.x, cov3D_M13_M22.x, cov3D_M23_M33.x, cov3D_M23_M33.y ); mat3 J = mat3( focal / camspace.z, 0., -(focal * camspace.x) / (camspace.z * camspace.z), 0., focal / camspace.z, -(focal * camspace.y) / (camspace.z * camspace.z), 0., 0., 0. ); mat3 W = transpose(mat3(modelViewMatrix)); mat3 T = W * J; mat3 cov = transpose(T) * Vrk * T; vec2 vCenter = vec2(pos2d) / pos2d.w; float diagonal1 = cov[0][0] + 0.3; float offDiagonal = cov[0][1]; float diagonal2 = cov[1][1] + 0.3; float mid = 0.5 * (diagonal1 + diagonal2); float radius = length(vec2((diagonal1 - diagonal2) / 2.0, offDiagonal)); float lambda1 = mid + radius; float lambda2 = max(mid - radius, 0.1); vec2 diagonalVector = normalize(vec2(offDiagonal, lambda1 - diagonal1)); vec2 v1 = min(sqrt(2.0 * lambda1), 1024.0) * diagonalVector; vec2 v2 = min(sqrt(2.0 * lambda2), 1024.0) * vec2(diagonalVector.y, -diagonalVector.x); uint colorUint = covAndColorData.w; vColor = vec4( float(colorUint & uint(0xFF)) / 255.0, float((colorUint >> uint(8)) & uint(0xFF)) / 255.0, float((colorUint >> uint(16)) & uint(0xFF)) / 255.0, float(colorUint >> uint(24)) / 255.0 ); vPosition = position; gl_Position = vec4( vCenter + position.x * v2 / viewport * 2.0 + position.y * v1 / viewport * 2.0, pos2d.z / pos2d.w, 1.0); } `, /*glsl*/ ` #include #include in vec4 vColor; in vec3 vPosition; void main () { float A = -dot(vPosition.xy, vPosition.xy); if (A < -4.0) discard; float B = exp(A) * vColor.a; vec4 diffuseColor = vec4(vColor.rgb, B); #include #include gl_FragColor = diffuseColor; #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> } ` ); function createWorker(self2) { let matrices = null; let offset = 0; function sortSplats(view, hashed = false) { const vertexCount = matrices.length / 16; const threshold = -1e-4; let maxDepth = -Infinity; let minDepth = Infinity; const depthList = new Float32Array(vertexCount); const sizeList = new Int32Array(depthList.buffer); const validIndexList = new Int32Array(vertexCount); let validCount = 0; for (let i4 = 0; i4 < vertexCount; i4++) { const depth = view[0] * matrices[i4 * 16 + 12] + view[1] * matrices[i4 * 16 + 13] + view[2] * matrices[i4 * 16 + 14] + view[3]; if (hashed || depth < 0 && matrices[i4 * 16 + 15] > threshold * depth) { depthList[validCount] = depth; validIndexList[validCount] = i4; validCount++; if (depth > maxDepth) maxDepth = depth; if (depth < minDepth) minDepth = depth; } } const depthInv = (256 * 256 - 1) / (maxDepth - minDepth); const counts0 = new Uint32Array(256 * 256); for (let i4 = 0; i4 < validCount; i4++) { sizeList[i4] = (depthList[i4] - minDepth) * depthInv | 0; counts0[sizeList[i4]]++; } const starts0 = new Uint32Array(256 * 256); for (let i4 = 1; i4 < 256 * 256; i4++) starts0[i4] = starts0[i4 - 1] + counts0[i4 - 1]; const depthIndex = new Uint32Array(validCount); for (let i4 = 0; i4 < validCount; i4++) depthIndex[starts0[sizeList[i4]]++] = validIndexList[i4]; return depthIndex; } self2.onmessage = (e2) => { if (e2.data.method == "push") { if (offset === 0) matrices = new Float32Array(e2.data.length); const new_matrices = new Float32Array(e2.data.matrices); matrices.set(new_matrices, offset); offset += new_matrices.length; } else if (e2.data.method == "sort") { if (matrices !== null) { const indices = sortSplats(new Float32Array(e2.data.view), e2.data.hashed); self2.postMessage({ indices, key: e2.data.key }, [indices.buffer]); } } }; } var SplatLoader = class extends Loader { constructor(...args) { super(...args); this.gl = null; this.chunkSize = 25e3; } load(url, onLoad, onProgress, onError) { const shared = { gl: this.gl, url: this.manager.resolveURL(url), worker: new Worker(URL.createObjectURL(new Blob(["(", createWorker.toString(), ")(self)"], { type: "application/javascript" }))), manager: this.manager, update: (target2, camera, hashed) => update(camera, shared, target2, hashed), connect: (target2) => connect(shared, target2), loading: false, loaded: false, loadedVertexCount: 0, chunkSize: this.chunkSize, totalDownloadBytes: 0, numVertices: 0, rowLength: 3 * 4 + 3 * 4 + 4 + 4, maxVertexes: 0, bufferTextureWidth: 0, bufferTextureHeight: 0, stream: null, centerAndScaleData: null, covAndColorData: null, covAndColorTexture: null, centerAndScaleTexture: null, onProgress }; load(shared).then(onLoad).catch((e2) => { onError == null || onError(e2); shared.manager.itemError(shared.url); }); } }; async function load(shared) { shared.manager.itemStart(shared.url); const data = await fetch(shared.url); if (data.body === null) throw "Failed to fetch file"; let _totalDownloadBytes = data.headers.get("Content-Length"); const totalDownloadBytes = _totalDownloadBytes ? parseInt(_totalDownloadBytes) : void 0; if (totalDownloadBytes == void 0) throw "Failed to get content length"; shared.stream = data.body.getReader(); shared.totalDownloadBytes = totalDownloadBytes; shared.numVertices = Math.floor(shared.totalDownloadBytes / shared.rowLength); const context12 = shared.gl.getContext(); let maxTextureSize = context12.getParameter(context12.MAX_TEXTURE_SIZE); shared.maxVertexes = maxTextureSize * maxTextureSize; if (shared.numVertices > shared.maxVertexes) shared.numVertices = shared.maxVertexes; shared.bufferTextureWidth = maxTextureSize; shared.bufferTextureHeight = Math.floor((shared.numVertices - 1) / maxTextureSize) + 1; shared.centerAndScaleData = new Float32Array(shared.bufferTextureWidth * shared.bufferTextureHeight * 4); shared.covAndColorData = new Uint32Array(shared.bufferTextureWidth * shared.bufferTextureHeight * 4); shared.centerAndScaleTexture = new DataTexture(shared.centerAndScaleData, shared.bufferTextureWidth, shared.bufferTextureHeight, RGBAFormat, FloatType); shared.centerAndScaleTexture.needsUpdate = true; shared.covAndColorTexture = new DataTexture(shared.covAndColorData, shared.bufferTextureWidth, shared.bufferTextureHeight, RGBAIntegerFormat, UnsignedIntType); shared.covAndColorTexture.internalFormat = "RGBA32UI"; shared.covAndColorTexture.needsUpdate = true; return shared; } async function lazyLoad(shared) { shared.loading = true; let bytesDownloaded = 0; let bytesProcessed = 0; const chunks = []; let lastReportedProgress = 0; const lengthComputable = shared.totalDownloadBytes !== 0; while (true) { try { const { value, done } = await shared.stream.read(); if (done) break; bytesDownloaded += value.length; if (shared.totalDownloadBytes != void 0) { const percent = bytesDownloaded / shared.totalDownloadBytes * 100; if (shared.onProgress && percent - lastReportedProgress > 1) { const event = new ProgressEvent("progress", { lengthComputable, loaded: bytesDownloaded, total: shared.totalDownloadBytes }); shared.onProgress(event); lastReportedProgress = percent; } } chunks.push(value); const bytesRemains = bytesDownloaded - bytesProcessed; if (shared.totalDownloadBytes != void 0 && bytesRemains > shared.rowLength * shared.chunkSize) { let vertexCount = Math.floor(bytesRemains / shared.rowLength); const concatenatedChunksbuffer = new Uint8Array(bytesRemains); let offset = 0; for (const chunk of chunks) { concatenatedChunksbuffer.set(chunk, offset); offset += chunk.length; } chunks.length = 0; if (bytesRemains > vertexCount * shared.rowLength) { const extra_data = new Uint8Array(bytesRemains - vertexCount * shared.rowLength); extra_data.set(concatenatedChunksbuffer.subarray(bytesRemains - extra_data.length, bytesRemains), 0); chunks.push(extra_data); } const buffer2 = new Uint8Array(vertexCount * shared.rowLength); buffer2.set(concatenatedChunksbuffer.subarray(0, buffer2.byteLength), 0); const matrices = pushDataBuffer(shared, buffer2.buffer, vertexCount); shared.worker.postMessage({ method: "push", src: shared.url, length: shared.numVertices * 16, matrices: matrices.buffer }, [matrices.buffer]); bytesProcessed += vertexCount * shared.rowLength; if (shared.onProgress) { const event = new ProgressEvent("progress", { lengthComputable, loaded: shared.totalDownloadBytes, total: shared.totalDownloadBytes }); shared.onProgress(event); } } } catch (error) { console.error(error); break; } } if (bytesDownloaded - bytesProcessed > 0) { let concatenatedChunks = new Uint8Array(chunks.reduce((acc, chunk) => acc + chunk.length, 0)); let offset = 0; for (const chunk of chunks) { concatenatedChunks.set(chunk, offset); offset += chunk.length; } let numVertices = Math.floor(concatenatedChunks.byteLength / shared.rowLength); const matrices = pushDataBuffer(shared, concatenatedChunks.buffer, numVertices); shared.worker.postMessage({ method: "push", src: shared.url, length: numVertices * 16, matrices: matrices.buffer }, [matrices.buffer]); } shared.loaded = true; shared.manager.itemEnd(shared.url); } function update(camera, shared, target2, hashed) { camera.updateMatrixWorld(); shared.gl.getCurrentViewport(target2.viewport); target2.material.viewport.x = target2.viewport.z; target2.material.viewport.y = target2.viewport.w; target2.material.focal = target2.viewport.w / 2 * Math.abs(camera.projectionMatrix.elements[5]); if (target2.ready) { if (hashed && target2.sorted) return; target2.ready = false; const view = new Float32Array([target2.modelViewMatrix.elements[2], -target2.modelViewMatrix.elements[6], target2.modelViewMatrix.elements[10], target2.modelViewMatrix.elements[14]]); shared.worker.postMessage({ method: "sort", src: shared.url, key: target2.uuid, view: view.buffer, hashed }, [view.buffer]); if (hashed && shared.loaded) target2.sorted = true; } } function connect(shared, target2) { if (!shared.loading) lazyLoad(shared); target2.ready = false; target2.pm = new Matrix4(); target2.vm1 = new Matrix4(); target2.vm2 = new Matrix4(); target2.viewport = new Vector4(); let splatIndexArray = new Uint32Array(shared.bufferTextureWidth * shared.bufferTextureHeight); const splatIndexes = new InstancedBufferAttribute(splatIndexArray, 1, false); splatIndexes.setUsage(DynamicDrawUsage); const geometry3 = target2.geometry = new InstancedBufferGeometry(); const positionsArray = new Float32Array(6 * 3); const positions = new BufferAttribute(positionsArray, 3); geometry3.setAttribute("position", positions); positions.setXYZ(2, -2, 2, 0); positions.setXYZ(1, 2, 2, 0); positions.setXYZ(0, -2, -2, 0); positions.setXYZ(5, -2, -2, 0); positions.setXYZ(4, 2, 2, 0); positions.setXYZ(3, 2, -2, 0); positions.needsUpdate = true; geometry3.setAttribute("splatIndex", splatIndexes); geometry3.instanceCount = 1; function listener(e2) { if (target2 && e2.data.key === target2.uuid) { let indexes = new Uint32Array(e2.data.indices); geometry3.attributes.splatIndex.set(indexes); geometry3.attributes.splatIndex.needsUpdate = true; geometry3.instanceCount = indexes.length; target2.ready = true; } } shared.worker.addEventListener("message", listener); async function wait() { while (true) { const centerAndScaleTextureProperties = shared.gl.properties.get(shared.centerAndScaleTexture); const covAndColorTextureProperties = shared.gl.properties.get(shared.covAndColorTexture); if (centerAndScaleTextureProperties != null && centerAndScaleTextureProperties.__webglTexture && covAndColorTextureProperties != null && covAndColorTextureProperties.__webglTexture && shared.loadedVertexCount > 0) break; await new Promise((resolve) => setTimeout(resolve, 10)); } target2.ready = true; } wait(); return () => shared.worker.removeEventListener("message", listener); } function pushDataBuffer(shared, buffer2, vertexCount) { const context12 = shared.gl.getContext(); if (shared.loadedVertexCount + vertexCount > shared.maxVertexes) vertexCount = shared.maxVertexes - shared.loadedVertexCount; if (vertexCount <= 0) throw "Failed to parse file"; const u_buffer = new Uint8Array(buffer2); const f_buffer = new Float32Array(buffer2); const matrices = new Float32Array(vertexCount * 16); const covAndColorData_uint8 = new Uint8Array(shared.covAndColorData.buffer); const covAndColorData_int16 = new Int16Array(shared.covAndColorData.buffer); for (let i4 = 0; i4 < vertexCount; i4++) { const quat = new Quaternion(-(u_buffer[32 * i4 + 28 + 1] - 128) / 128, (u_buffer[32 * i4 + 28 + 2] - 128) / 128, (u_buffer[32 * i4 + 28 + 3] - 128) / 128, -(u_buffer[32 * i4 + 28 + 0] - 128) / 128); quat.invert(); const center3 = new Vector3(f_buffer[8 * i4 + 0], f_buffer[8 * i4 + 1], -f_buffer[8 * i4 + 2]); const scale5 = new Vector3(f_buffer[8 * i4 + 3 + 0], f_buffer[8 * i4 + 3 + 1], f_buffer[8 * i4 + 3 + 2]); const mtx = new Matrix4(); mtx.makeRotationFromQuaternion(quat); mtx.transpose(); mtx.scale(scale5); const mtx_t = mtx.clone(); mtx.transpose(); mtx.premultiply(mtx_t); mtx.setPosition(center3); const cov_indexes = [0, 1, 2, 5, 6, 10]; let max_value = 0; for (let j = 0; j < cov_indexes.length; j++) if (Math.abs(mtx.elements[cov_indexes[j]]) > max_value) max_value = Math.abs(mtx.elements[cov_indexes[j]]); let destOffset = shared.loadedVertexCount * 4 + i4 * 4; shared.centerAndScaleData[destOffset + 0] = center3.x; shared.centerAndScaleData[destOffset + 1] = -center3.y; shared.centerAndScaleData[destOffset + 2] = center3.z; shared.centerAndScaleData[destOffset + 3] = max_value / 32767; destOffset = shared.loadedVertexCount * 8 + i4 * 4 * 2; for (let j = 0; j < cov_indexes.length; j++) covAndColorData_int16[destOffset + j] = mtx.elements[cov_indexes[j]] * 32767 / max_value; destOffset = shared.loadedVertexCount * 16 + (i4 * 4 + 3) * 4; const col3 = new Color(u_buffer[32 * i4 + 24 + 0] / 255, u_buffer[32 * i4 + 24 + 1] / 255, u_buffer[32 * i4 + 24 + 2] / 255); col3.convertSRGBToLinear(); covAndColorData_uint8[destOffset + 0] = col3.r * 255; covAndColorData_uint8[destOffset + 1] = col3.g * 255; covAndColorData_uint8[destOffset + 2] = col3.b * 255; covAndColorData_uint8[destOffset + 3] = u_buffer[32 * i4 + 24 + 3]; mtx.elements[15] = Math.max(scale5.x, scale5.y, scale5.z) * u_buffer[32 * i4 + 24 + 3] / 255; for (let j = 0; j < 16; j++) matrices[i4 * 16 + j] = mtx.elements[j]; } while (vertexCount > 0) { let width = 0; let height = 0; const xoffset = shared.loadedVertexCount % shared.bufferTextureWidth; const yoffset = Math.floor(shared.loadedVertexCount / shared.bufferTextureWidth); if (shared.loadedVertexCount % shared.bufferTextureWidth != 0) { width = Math.min(shared.bufferTextureWidth, xoffset + vertexCount) - xoffset; height = 1; } else if (Math.floor(vertexCount / shared.bufferTextureWidth) > 0) { width = shared.bufferTextureWidth; height = Math.floor(vertexCount / shared.bufferTextureWidth); } else { width = vertexCount % shared.bufferTextureWidth; height = 1; } const centerAndScaleTextureProperties = shared.gl.properties.get(shared.centerAndScaleTexture); context12.bindTexture(context12.TEXTURE_2D, centerAndScaleTextureProperties.__webglTexture); context12.texSubImage2D(context12.TEXTURE_2D, 0, xoffset, yoffset, width, height, context12.RGBA, context12.FLOAT, shared.centerAndScaleData, shared.loadedVertexCount * 4); const covAndColorTextureProperties = shared.gl.properties.get(shared.covAndColorTexture); context12.bindTexture(context12.TEXTURE_2D, covAndColorTextureProperties.__webglTexture); context12.texSubImage2D( context12.TEXTURE_2D, 0, xoffset, yoffset, width, height, // @ts-ignore context12.RGBA_INTEGER, context12.UNSIGNED_INT, shared.covAndColorData, shared.loadedVertexCount * 4 ); shared.gl.resetState(); shared.loadedVertexCount += width * height; vertexCount -= width * height; } return matrices; } function Splat({ src, toneMapped = false, alphaTest = 0, alphaHash = false, chunkSize = 25e3, ...props }) { extend({ SplatMaterial }); const ref = React38.useRef(null); const gl = useThree((state) => state.gl); const camera = useThree((state) => state.camera); const shared = useLoader(SplatLoader, src, (loader2) => { loader2.gl = gl; loader2.chunkSize = chunkSize; }); React38.useLayoutEffect(() => shared.connect(ref.current), [src]); useFrame(() => shared.update(ref.current, camera, alphaHash)); return React38.createElement("mesh", _extends({ ref, frustumCulled: false }, props), React38.createElement("splatMaterial", { key: `${src}/${alphaTest}/${alphaHash}${SplatMaterial.key}`, transparent: !alphaHash, depthTest: true, alphaTest: alphaHash ? 0 : alphaTest, centerAndScaleTexture: shared.centerAndScaleTexture, covAndColorTexture: shared.covAndColorTexture, depthWrite: alphaHash ? true : alphaTest > 0, blending: alphaHash ? NormalBlending : CustomBlending, blendSrcAlpha: OneFactor, alphaHash: !!alphaHash, toneMapped })); } // node_modules/@react-three/drei/core/OrthographicCamera.js var React40 = __toESM(require_react()); // node_modules/@react-three/drei/core/Fbo.js var React39 = __toESM(require_react()); var import_react9 = __toESM(require_react()); function useFBO(width, height, settings) { const size2 = useThree((state) => state.size); const viewport = useThree((state) => state.viewport); const _width = typeof width === "number" ? width : size2.width * viewport.dpr; const _height = typeof height === "number" ? height : size2.height * viewport.dpr; const _settings = (typeof width === "number" ? settings : width) || {}; const { samples = 0, depth, ...targetSettings } = _settings; const depthBuffer = depth !== null && depth !== void 0 ? depth : _settings.depthBuffer; const target2 = React39.useMemo(() => { const target3 = new WebGLRenderTarget(_width, _height, { minFilter: LinearFilter, magFilter: LinearFilter, type: HalfFloatType, ...targetSettings }); if (depthBuffer) { target3.depthTexture = new DepthTexture(_width, _height, FloatType); } target3.samples = samples; return target3; }, []); React39.useLayoutEffect(() => { target2.setSize(_width, _height); if (samples) target2.samples = samples; }, [samples, target2, _width, _height]); React39.useEffect(() => { return () => target2.dispose(); }, []); return target2; } var Fbo = (0, import_react9.forwardRef)(({ children, width, height, ...settings }, fref) => { const target2 = useFBO(width, height, settings); (0, import_react9.useImperativeHandle)(fref, () => target2, [target2]); return React39.createElement(React39.Fragment, null, children == null ? void 0 : children(target2)); }); // node_modules/@react-three/drei/core/OrthographicCamera.js var isFunction = (node) => typeof node === "function"; var OrthographicCamera2 = React40.forwardRef(({ envMap, resolution = 256, frames = Infinity, children, makeDefault, ...props }, ref) => { const set = useThree(({ set: set2 }) => set2); const camera = useThree(({ camera: camera2 }) => camera2); const size2 = useThree(({ size: size3 }) => size3); const cameraRef = React40.useRef(null); React40.useImperativeHandle(ref, () => cameraRef.current, []); const groupRef = React40.useRef(null); const fbo = useFBO(resolution); React40.useLayoutEffect(() => { if (!props.manual) { cameraRef.current.updateProjectionMatrix(); } }, [size2, props]); React40.useLayoutEffect(() => { cameraRef.current.updateProjectionMatrix(); }); React40.useLayoutEffect(() => { if (makeDefault) { const oldCam = camera; set(() => ({ camera: cameraRef.current })); return () => set(() => ({ camera: oldCam })); } }, [cameraRef, makeDefault, set]); let count = 0; let oldEnvMap = null; const functional = isFunction(children); useFrame((state) => { if (functional && (frames === Infinity || count < frames)) { groupRef.current.visible = false; state.gl.setRenderTarget(fbo); oldEnvMap = state.scene.background; if (envMap) state.scene.background = envMap; state.gl.render(state.scene, cameraRef.current); state.scene.background = oldEnvMap; state.gl.setRenderTarget(null); groupRef.current.visible = true; count++; } }); return React40.createElement(React40.Fragment, null, React40.createElement("orthographicCamera", _extends({ left: size2.width / -2, right: size2.width / 2, top: size2.height / 2, bottom: size2.height / -2, ref: cameraRef }, props), !functional && children), React40.createElement("group", { ref: groupRef }, functional && children(fbo.texture))); }); // node_modules/@react-three/drei/core/PerspectiveCamera.js var React41 = __toESM(require_react()); var isFunction2 = (node) => typeof node === "function"; var PerspectiveCamera2 = React41.forwardRef(({ envMap, resolution = 256, frames = Infinity, makeDefault, children, ...props }, ref) => { const set = useThree(({ set: set2 }) => set2); const camera = useThree(({ camera: camera2 }) => camera2); const size2 = useThree(({ size: size3 }) => size3); const cameraRef = React41.useRef(null); React41.useImperativeHandle(ref, () => cameraRef.current, []); const groupRef = React41.useRef(null); const fbo = useFBO(resolution); React41.useLayoutEffect(() => { if (!props.manual) { cameraRef.current.aspect = size2.width / size2.height; } }, [size2, props]); React41.useLayoutEffect(() => { cameraRef.current.updateProjectionMatrix(); }); let count = 0; let oldEnvMap = null; const functional = isFunction2(children); useFrame((state) => { if (functional && (frames === Infinity || count < frames)) { groupRef.current.visible = false; state.gl.setRenderTarget(fbo); oldEnvMap = state.scene.background; if (envMap) state.scene.background = envMap; state.gl.render(state.scene, cameraRef.current); state.scene.background = oldEnvMap; state.gl.setRenderTarget(null); groupRef.current.visible = true; count++; } }); React41.useLayoutEffect(() => { if (makeDefault) { const oldCam = camera; set(() => ({ camera: cameraRef.current })); return () => set(() => ({ camera: oldCam })); } }, [cameraRef, makeDefault, set]); return React41.createElement(React41.Fragment, null, React41.createElement("perspectiveCamera", _extends({ ref: cameraRef }, props), !functional && children), React41.createElement("group", { ref: groupRef }, functional && children(fbo.texture))); }); // node_modules/@react-three/drei/core/CubeCamera.js var React42 = __toESM(require_react()); var import_react10 = __toESM(require_react()); function useCubeCamera({ resolution = 256, near = 0.1, far = 1e3, envMap, fog } = {}) { const gl = useThree(({ gl: gl2 }) => gl2); const scene = useThree(({ scene: scene2 }) => scene2); const fbo = (0, import_react10.useMemo)(() => { const fbo2 = new WebGLCubeRenderTarget(resolution); fbo2.texture.type = HalfFloatType; return fbo2; }, [resolution]); (0, import_react10.useEffect)(() => { return () => { fbo.dispose(); }; }, [fbo]); const camera = (0, import_react10.useMemo)(() => new CubeCamera(near, far, fbo), [near, far, fbo]); let originalFog; let originalBackground; const update2 = React42.useCallback(() => { originalFog = scene.fog; originalBackground = scene.background; scene.background = envMap || originalBackground; scene.fog = fog || originalFog; camera.update(gl, scene); scene.fog = originalFog; scene.background = originalBackground; }, [gl, scene, camera]); return { fbo, camera, update: update2 }; } function CubeCamera2({ children, frames = Infinity, resolution, near, far, envMap, fog, ...props }) { const ref = React42.useRef(null); const { fbo, camera, update: update2 } = useCubeCamera({ resolution, near, far, envMap, fog }); let count = 0; useFrame(() => { if (ref.current && (frames === Infinity || count < frames)) { ref.current.visible = false; update2(); ref.current.visible = true; count++; } }); return React42.createElement("group", props, React42.createElement("primitive", { object: camera }), React42.createElement("group", { ref }, children == null ? void 0 : children(fbo.texture))); } // node_modules/@react-three/drei/core/DeviceOrientationControls.js var React43 = __toESM(require_react()); var DeviceOrientationControls2 = React43.forwardRef((props, ref) => { const { camera, onChange, makeDefault, ...rest } = props; const defaultCamera = useThree((state) => state.camera); const invalidate = useThree((state) => state.invalidate); const get = useThree((state) => state.get); const set = useThree((state) => state.set); const explCamera = camera || defaultCamera; const controls = React43.useMemo(() => new DeviceOrientationControls(explCamera), [explCamera]); React43.useEffect(() => { const callback = (e2) => { invalidate(); if (onChange) onChange(e2); }; controls == null || controls.addEventListener == null || controls.addEventListener("change", callback); return () => controls == null || controls.removeEventListener == null ? void 0 : controls.removeEventListener("change", callback); }, [onChange, controls, invalidate]); useFrame(() => controls == null ? void 0 : controls.update(), -1); React43.useEffect(() => { const current = controls; current == null || current.connect(); return () => current == null ? void 0 : current.dispose(); }, [controls]); React43.useEffect(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); return controls ? React43.createElement("primitive", _extends({ ref, object: controls }, rest)) : null; }); // node_modules/@react-three/drei/core/FlyControls.js var React44 = __toESM(require_react()); var FlyControls2 = React44.forwardRef(({ domElement, ...props }, fref) => { const { onChange, makeDefault, ...rest } = props; const invalidate = useThree((state) => state.invalidate); const camera = useThree((state) => state.camera); const gl = useThree((state) => state.gl); const events = useThree((state) => state.events); const get = useThree((state) => state.get); const set = useThree((state) => state.set); const explDomElement = domElement || events.connected || gl.domElement; const controls = React44.useMemo(() => new FlyControls(camera), [camera]); React44.useEffect(() => { controls.connect(explDomElement); return () => void controls.dispose(); }, [explDomElement, controls, invalidate]); React44.useEffect(() => { const callback = (e2) => { invalidate(); if (onChange) onChange(e2); }; controls.addEventListener == null || controls.addEventListener("change", callback); return () => controls.removeEventListener == null ? void 0 : controls.removeEventListener("change", callback); }, [onChange, invalidate]); React44.useEffect(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); useFrame((_, delta) => controls.update(delta)); return React44.createElement("primitive", _extends({ ref: fref, object: controls, args: [camera, explDomElement] }, rest)); }); // node_modules/@react-three/drei/core/MapControls.js var React45 = __toESM(require_react()); var MapControls2 = React45.forwardRef((props = { enableDamping: true }, ref) => { const { domElement, camera, makeDefault, onChange, onStart, onEnd, ...rest } = props; const invalidate = useThree((state) => state.invalidate); const defaultCamera = useThree((state) => state.camera); const gl = useThree((state) => state.gl); const events = useThree((state) => state.events); const set = useThree((state) => state.set); const get = useThree((state) => state.get); const explDomElement = domElement || events.connected || gl.domElement; const explCamera = camera || defaultCamera; const controls = React45.useMemo(() => new MapControls(explCamera), [explCamera]); React45.useEffect(() => { controls.connect(explDomElement); const callback = (e2) => { invalidate(); if (onChange) onChange(e2); }; controls.addEventListener("change", callback); if (onStart) controls.addEventListener("start", onStart); if (onEnd) controls.addEventListener("end", onEnd); return () => { controls.dispose(); controls.removeEventListener("change", callback); if (onStart) controls.removeEventListener("start", onStart); if (onEnd) controls.removeEventListener("end", onEnd); }; }, [onChange, onStart, onEnd, controls, invalidate, explDomElement]); React45.useEffect(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); useFrame(() => controls.update(), -1); return React45.createElement("primitive", _extends({ ref, object: controls, enableDamping: true }, rest)); }); // node_modules/@react-three/drei/core/OrbitControls.js var React46 = __toESM(require_react()); var OrbitControls2 = React46.forwardRef(({ makeDefault, camera, regress, domElement, enableDamping = true, keyEvents = false, onChange, onStart, onEnd, ...restProps }, ref) => { const invalidate = useThree((state) => state.invalidate); const defaultCamera = useThree((state) => state.camera); const gl = useThree((state) => state.gl); const events = useThree((state) => state.events); const setEvents = useThree((state) => state.setEvents); const set = useThree((state) => state.set); const get = useThree((state) => state.get); const performance2 = useThree((state) => state.performance); const explCamera = camera || defaultCamera; const explDomElement = domElement || events.connected || gl.domElement; const controls = React46.useMemo(() => new OrbitControls(explCamera), [explCamera]); useFrame(() => { if (controls.enabled) controls.update(); }, -1); React46.useEffect(() => { if (keyEvents) { controls.connect(keyEvents === true ? explDomElement : keyEvents); } controls.connect(explDomElement); return () => void controls.dispose(); }, [keyEvents, explDomElement, regress, controls, invalidate]); React46.useEffect(() => { const callback = (e2) => { invalidate(); if (regress) performance2.regress(); if (onChange) onChange(e2); }; const onStartCb = (e2) => { if (onStart) onStart(e2); }; const onEndCb = (e2) => { if (onEnd) onEnd(e2); }; controls.addEventListener("change", callback); controls.addEventListener("start", onStartCb); controls.addEventListener("end", onEndCb); return () => { controls.removeEventListener("start", onStartCb); controls.removeEventListener("end", onEndCb); controls.removeEventListener("change", callback); }; }, [onChange, onStart, onEnd, controls, invalidate, setEvents]); React46.useEffect(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); return React46.createElement("primitive", _extends({ ref, object: controls, enableDamping }, restProps)); }); // node_modules/@react-three/drei/core/TrackballControls.js var React47 = __toESM(require_react()); var TrackballControls2 = React47.forwardRef(({ makeDefault, camera, domElement, regress, onChange, onStart, onEnd, ...restProps }, ref) => { const { invalidate, camera: defaultCamera, gl, events, set, get, performance: performance2, viewport } = useThree(); const explCamera = camera || defaultCamera; const explDomElement = domElement || events.connected || gl.domElement; const controls = React47.useMemo(() => new TrackballControls(explCamera), [explCamera]); useFrame(() => { if (controls.enabled) controls.update(); }, -1); React47.useEffect(() => { controls.connect(explDomElement); return () => void controls.dispose(); }, [explDomElement, regress, controls, invalidate]); React47.useEffect(() => { const callback = (e2) => { invalidate(); if (regress) performance2.regress(); if (onChange) onChange(e2); }; controls.addEventListener("change", callback); if (onStart) controls.addEventListener("start", onStart); if (onEnd) controls.addEventListener("end", onEnd); return () => { if (onStart) controls.removeEventListener("start", onStart); if (onEnd) controls.removeEventListener("end", onEnd); controls.removeEventListener("change", callback); }; }, [onChange, onStart, onEnd, controls, invalidate]); React47.useEffect(() => { controls.handleResize(); }, [viewport]); React47.useEffect(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); return React47.createElement("primitive", _extends({ ref, object: controls }, restProps)); }); // node_modules/@react-three/drei/core/ArcballControls.js var React48 = __toESM(require_react()); var import_react11 = __toESM(require_react()); var ArcballControls2 = (0, import_react11.forwardRef)(({ camera, makeDefault, regress, domElement, onChange, onStart, onEnd, ...restProps }, ref) => { const invalidate = useThree((state) => state.invalidate); const defaultCamera = useThree((state) => state.camera); const gl = useThree((state) => state.gl); const events = useThree((state) => state.events); const set = useThree((state) => state.set); const get = useThree((state) => state.get); const performance2 = useThree((state) => state.performance); const explCamera = camera || defaultCamera; const explDomElement = domElement || events.connected || gl.domElement; const controls = (0, import_react11.useMemo)(() => new ArcballControls(explCamera), [explCamera]); useFrame(() => { if (controls.enabled) controls.update(); }, -1); (0, import_react11.useEffect)(() => { controls.connect(explDomElement); return () => void controls.dispose(); }, [explDomElement, regress, controls, invalidate]); (0, import_react11.useEffect)(() => { const callback = (e2) => { invalidate(); if (regress) performance2.regress(); if (onChange) onChange(e2); }; controls.addEventListener("change", callback); if (onStart) controls.addEventListener("start", onStart); if (onEnd) controls.addEventListener("end", onEnd); return () => { controls.removeEventListener("change", callback); if (onStart) controls.removeEventListener("start", onStart); if (onEnd) controls.removeEventListener("end", onEnd); }; }, [onChange, onStart, onEnd]); (0, import_react11.useEffect)(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); return React48.createElement("primitive", _extends({ ref, object: controls }, restProps)); }); // node_modules/@react-three/drei/core/TransformControls.js var React49 = __toESM(require_react()); var TransformControls2 = React49.forwardRef(({ children, domElement, onChange, onMouseDown, onMouseUp, onObjectChange, object, makeDefault, camera, // Transform enabled, axis, mode, translationSnap, rotationSnap, scaleSnap, space, size: size2, showX, showY, showZ, ...props }, ref) => { const defaultControls = useThree((state) => state.controls); const gl = useThree((state) => state.gl); const events = useThree((state) => state.events); const defaultCamera = useThree((state) => state.camera); const invalidate = useThree((state) => state.invalidate); const get = useThree((state) => state.get); const set = useThree((state) => state.set); const explCamera = camera || defaultCamera; const explDomElement = domElement || events.connected || gl.domElement; const controls = React49.useMemo(() => new TransformControls(explCamera, explDomElement), [explCamera, explDomElement]); const group = React49.useRef(null); React49.useLayoutEffect(() => { if (object) { controls.attach(object instanceof Object3D ? object : object.current); } else if (group.current instanceof Object3D) { controls.attach(group.current); } return () => void controls.detach(); }, [object, children, controls]); React49.useEffect(() => { if (defaultControls) { const callback = (event) => defaultControls.enabled = !event.value; controls.addEventListener("dragging-changed", callback); return () => controls.removeEventListener("dragging-changed", callback); } }, [controls, defaultControls]); const onChangeRef = React49.useRef(void 0); const onMouseDownRef = React49.useRef(void 0); const onMouseUpRef = React49.useRef(void 0); const onObjectChangeRef = React49.useRef(void 0); React49.useLayoutEffect(() => void (onChangeRef.current = onChange), [onChange]); React49.useLayoutEffect(() => void (onMouseDownRef.current = onMouseDown), [onMouseDown]); React49.useLayoutEffect(() => void (onMouseUpRef.current = onMouseUp), [onMouseUp]); React49.useLayoutEffect(() => void (onObjectChangeRef.current = onObjectChange), [onObjectChange]); React49.useEffect(() => { const onChange2 = (e2) => { invalidate(); onChangeRef.current == null || onChangeRef.current(e2); }; const onMouseDown2 = (e2) => onMouseDownRef.current == null ? void 0 : onMouseDownRef.current(e2); const onMouseUp2 = (e2) => onMouseUpRef.current == null ? void 0 : onMouseUpRef.current(e2); const onObjectChange2 = (e2) => onObjectChangeRef.current == null ? void 0 : onObjectChangeRef.current(e2); controls.addEventListener("change", onChange2); controls.addEventListener("mouseDown", onMouseDown2); controls.addEventListener("mouseUp", onMouseUp2); controls.addEventListener("objectChange", onObjectChange2); return () => { controls.removeEventListener("change", onChange2); controls.removeEventListener("mouseDown", onMouseDown2); controls.removeEventListener("mouseUp", onMouseUp2); controls.removeEventListener("objectChange", onObjectChange2); }; }, [invalidate, controls]); React49.useEffect(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); return React49.createElement(React49.Fragment, null, React49.createElement("primitive", { ref, object: controls, enabled, axis, mode, translationSnap, rotationSnap, scaleSnap, space, size: size2, showX, showY, showZ }), React49.createElement("group", _extends({ ref: group }, props), children)); }); // node_modules/@react-three/drei/core/PointerLockControls.js var React50 = __toESM(require_react()); var PointerLockControls2 = React50.forwardRef(({ domElement, selector, onChange, onLock, onUnlock, enabled = true, makeDefault, ...props }, ref) => { const { camera, ...rest } = props; const setEvents = useThree((state) => state.setEvents); const gl = useThree((state) => state.gl); const defaultCamera = useThree((state) => state.camera); const invalidate = useThree((state) => state.invalidate); const events = useThree((state) => state.events); const get = useThree((state) => state.get); const set = useThree((state) => state.set); const explCamera = camera || defaultCamera; const explDomElement = domElement || events.connected || gl.domElement; const controls = React50.useMemo(() => new PointerLockControls(explCamera), [explCamera]); React50.useEffect(() => { if (enabled) { controls.connect(explDomElement); const oldComputeOffsets = get().events.compute; setEvents({ compute(event, state) { const offsetX = state.size.width / 2; const offsetY = state.size.height / 2; state.pointer.set(offsetX / state.size.width * 2 - 1, -(offsetY / state.size.height) * 2 + 1); state.raycaster.setFromCamera(state.pointer, state.camera); } }); return () => { controls.disconnect(); setEvents({ compute: oldComputeOffsets }); }; } }, [enabled, controls]); React50.useEffect(() => { const callback = (e2) => { invalidate(); if (onChange) onChange(e2); }; controls.addEventListener("change", callback); if (onLock) controls.addEventListener("lock", onLock); if (onUnlock) controls.addEventListener("unlock", onUnlock); const handler = () => controls.lock(); const elements = selector ? Array.from(document.querySelectorAll(selector)) : [document]; elements.forEach((element) => element && element.addEventListener("click", handler)); return () => { controls.removeEventListener("change", callback); if (onLock) controls.removeEventListener("lock", onLock); if (onUnlock) controls.removeEventListener("unlock", onUnlock); elements.forEach((element) => element ? element.removeEventListener("click", handler) : void 0); }; }, [onChange, onLock, onUnlock, selector, controls, invalidate]); React50.useEffect(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); return React50.createElement("primitive", _extends({ ref, object: controls }, rest)); }); // node_modules/@react-three/drei/core/FirstPersonControls.js var React51 = __toESM(require_react()); var FirstPersonControls2 = React51.forwardRef(({ domElement, makeDefault, ...props }, ref) => { const camera = useThree((state) => state.camera); const gl = useThree((state) => state.gl); const events = useThree((state) => state.events); const get = useThree((state) => state.get); const set = useThree((state) => state.set); const explDomElement = domElement || events.connected || gl.domElement; const [controls] = React51.useState(() => new FirstPersonControls(camera, explDomElement)); React51.useEffect(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); useFrame((_, delta) => { controls.update(delta); }, -1); return controls ? React51.createElement("primitive", _extends({ ref, object: controls }, props)) : null; }); // node_modules/@react-three/drei/core/CameraControls.js var React52 = __toESM(require_react()); var import_react12 = __toESM(require_react()); // node_modules/camera-controls/dist/camera-controls.module.js var MOUSE_BUTTON = { LEFT: 1, RIGHT: 2, MIDDLE: 4 }; var ACTION = Object.freeze({ NONE: 0, ROTATE: 1, TRUCK: 2, SCREEN_PAN: 4, OFFSET: 8, DOLLY: 16, ZOOM: 32, TOUCH_ROTATE: 64, TOUCH_TRUCK: 128, TOUCH_SCREEN_PAN: 256, TOUCH_OFFSET: 512, TOUCH_DOLLY: 1024, TOUCH_ZOOM: 2048, TOUCH_DOLLY_TRUCK: 4096, TOUCH_DOLLY_SCREEN_PAN: 8192, TOUCH_DOLLY_OFFSET: 16384, TOUCH_DOLLY_ROTATE: 32768, TOUCH_ZOOM_TRUCK: 65536, TOUCH_ZOOM_OFFSET: 131072, TOUCH_ZOOM_SCREEN_PAN: 262144, TOUCH_ZOOM_ROTATE: 524288 }); var DOLLY_DIRECTION = { NONE: 0, IN: 1, OUT: -1 }; function isPerspectiveCamera(camera) { return camera.isPerspectiveCamera; } function isOrthographicCamera(camera) { return camera.isOrthographicCamera; } var PI_2 = Math.PI * 2; var PI_HALF = Math.PI / 2; var EPSILON = 1e-5; var DEG2RAD = Math.PI / 180; function clamp3(value, min, max2) { return Math.max(min, Math.min(max2, value)); } function approxZero(number, error = EPSILON) { return Math.abs(number) < error; } function approxEquals(a6, b5, error = EPSILON) { return approxZero(a6 - b5, error); } function roundToStep(value, step) { return Math.round(value / step) * step; } function infinityToMaxNumber(value) { if (isFinite(value)) return value; if (value < 0) return -Number.MAX_VALUE; return Number.MAX_VALUE; } function maxNumberToInfinity(value) { if (Math.abs(value) < Number.MAX_VALUE) return value; return value * Infinity; } function smoothDamp(current, target2, currentVelocityRef, smoothTime, maxSpeed = Infinity, deltaTime) { smoothTime = Math.max(1e-4, smoothTime); const omega = 2 / smoothTime; const x = omega * deltaTime; const exp3 = 1 / (1 + x + 0.48 * x * x + 0.235 * x * x * x); let change = current - target2; const originalTo = target2; const maxChange = maxSpeed * smoothTime; change = clamp3(change, -maxChange, maxChange); target2 = current - change; const temp5 = (currentVelocityRef.value + omega * change) * deltaTime; currentVelocityRef.value = (currentVelocityRef.value - omega * temp5) * exp3; let output = target2 + (change + temp5) * exp3; if (originalTo - current > 0 === output > originalTo) { output = originalTo; currentVelocityRef.value = (output - originalTo) / deltaTime; } return output; } function smoothDampVec3(current, target2, currentVelocityRef, smoothTime, maxSpeed = Infinity, deltaTime, out7) { smoothTime = Math.max(1e-4, smoothTime); const omega = 2 / smoothTime; const x = omega * deltaTime; const exp3 = 1 / (1 + x + 0.48 * x * x + 0.235 * x * x * x); let targetX = target2.x; let targetY = target2.y; let targetZ = target2.z; let changeX = current.x - targetX; let changeY = current.y - targetY; let changeZ = current.z - targetZ; const originalToX = targetX; const originalToY = targetY; const originalToZ = targetZ; const maxChange = maxSpeed * smoothTime; const maxChangeSq = maxChange * maxChange; const magnitudeSq = changeX * changeX + changeY * changeY + changeZ * changeZ; if (magnitudeSq > maxChangeSq) { const magnitude = Math.sqrt(magnitudeSq); changeX = changeX / magnitude * maxChange; changeY = changeY / magnitude * maxChange; changeZ = changeZ / magnitude * maxChange; } targetX = current.x - changeX; targetY = current.y - changeY; targetZ = current.z - changeZ; const tempX = (currentVelocityRef.x + omega * changeX) * deltaTime; const tempY = (currentVelocityRef.y + omega * changeY) * deltaTime; const tempZ = (currentVelocityRef.z + omega * changeZ) * deltaTime; currentVelocityRef.x = (currentVelocityRef.x - omega * tempX) * exp3; currentVelocityRef.y = (currentVelocityRef.y - omega * tempY) * exp3; currentVelocityRef.z = (currentVelocityRef.z - omega * tempZ) * exp3; out7.x = targetX + (changeX + tempX) * exp3; out7.y = targetY + (changeY + tempY) * exp3; out7.z = targetZ + (changeZ + tempZ) * exp3; const origMinusCurrentX = originalToX - current.x; const origMinusCurrentY = originalToY - current.y; const origMinusCurrentZ = originalToZ - current.z; const outMinusOrigX = out7.x - originalToX; const outMinusOrigY = out7.y - originalToY; const outMinusOrigZ = out7.z - originalToZ; if (origMinusCurrentX * outMinusOrigX + origMinusCurrentY * outMinusOrigY + origMinusCurrentZ * outMinusOrigZ > 0) { out7.x = originalToX; out7.y = originalToY; out7.z = originalToZ; currentVelocityRef.x = (out7.x - originalToX) / deltaTime; currentVelocityRef.y = (out7.y - originalToY) / deltaTime; currentVelocityRef.z = (out7.z - originalToZ) / deltaTime; } return out7; } function extractClientCoordFromEvent(pointers, out7) { out7.set(0, 0); pointers.forEach((pointer) => { out7.x += pointer.clientX; out7.y += pointer.clientY; }); out7.x /= pointers.length; out7.y /= pointers.length; } function notSupportedInOrthographicCamera(camera, message) { if (isOrthographicCamera(camera)) { console.warn(`${message} is not supported in OrthographicCamera`); return true; } return false; } var EventDispatcher3 = class { _listeners = {}; /** * Adds the specified event listener. * @param type event name * @param listener handler function * @category Methods */ addEventListener(type, listener) { const listeners = this._listeners; if (listeners[type] === void 0) listeners[type] = []; if (listeners[type].indexOf(listener) === -1) listeners[type].push(listener); } /** * Presence of the specified event listener. * @param type event name * @param listener handler function * @category Methods */ hasEventListener(type, listener) { const listeners = this._listeners; return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1; } /** * Removes the specified event listener * @param type event name * @param listener handler function * @category Methods */ removeEventListener(type, listener) { const listeners = this._listeners; const listenerArray = listeners[type]; if (listenerArray !== void 0) { const index2 = listenerArray.indexOf(listener); if (index2 !== -1) listenerArray.splice(index2, 1); } } /** * Removes all event listeners * @param type event name * @category Methods */ removeAllEventListeners(type) { if (!type) { this._listeners = {}; return; } if (Array.isArray(this._listeners[type])) this._listeners[type].length = 0; } /** * Fire an event type. * @param event DispatcherEvent * @category Methods */ dispatchEvent(event) { const listeners = this._listeners; const listenerArray = listeners[event.type]; if (listenerArray !== void 0) { event.target = this; const array = listenerArray.slice(0); for (let i4 = 0, l2 = array.length; i4 < l2; i4++) { array[i4].call(this, event); } } } }; var VERSION = "3.1.2"; var TOUCH_DOLLY_FACTOR = 1 / 8; var isMac = /Mac/.test(globalThis?.navigator?.platform); var THREE; var _ORIGIN; var _AXIS_Y; var _AXIS_Z; var _v25; var _v3A; var _v3B; var _v3C; var _cameraDirection; var _xColumn; var _yColumn; var _zColumn; var _deltaTarget; var _deltaOffset; var _sphericalA; var _sphericalB; var _box3A; var _box3B; var _sphere3; var _quaternionA; var _quaternionB; var _rotationMatrix; var _raycaster; var CameraControls2 = class _CameraControls extends EventDispatcher3 { /** * Injects THREE as the dependency. You can then proceed to use CameraControls. * * e.g * ```javascript * CameraControls.install( { THREE: THREE } ); * ``` * * Note: If you do not wish to use enter three.js to reduce file size(tree-shaking for example), make a subset to install. * * ```js * import { * Vector2, * Vector3, * Vector4, * Quaternion, * Matrix4, * Spherical, * Box3, * Sphere, * Raycaster, * MathUtils, * } from 'three'; * * const subsetOfTHREE = { * Vector2 : Vector2, * Vector3 : Vector3, * Vector4 : Vector4, * Quaternion: Quaternion, * Matrix4 : Matrix4, * Spherical : Spherical, * Box3 : Box3, * Sphere : Sphere, * Raycaster : Raycaster, * }; * CameraControls.install( { THREE: subsetOfTHREE } ); * ``` * @category Statics */ static install(libs) { THREE = libs.THREE; _ORIGIN = Object.freeze(new THREE.Vector3(0, 0, 0)); _AXIS_Y = Object.freeze(new THREE.Vector3(0, 1, 0)); _AXIS_Z = Object.freeze(new THREE.Vector3(0, 0, 1)); _v25 = new THREE.Vector2(); _v3A = new THREE.Vector3(); _v3B = new THREE.Vector3(); _v3C = new THREE.Vector3(); _cameraDirection = new THREE.Vector3(); _xColumn = new THREE.Vector3(); _yColumn = new THREE.Vector3(); _zColumn = new THREE.Vector3(); _deltaTarget = new THREE.Vector3(); _deltaOffset = new THREE.Vector3(); _sphericalA = new THREE.Spherical(); _sphericalB = new THREE.Spherical(); _box3A = new THREE.Box3(); _box3B = new THREE.Box3(); _sphere3 = new THREE.Sphere(); _quaternionA = new THREE.Quaternion(); _quaternionB = new THREE.Quaternion(); _rotationMatrix = new THREE.Matrix4(); _raycaster = new THREE.Raycaster(); } /** * list all ACTIONs * @category Statics */ static get ACTION() { return ACTION; } /** * Minimum vertical angle in radians. * The angle has to be between `0` and `.maxPolarAngle` inclusive. * The default value is `0`. * * e.g. * ``` * cameraControls.maxPolarAngle = 0; * ``` * @category Properties */ minPolarAngle = 0; // radians /** * Maximum vertical angle in radians. * The angle has to be between `.maxPolarAngle` and `Math.PI` inclusive. * The default value is `Math.PI`. * * e.g. * ``` * cameraControls.maxPolarAngle = Math.PI; * ``` * @category Properties */ maxPolarAngle = Math.PI; // radians /** * Minimum horizontal angle in radians. * The angle has to be less than `.maxAzimuthAngle`. * The default value is `- Infinity`. * * e.g. * ``` * cameraControls.minAzimuthAngle = - Infinity; * ``` * @category Properties */ minAzimuthAngle = -Infinity; // radians /** * Maximum horizontal angle in radians. * The angle has to be greater than `.minAzimuthAngle`. * The default value is `Infinity`. * * e.g. * ``` * cameraControls.maxAzimuthAngle = Infinity; * ``` * @category Properties */ maxAzimuthAngle = Infinity; // radians // How far you can dolly in and out ( PerspectiveCamera only ) /** * Minimum distance for dolly. The value must be higher than `0`. Default is `Number.EPSILON`. * PerspectiveCamera only. * @category Properties */ minDistance = Number.EPSILON; /** * Maximum distance for dolly. The value must be higher than `minDistance`. Default is `Infinity`. * PerspectiveCamera only. * @category Properties */ maxDistance = Infinity; /** * `true` to enable Infinity Dolly for wheel and pinch. Use this with `minDistance` and `maxDistance` * If the Dolly distance is less (or over) than the `minDistance` (or `maxDistance`), `infinityDolly` will keep the distance and pushes the target position instead. * @category Properties */ infinityDolly = false; /** * Minimum camera zoom. * @category Properties */ minZoom = 0.01; /** * Maximum camera zoom. * @category Properties */ maxZoom = Infinity; /** * Approximate time in seconds to reach the target. A smaller value will reach the target faster. * @category Properties */ smoothTime = 0.25; /** * the smoothTime while dragging * @category Properties */ draggingSmoothTime = 0.125; /** * Max transition speed in unit-per-seconds * @category Properties */ maxSpeed = Infinity; /** * Speed of azimuth (horizontal) rotation. * @category Properties */ azimuthRotateSpeed = 1; /** * Speed of polar (vertical) rotation. * @category Properties */ polarRotateSpeed = 1; /** * Speed of mouse-wheel dollying. * @category Properties */ dollySpeed = 1; /** * `true` to invert direction when dollying or zooming via drag * @category Properties */ dollyDragInverted = false; /** * Speed of drag for truck and pedestal. * @category Properties */ truckSpeed = 2; /** * `true` to enable Dolly-in to the mouse cursor coords. * @category Properties */ dollyToCursor = false; /** * @category Properties */ dragToOffset = false; /** * Friction ratio of the boundary. * @category Properties */ boundaryFriction = 0; /** * Controls how soon the `rest` event fires as the camera slows. * @category Properties */ restThreshold = 0.01; /** * An array of Meshes to collide with camera. * Be aware colliderMeshes may decrease performance. The collision test uses 4 raycasters from the camera since the near plane has 4 corners. * @category Properties */ colliderMeshes = []; // button configs /** * User's mouse input config. * * | button to assign | behavior | * | --------------------- | -------- | * | `mouseButtons.left` | `CameraControls.ACTION.ROTATE`* \| `CameraControls.ACTION.TRUCK` \| `CameraControls.ACTION.OFFSET` \| `CameraControls.ACTION.DOLLY` \| `CameraControls.ACTION.ZOOM` \| `CameraControls.ACTION.NONE` | * | `mouseButtons.right` | `CameraControls.ACTION.ROTATE` \| `CameraControls.ACTION.TRUCK`* \| `CameraControls.ACTION.OFFSET` \| `CameraControls.ACTION.DOLLY` \| `CameraControls.ACTION.ZOOM` \| `CameraControls.ACTION.NONE` | * | `mouseButtons.wheel` ¹ | `CameraControls.ACTION.ROTATE` \| `CameraControls.ACTION.TRUCK` \| `CameraControls.ACTION.OFFSET` \| `CameraControls.ACTION.DOLLY` \| `CameraControls.ACTION.ZOOM` \| `CameraControls.ACTION.NONE` | * | `mouseButtons.middle` ² | `CameraControls.ACTION.ROTATE` \| `CameraControls.ACTION.TRUCK` \| `CameraControls.ACTION.OFFSET` \| `CameraControls.ACTION.DOLLY`* \| `CameraControls.ACTION.ZOOM` \| `CameraControls.ACTION.NONE` | * * 1. Mouse wheel event for scroll "up/down" on mac "up/down/left/right" * 2. Mouse click on wheel event "button" * - \* is the default. * - The default of `mouseButtons.wheel` is: * - `DOLLY` for Perspective camera. * - `ZOOM` for Orthographic camera, and can't set `DOLLY`. * @category Properties */ mouseButtons; /** * User's touch input config. * * | fingers to assign | behavior | * | --------------------- | -------- | * | `touches.one` | `CameraControls.ACTION.TOUCH_ROTATE`* \| `CameraControls.ACTION.TOUCH_TRUCK` \| `CameraControls.ACTION.TOUCH_OFFSET` \| `CameraControls.ACTION.DOLLY` | `CameraControls.ACTION.ZOOM` | `CameraControls.ACTION.NONE` | * | `touches.two` | `ACTION.TOUCH_DOLLY_TRUCK` \| `ACTION.TOUCH_DOLLY_OFFSET` \| `ACTION.TOUCH_DOLLY_ROTATE` \| `ACTION.TOUCH_ZOOM_TRUCK` \| `ACTION.TOUCH_ZOOM_OFFSET` \| `ACTION.TOUCH_ZOOM_ROTATE` \| `ACTION.TOUCH_DOLLY` \| `ACTION.TOUCH_ZOOM` \| `CameraControls.ACTION.TOUCH_ROTATE` \| `CameraControls.ACTION.TOUCH_TRUCK` \| `CameraControls.ACTION.TOUCH_OFFSET` \| `CameraControls.ACTION.NONE` | * | `touches.three` | `ACTION.TOUCH_DOLLY_TRUCK` \| `ACTION.TOUCH_DOLLY_OFFSET` \| `ACTION.TOUCH_DOLLY_ROTATE` \| `ACTION.TOUCH_ZOOM_TRUCK` \| `ACTION.TOUCH_ZOOM_OFFSET` \| `ACTION.TOUCH_ZOOM_ROTATE` \| `CameraControls.ACTION.TOUCH_ROTATE` \| `CameraControls.ACTION.TOUCH_TRUCK` \| `CameraControls.ACTION.TOUCH_OFFSET` \| `CameraControls.ACTION.NONE` | * * - \* is the default. * - The default of `touches.two` and `touches.three` is: * - `TOUCH_DOLLY_TRUCK` for Perspective camera. * - `TOUCH_ZOOM_TRUCK` for Orthographic camera, and can't set `TOUCH_DOLLY_TRUCK` and `TOUCH_DOLLY`. * @category Properties */ touches; /** * Force cancel user dragging. * @category Methods */ // cancel will be overwritten in the constructor. cancel = () => { }; /** * Still an experimental feature. * This could change at any time. * @category Methods */ lockPointer; /** * Still an experimental feature. * This could change at any time. * @category Methods */ unlockPointer; _enabled = true; _camera; _yAxisUpSpace; _yAxisUpSpaceInverse; _state = ACTION.NONE; _domElement; _viewport = null; // the location of focus, where the object orbits around _target; _targetEnd; _focalOffset; _focalOffsetEnd; // rotation and dolly distance _spherical; _sphericalEnd; _lastDistance; _zoom; _zoomEnd; _lastZoom; // reset _cameraUp0; _target0; _position0; _zoom0; _focalOffset0; _dollyControlCoord; _changedDolly = 0; _changedZoom = 0; // collisionTest uses nearPlane. ( PerspectiveCamera only ) _nearPlaneCorners; _hasRested = true; _boundary; _boundaryEnclosesCamera = false; _needsUpdate = true; _updatedLastTime = false; _elementRect = new DOMRect(); _isDragging = false; _dragNeedsUpdate = true; _activePointers = []; _lockedPointer = null; _interactiveArea = new DOMRect(0, 0, 1, 1); // Use draggingSmoothTime over smoothTime while true. // set automatically true on user-dragging start. // set automatically false on programmable methods call. _isUserControllingRotate = false; _isUserControllingDolly = false; _isUserControllingTruck = false; _isUserControllingOffset = false; _isUserControllingZoom = false; _lastDollyDirection = DOLLY_DIRECTION.NONE; // velocities for smoothDamp _thetaVelocity = { value: 0 }; _phiVelocity = { value: 0 }; _radiusVelocity = { value: 0 }; _targetVelocity = new THREE.Vector3(); _focalOffsetVelocity = new THREE.Vector3(); _zoomVelocity = { value: 0 }; /** * @deprecated Use `cameraControls.mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead. */ set verticalDragToForward(_) { console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead."); } /** * Creates a `CameraControls` instance. * * Note: * You **must install** three.js before using camera-controls. see [#install](#install) * Not doing so will lead to runtime errors (`undefined` references to THREE). * * e.g. * ``` * CameraControls.install( { THREE } ); * const cameraControls = new CameraControls( camera, domElement ); * ``` * * @param camera A `THREE.PerspectiveCamera` or `THREE.OrthographicCamera` to be controlled. * @param domElement A `HTMLElement` for the draggable area, usually `renderer.domElement`. * @category Constructor */ constructor(camera, domElement) { super(); if (typeof THREE === "undefined") { console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."); } this._camera = camera; this._yAxisUpSpace = new THREE.Quaternion().setFromUnitVectors(this._camera.up, _AXIS_Y); this._yAxisUpSpaceInverse = this._yAxisUpSpace.clone().invert(); this._state = ACTION.NONE; this._target = new THREE.Vector3(); this._targetEnd = this._target.clone(); this._focalOffset = new THREE.Vector3(); this._focalOffsetEnd = this._focalOffset.clone(); this._spherical = new THREE.Spherical().setFromVector3(_v3A.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)); this._sphericalEnd = this._spherical.clone(); this._lastDistance = this._spherical.radius; this._zoom = this._camera.zoom; this._zoomEnd = this._zoom; this._lastZoom = this._zoom; this._nearPlaneCorners = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ]; this._updateNearPlaneCorners(); this._boundary = new THREE.Box3(new THREE.Vector3(-Infinity, -Infinity, -Infinity), new THREE.Vector3(Infinity, Infinity, Infinity)); this._cameraUp0 = this._camera.up.clone(); this._target0 = this._target.clone(); this._position0 = this._camera.position.clone(); this._zoom0 = this._zoom; this._focalOffset0 = this._focalOffset.clone(); this._dollyControlCoord = new THREE.Vector2(); this.mouseButtons = { left: ACTION.ROTATE, middle: ACTION.DOLLY, right: ACTION.TRUCK, wheel: isPerspectiveCamera(this._camera) ? ACTION.DOLLY : isOrthographicCamera(this._camera) ? ACTION.ZOOM : ACTION.NONE }; this.touches = { one: ACTION.TOUCH_ROTATE, two: isPerspectiveCamera(this._camera) ? ACTION.TOUCH_DOLLY_TRUCK : isOrthographicCamera(this._camera) ? ACTION.TOUCH_ZOOM_TRUCK : ACTION.NONE, three: ACTION.TOUCH_TRUCK }; const dragStartPosition = new THREE.Vector2(); const lastDragPosition = new THREE.Vector2(); const dollyStart = new THREE.Vector2(); const onPointerDown = (event) => { if (!this._enabled || !this._domElement) return; if (this._interactiveArea.left !== 0 || this._interactiveArea.top !== 0 || this._interactiveArea.width !== 1 || this._interactiveArea.height !== 1) { const elRect = this._domElement.getBoundingClientRect(); const left = event.clientX / elRect.width; const top = event.clientY / elRect.height; if (left < this._interactiveArea.left || left > this._interactiveArea.right || top < this._interactiveArea.top || top > this._interactiveArea.bottom) return; } const mouseButton = event.pointerType !== "mouse" ? null : (event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT ? MOUSE_BUTTON.LEFT : (event.buttons & MOUSE_BUTTON.MIDDLE) === MOUSE_BUTTON.MIDDLE ? MOUSE_BUTTON.MIDDLE : (event.buttons & MOUSE_BUTTON.RIGHT) === MOUSE_BUTTON.RIGHT ? MOUSE_BUTTON.RIGHT : null; if (mouseButton !== null) { const zombiePointer = this._findPointerByMouseButton(mouseButton); zombiePointer && this._disposePointer(zombiePointer); } if ((event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT && this._lockedPointer) return; const pointer = { pointerId: event.pointerId, clientX: event.clientX, clientY: event.clientY, deltaX: 0, deltaY: 0, mouseButton }; this._activePointers.push(pointer); this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); this._domElement.ownerDocument.addEventListener("pointermove", onPointerMove, { passive: false }); this._domElement.ownerDocument.addEventListener("pointerup", onPointerUp); this._isDragging = true; startDragging(event); }; const onPointerMove = (event) => { if (event.cancelable) event.preventDefault(); const pointerId2 = event.pointerId; const pointer = this._lockedPointer || this._findPointerById(pointerId2); if (!pointer) return; pointer.clientX = event.clientX; pointer.clientY = event.clientY; pointer.deltaX = event.movementX; pointer.deltaY = event.movementY; this._state = 0; if (event.pointerType === "touch") { switch (this._activePointers.length) { case 1: this._state = this.touches.one; break; case 2: this._state = this.touches.two; break; case 3: this._state = this.touches.three; break; } } else { if (!this._isDragging && this._lockedPointer || this._isDragging && (event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT) { this._state = this._state | this.mouseButtons.left; } if (this._isDragging && (event.buttons & MOUSE_BUTTON.MIDDLE) === MOUSE_BUTTON.MIDDLE) { this._state = this._state | this.mouseButtons.middle; } if (this._isDragging && (event.buttons & MOUSE_BUTTON.RIGHT) === MOUSE_BUTTON.RIGHT) { this._state = this._state | this.mouseButtons.right; } } dragging(); }; const onPointerUp = (event) => { const pointer = this._findPointerById(event.pointerId); if (pointer && pointer === this._lockedPointer) return; pointer && this._disposePointer(pointer); if (event.pointerType === "touch") { switch (this._activePointers.length) { case 0: this._state = ACTION.NONE; break; case 1: this._state = this.touches.one; break; case 2: this._state = this.touches.two; break; case 3: this._state = this.touches.three; break; } } else { this._state = ACTION.NONE; } endDragging(); }; let lastScrollTimeStamp = -1; const onMouseWheel = (event) => { if (!this._domElement) return; if (!this._enabled || this.mouseButtons.wheel === ACTION.NONE) return; if (this._interactiveArea.left !== 0 || this._interactiveArea.top !== 0 || this._interactiveArea.width !== 1 || this._interactiveArea.height !== 1) { const elRect = this._domElement.getBoundingClientRect(); const left = event.clientX / elRect.width; const top = event.clientY / elRect.height; if (left < this._interactiveArea.left || left > this._interactiveArea.right || top < this._interactiveArea.top || top > this._interactiveArea.bottom) return; } event.preventDefault(); if (this.dollyToCursor || this.mouseButtons.wheel === ACTION.ROTATE || this.mouseButtons.wheel === ACTION.TRUCK) { const now2 = performance.now(); if (lastScrollTimeStamp - now2 < 1e3) this._getClientRect(this._elementRect); lastScrollTimeStamp = now2; } const deltaYFactor = isMac ? -1 : -3; const delta = event.deltaMode === 1 && !event.ctrlKey ? event.deltaY / deltaYFactor : event.deltaY / (deltaYFactor * 10); const x = this.dollyToCursor ? (event.clientX - this._elementRect.x) / this._elementRect.width * 2 - 1 : 0; const y = this.dollyToCursor ? (event.clientY - this._elementRect.y) / this._elementRect.height * -2 + 1 : 0; const controlMode = event.ctrlKey ? ACTION.ZOOM : this.mouseButtons.wheel; switch (controlMode) { case ACTION.ROTATE: { this._rotateInternal(event.deltaX, event.deltaY); this._isUserControllingRotate = true; break; } case ACTION.TRUCK: { this._truckInternal(event.deltaX, event.deltaY, false, false); this._isUserControllingTruck = true; break; } case ACTION.SCREEN_PAN: { this._truckInternal(event.deltaX, event.deltaY, false, true); this._isUserControllingTruck = true; break; } case ACTION.OFFSET: { this._truckInternal(event.deltaX, event.deltaY, true, false); this._isUserControllingOffset = true; break; } case ACTION.DOLLY: { this._dollyInternal(-delta, x, y); this._isUserControllingDolly = true; break; } case ACTION.ZOOM: { this._zoomInternal(-delta, x, y); this._isUserControllingZoom = true; break; } } this.dispatchEvent({ type: "control" }); }; const onContextMenu = (event) => { if (!this._domElement || !this._enabled) return; if (this.mouseButtons.right === _CameraControls.ACTION.NONE) { const pointerId2 = event instanceof PointerEvent ? event.pointerId : 0; const pointer = this._findPointerById(pointerId2); pointer && this._disposePointer(pointer); this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); return; } event.preventDefault(); }; const startDragging = (event) => { if (!this._enabled) return; extractClientCoordFromEvent(this._activePointers, _v25); this._getClientRect(this._elementRect); dragStartPosition.copy(_v25); lastDragPosition.copy(_v25); const isMultiTouch = this._activePointers.length >= 2; if (isMultiTouch) { const dx = _v25.x - this._activePointers[1].clientX; const dy = _v25.y - this._activePointers[1].clientY; const distance3 = Math.sqrt(dx * dx + dy * dy); dollyStart.set(0, distance3); const x = (this._activePointers[0].clientX + this._activePointers[1].clientX) * 0.5; const y = (this._activePointers[0].clientY + this._activePointers[1].clientY) * 0.5; lastDragPosition.set(x, y); } this._state = 0; if (!event) { if (this._lockedPointer) this._state = this._state | this.mouseButtons.left; } else if ("pointerType" in event && event.pointerType === "touch") { switch (this._activePointers.length) { case 1: this._state = this.touches.one; break; case 2: this._state = this.touches.two; break; case 3: this._state = this.touches.three; break; } } else { if (!this._lockedPointer && (event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT) { this._state = this._state | this.mouseButtons.left; } if ((event.buttons & MOUSE_BUTTON.MIDDLE) === MOUSE_BUTTON.MIDDLE) { this._state = this._state | this.mouseButtons.middle; } if ((event.buttons & MOUSE_BUTTON.RIGHT) === MOUSE_BUTTON.RIGHT) { this._state = this._state | this.mouseButtons.right; } } if ((this._state & ACTION.ROTATE) === ACTION.ROTATE || (this._state & ACTION.TOUCH_ROTATE) === ACTION.TOUCH_ROTATE || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE || (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) { this._sphericalEnd.theta = this._spherical.theta; this._sphericalEnd.phi = this._spherical.phi; this._thetaVelocity.value = 0; this._phiVelocity.value = 0; } if ((this._state & ACTION.TRUCK) === ACTION.TRUCK || (this._state & ACTION.SCREEN_PAN) === ACTION.SCREEN_PAN || (this._state & ACTION.TOUCH_TRUCK) === ACTION.TOUCH_TRUCK || (this._state & ACTION.TOUCH_SCREEN_PAN) === ACTION.TOUCH_SCREEN_PAN || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_DOLLY_SCREEN_PAN) === ACTION.TOUCH_DOLLY_SCREEN_PAN || (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK || (this._state & ACTION.TOUCH_ZOOM_SCREEN_PAN) === ACTION.TOUCH_DOLLY_SCREEN_PAN) { this._targetEnd.copy(this._target); this._targetVelocity.set(0, 0, 0); } if ((this._state & ACTION.DOLLY) === ACTION.DOLLY || (this._state & ACTION.TOUCH_DOLLY) === ACTION.TOUCH_DOLLY || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_DOLLY_SCREEN_PAN) === ACTION.TOUCH_DOLLY_SCREEN_PAN || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE) { this._sphericalEnd.radius = this._spherical.radius; this._radiusVelocity.value = 0; } if ((this._state & ACTION.ZOOM) === ACTION.ZOOM || (this._state & ACTION.TOUCH_ZOOM) === ACTION.TOUCH_ZOOM || (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK || (this._state & ACTION.TOUCH_ZOOM_SCREEN_PAN) === ACTION.TOUCH_ZOOM_SCREEN_PAN || (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET || (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) { this._zoomEnd = this._zoom; this._zoomVelocity.value = 0; } if ((this._state & ACTION.OFFSET) === ACTION.OFFSET || (this._state & ACTION.TOUCH_OFFSET) === ACTION.TOUCH_OFFSET || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET || (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET) { this._focalOffsetEnd.copy(this._focalOffset); this._focalOffsetVelocity.set(0, 0, 0); } this.dispatchEvent({ type: "controlstart" }); }; const dragging = () => { if (!this._enabled || !this._dragNeedsUpdate) return; this._dragNeedsUpdate = false; extractClientCoordFromEvent(this._activePointers, _v25); const isPointerLockActive = this._domElement && this._domElement.ownerDocument.pointerLockElement === this._domElement; const lockedPointer = isPointerLockActive ? this._lockedPointer || this._activePointers[0] : null; const deltaX = lockedPointer ? -lockedPointer.deltaX : lastDragPosition.x - _v25.x; const deltaY = lockedPointer ? -lockedPointer.deltaY : lastDragPosition.y - _v25.y; lastDragPosition.copy(_v25); if ((this._state & ACTION.ROTATE) === ACTION.ROTATE || (this._state & ACTION.TOUCH_ROTATE) === ACTION.TOUCH_ROTATE || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE || (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) { this._rotateInternal(deltaX, deltaY); this._isUserControllingRotate = true; } if ((this._state & ACTION.DOLLY) === ACTION.DOLLY || (this._state & ACTION.ZOOM) === ACTION.ZOOM) { const dollyX = this.dollyToCursor ? (dragStartPosition.x - this._elementRect.x) / this._elementRect.width * 2 - 1 : 0; const dollyY = this.dollyToCursor ? (dragStartPosition.y - this._elementRect.y) / this._elementRect.height * -2 + 1 : 0; const dollyDirection = this.dollyDragInverted ? -1 : 1; if ((this._state & ACTION.DOLLY) === ACTION.DOLLY) { this._dollyInternal(dollyDirection * deltaY * TOUCH_DOLLY_FACTOR, dollyX, dollyY); this._isUserControllingDolly = true; } else { this._zoomInternal(dollyDirection * deltaY * TOUCH_DOLLY_FACTOR, dollyX, dollyY); this._isUserControllingZoom = true; } } if ((this._state & ACTION.TOUCH_DOLLY) === ACTION.TOUCH_DOLLY || (this._state & ACTION.TOUCH_ZOOM) === ACTION.TOUCH_ZOOM || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK || (this._state & ACTION.TOUCH_DOLLY_SCREEN_PAN) === ACTION.TOUCH_DOLLY_SCREEN_PAN || (this._state & ACTION.TOUCH_ZOOM_SCREEN_PAN) === ACTION.TOUCH_ZOOM_SCREEN_PAN || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET || (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE || (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) { const dx = _v25.x - this._activePointers[1].clientX; const dy = _v25.y - this._activePointers[1].clientY; const distance3 = Math.sqrt(dx * dx + dy * dy); const dollyDelta = dollyStart.y - distance3; dollyStart.set(0, distance3); const dollyX = this.dollyToCursor ? (lastDragPosition.x - this._elementRect.x) / this._elementRect.width * 2 - 1 : 0; const dollyY = this.dollyToCursor ? (lastDragPosition.y - this._elementRect.y) / this._elementRect.height * -2 + 1 : 0; if ((this._state & ACTION.TOUCH_DOLLY) === ACTION.TOUCH_DOLLY || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_DOLLY_SCREEN_PAN) === ACTION.TOUCH_DOLLY_SCREEN_PAN || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET) { this._dollyInternal(dollyDelta * TOUCH_DOLLY_FACTOR, dollyX, dollyY); this._isUserControllingDolly = true; } else { this._zoomInternal(dollyDelta * TOUCH_DOLLY_FACTOR, dollyX, dollyY); this._isUserControllingZoom = true; } } if ((this._state & ACTION.TRUCK) === ACTION.TRUCK || (this._state & ACTION.TOUCH_TRUCK) === ACTION.TOUCH_TRUCK || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK) { this._truckInternal(deltaX, deltaY, false, false); this._isUserControllingTruck = true; } if ((this._state & ACTION.SCREEN_PAN) === ACTION.SCREEN_PAN || (this._state & ACTION.TOUCH_SCREEN_PAN) === ACTION.TOUCH_SCREEN_PAN || (this._state & ACTION.TOUCH_DOLLY_SCREEN_PAN) === ACTION.TOUCH_DOLLY_SCREEN_PAN || (this._state & ACTION.TOUCH_ZOOM_SCREEN_PAN) === ACTION.TOUCH_ZOOM_SCREEN_PAN) { this._truckInternal(deltaX, deltaY, false, true); this._isUserControllingTruck = true; } if ((this._state & ACTION.OFFSET) === ACTION.OFFSET || (this._state & ACTION.TOUCH_OFFSET) === ACTION.TOUCH_OFFSET || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET || (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET) { this._truckInternal(deltaX, deltaY, true, false); this._isUserControllingOffset = true; } this.dispatchEvent({ type: "control" }); }; const endDragging = () => { extractClientCoordFromEvent(this._activePointers, _v25); lastDragPosition.copy(_v25); this._dragNeedsUpdate = false; if (this._activePointers.length === 0 || this._activePointers.length === 1 && this._activePointers[0] === this._lockedPointer) { this._isDragging = false; } if (this._activePointers.length === 0 && this._domElement) { this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); this.dispatchEvent({ type: "controlend" }); } }; this.lockPointer = () => { if (!this._enabled || !this._domElement) return; this.cancel(); this._lockedPointer = { pointerId: -1, clientX: 0, clientY: 0, deltaX: 0, deltaY: 0, mouseButton: null }; this._activePointers.push(this._lockedPointer); this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); this._domElement.requestPointerLock(); this._domElement.ownerDocument.addEventListener("pointerlockchange", onPointerLockChange); this._domElement.ownerDocument.addEventListener("pointerlockerror", onPointerLockError); this._domElement.ownerDocument.addEventListener("pointermove", onPointerMove, { passive: false }); this._domElement.ownerDocument.addEventListener("pointerup", onPointerUp); startDragging(); }; this.unlockPointer = () => { if (this._lockedPointer !== null) { this._disposePointer(this._lockedPointer); this._lockedPointer = null; } this._domElement?.ownerDocument.exitPointerLock(); this._domElement?.ownerDocument.removeEventListener("pointerlockchange", onPointerLockChange); this._domElement?.ownerDocument.removeEventListener("pointerlockerror", onPointerLockError); this.cancel(); }; const onPointerLockChange = () => { const isPointerLockActive = this._domElement && this._domElement.ownerDocument.pointerLockElement === this._domElement; if (!isPointerLockActive) this.unlockPointer(); }; const onPointerLockError = () => { this.unlockPointer(); }; this._addAllEventListeners = (domElement2) => { this._domElement = domElement2; this._domElement.style.touchAction = "none"; this._domElement.style.userSelect = "none"; this._domElement.style.webkitUserSelect = "none"; this._domElement.addEventListener("pointerdown", onPointerDown); this._domElement.addEventListener("pointercancel", onPointerUp); this._domElement.addEventListener("wheel", onMouseWheel, { passive: false }); this._domElement.addEventListener("contextmenu", onContextMenu); }; this._removeAllEventListeners = () => { if (!this._domElement) return; this._domElement.style.touchAction = ""; this._domElement.style.userSelect = ""; this._domElement.style.webkitUserSelect = ""; this._domElement.removeEventListener("pointerdown", onPointerDown); this._domElement.removeEventListener("pointercancel", onPointerUp); this._domElement.removeEventListener("wheel", onMouseWheel, { passive: false }); this._domElement.removeEventListener("contextmenu", onContextMenu); this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); this._domElement.ownerDocument.removeEventListener("pointerlockchange", onPointerLockChange); this._domElement.ownerDocument.removeEventListener("pointerlockerror", onPointerLockError); }; this.cancel = () => { if (this._state === ACTION.NONE) return; this._state = ACTION.NONE; this._activePointers.length = 0; endDragging(); }; if (domElement) this.connect(domElement); this.update(0); } /** * The camera to be controlled * @category Properties */ get camera() { return this._camera; } set camera(camera) { this._camera = camera; this.updateCameraUp(); this._camera.updateProjectionMatrix(); this._updateNearPlaneCorners(); this._needsUpdate = true; } /** * Whether or not the controls are enabled. * `false` to disable user dragging/touch-move, but all methods works. * @category Properties */ get enabled() { return this._enabled; } set enabled(enabled) { this._enabled = enabled; if (!this._domElement) return; if (enabled) { this._domElement.style.touchAction = "none"; this._domElement.style.userSelect = "none"; this._domElement.style.webkitUserSelect = "none"; } else { this.cancel(); this._domElement.style.touchAction = ""; this._domElement.style.userSelect = ""; this._domElement.style.webkitUserSelect = ""; } } /** * Returns `true` if the controls are active updating. * readonly value. * @category Properties */ get active() { return !this._hasRested; } /** * Getter for the current `ACTION`. * readonly value. * @category Properties */ get currentAction() { return this._state; } /** * get/set Current distance. * @category Properties */ get distance() { return this._spherical.radius; } set distance(distance3) { if (this._spherical.radius === distance3 && this._sphericalEnd.radius === distance3) return; this._spherical.radius = distance3; this._sphericalEnd.radius = distance3; this._needsUpdate = true; } // horizontal angle /** * get/set the azimuth angle (horizontal) in radians. * Every 360 degrees turn is added to `.azimuthAngle` value, which is accumulative. * @category Properties */ get azimuthAngle() { return this._spherical.theta; } set azimuthAngle(azimuthAngle) { if (this._spherical.theta === azimuthAngle && this._sphericalEnd.theta === azimuthAngle) return; this._spherical.theta = azimuthAngle; this._sphericalEnd.theta = azimuthAngle; this._needsUpdate = true; } // vertical angle /** * get/set the polar angle (vertical) in radians. * @category Properties */ get polarAngle() { return this._spherical.phi; } set polarAngle(polarAngle) { if (this._spherical.phi === polarAngle && this._sphericalEnd.phi === polarAngle) return; this._spherical.phi = polarAngle; this._sphericalEnd.phi = polarAngle; this._needsUpdate = true; } /** * Whether camera position should be enclosed in the boundary or not. * @category Properties */ get boundaryEnclosesCamera() { return this._boundaryEnclosesCamera; } set boundaryEnclosesCamera(boundaryEnclosesCamera) { this._boundaryEnclosesCamera = boundaryEnclosesCamera; this._needsUpdate = true; } /** * Set drag-start, touches and wheel enable area in the domElement. * each values are between `0` and `1` inclusive, where `0` is left/top and `1` is right/bottom of the screen. * e.g. `{ x: 0, y: 0, width: 1, height: 1 }` for entire area. * @category Properties */ set interactiveArea(interactiveArea) { this._interactiveArea.width = clamp3(interactiveArea.width, 0, 1); this._interactiveArea.height = clamp3(interactiveArea.height, 0, 1); this._interactiveArea.x = clamp3(interactiveArea.x, 0, 1 - this._interactiveArea.width); this._interactiveArea.y = clamp3(interactiveArea.y, 0, 1 - this._interactiveArea.height); } /** * Adds the specified event listener. * Applicable event types (which is `K`) are: * | Event name | Timing | * | ------------------- | ------ | * | `'controlstart'` | When the user starts to control the camera via mouse / touches. ¹ | * | `'control'` | When the user controls the camera (dragging). | * | `'controlend'` | When the user ends to control the camera. ¹ | * | `'transitionstart'` | When any kind of transition starts, either user control or using a method with `enableTransition = true` | * | `'update'` | When the camera position is updated. | * | `'wake'` | When the camera starts moving. | * | `'rest'` | When the camera movement is below `.restThreshold` ². | * | `'sleep'` | When the camera end moving. | * * 1. `mouseButtons.wheel` (Mouse wheel control) does not emit `'controlstart'` and `'controlend'`. `mouseButtons.wheel` uses scroll-event internally, and scroll-event happens intermittently. That means "start" and "end" cannot be detected. * 2. Due to damping, `sleep` will usually fire a few seconds after the camera _appears_ to have stopped moving. If you want to do something (e.g. enable UI, perform another transition) at the point when the camera has stopped, you probably want the `rest` event. This can be fine tuned using the `.restThreshold` parameter. See the [Rest and Sleep Example](https://yomotsu.github.io/camera-controls/examples/rest-and-sleep.html). * * e.g. * ``` * cameraControl.addEventListener( 'controlstart', myCallbackFunction ); * ``` * @param type event name * @param listener handler function * @category Methods */ addEventListener(type, listener) { super.addEventListener(type, listener); } /** * Removes the specified event listener * e.g. * ``` * cameraControl.addEventListener( 'controlstart', myCallbackFunction ); * ``` * @param type event name * @param listener handler function * @category Methods */ removeEventListener(type, listener) { super.removeEventListener(type, listener); } /** * Rotate azimuthal angle(horizontal) and polar angle(vertical). * Every value is added to the current value. * @param azimuthAngle Azimuth rotate angle. In radian. * @param polarAngle Polar rotate angle. In radian. * @param enableTransition Whether to move smoothly or immediately * @category Methods */ rotate(azimuthAngle, polarAngle, enableTransition = false) { return this.rotateTo(this._sphericalEnd.theta + azimuthAngle, this._sphericalEnd.phi + polarAngle, enableTransition); } /** * Rotate azimuthal angle(horizontal) to the given angle and keep the same polar angle(vertical) target. * * e.g. * ``` * cameraControls.rotateAzimuthTo( 30 * THREE.MathUtils.DEG2RAD, true ); * ``` * @param azimuthAngle Azimuth rotate angle. In radian. * @param enableTransition Whether to move smoothly or immediately * @category Methods */ rotateAzimuthTo(azimuthAngle, enableTransition = false) { return this.rotateTo(azimuthAngle, this._sphericalEnd.phi, enableTransition); } /** * Rotate polar angle(vertical) to the given angle and keep the same azimuthal angle(horizontal) target. * * e.g. * ``` * cameraControls.rotatePolarTo( 30 * THREE.MathUtils.DEG2RAD, true ); * ``` * @param polarAngle Polar rotate angle. In radian. * @param enableTransition Whether to move smoothly or immediately * @category Methods */ rotatePolarTo(polarAngle, enableTransition = false) { return this.rotateTo(this._sphericalEnd.theta, polarAngle, enableTransition); } /** * Rotate azimuthal angle(horizontal) and polar angle(vertical) to the given angle. * Camera view will rotate over the orbit pivot absolutely: * * azimuthAngle * ``` * 0º * \ * 90º -----+----- -90º * \ * 180º * ``` * | direction | angle | * | --------- | ---------------------- | * | front | 0º | * | left | 90º (`Math.PI / 2`) | * | right | -90º (`- Math.PI / 2`) | * | back | 180º (`Math.PI`) | * * polarAngle * ``` * 180º * | * 90º * | * 0º * ``` * | direction | angle | * | -------------------- | ---------------------- | * | top/sky | 180º (`Math.PI`) | * | horizontal from view | 90º (`Math.PI / 2`) | * | bottom/floor | 0º | * * @param azimuthAngle Azimuth rotate angle to. In radian. * @param polarAngle Polar rotate angle to. In radian. * @param enableTransition Whether to move smoothly or immediately * @category Methods */ rotateTo(azimuthAngle, polarAngle, enableTransition = false) { this._isUserControllingRotate = false; const theta = clamp3(azimuthAngle, this.minAzimuthAngle, this.maxAzimuthAngle); const phi = clamp3(polarAngle, this.minPolarAngle, this.maxPolarAngle); this._sphericalEnd.theta = theta; this._sphericalEnd.phi = phi; this._sphericalEnd.makeSafe(); this._needsUpdate = true; if (!enableTransition) { this._spherical.theta = this._sphericalEnd.theta; this._spherical.phi = this._sphericalEnd.phi; } const resolveImmediately = !enableTransition || approxEquals(this._spherical.theta, this._sphericalEnd.theta, this.restThreshold) && approxEquals(this._spherical.phi, this._sphericalEnd.phi, this.restThreshold); return this._createOnRestPromise(resolveImmediately); } /** * Dolly in/out camera position. * @param distance Distance of dollyIn. Negative number for dollyOut. * @param enableTransition Whether to move smoothly or immediately. * @category Methods */ dolly(distance3, enableTransition = false) { return this.dollyTo(this._sphericalEnd.radius - distance3, enableTransition); } /** * Dolly in/out camera position to given distance. * @param distance Distance of dolly. * @param enableTransition Whether to move smoothly or immediately. * @category Methods */ dollyTo(distance3, enableTransition = false) { this._isUserControllingDolly = false; this._lastDollyDirection = DOLLY_DIRECTION.NONE; this._changedDolly = 0; return this._dollyToNoClamp(clamp3(distance3, this.minDistance, this.maxDistance), enableTransition); } _dollyToNoClamp(distance3, enableTransition = false) { const lastRadius = this._sphericalEnd.radius; const hasCollider = this.colliderMeshes.length >= 1; if (hasCollider) { const maxDistanceByCollisionTest = this._collisionTest(); const isCollided = approxEquals(maxDistanceByCollisionTest, this._spherical.radius); const isDollyIn = lastRadius > distance3; if (!isDollyIn && isCollided) return Promise.resolve(); this._sphericalEnd.radius = Math.min(distance3, maxDistanceByCollisionTest); } else { this._sphericalEnd.radius = distance3; } this._needsUpdate = true; if (!enableTransition) { this._spherical.radius = this._sphericalEnd.radius; } const resolveImmediately = !enableTransition || approxEquals(this._spherical.radius, this._sphericalEnd.radius, this.restThreshold); return this._createOnRestPromise(resolveImmediately); } /** * Dolly in, but does not change the distance between the target and the camera, and moves the target position instead. * Specify a negative value for dolly out. * @param distance Distance of dolly. * @param enableTransition Whether to move smoothly or immediately. * @category Methods */ dollyInFixed(distance3, enableTransition = false) { this._targetEnd.add(this._getCameraDirection(_cameraDirection).multiplyScalar(distance3)); if (!enableTransition) { this._target.copy(this._targetEnd); } const resolveImmediately = !enableTransition || approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) && approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) && approxEquals(this._target.z, this._targetEnd.z, this.restThreshold); return this._createOnRestPromise(resolveImmediately); } /** * Zoom in/out camera. The value is added to camera zoom. * Limits set with `.minZoom` and `.maxZoom` * @param zoomStep zoom scale * @param enableTransition Whether to move smoothly or immediately * @category Methods */ zoom(zoomStep, enableTransition = false) { return this.zoomTo(this._zoomEnd + zoomStep, enableTransition); } /** * Zoom in/out camera to given scale. The value overwrites camera zoom. * Limits set with .minZoom and .maxZoom * @param zoom * @param enableTransition * @category Methods */ zoomTo(zoom, enableTransition = false) { this._isUserControllingZoom = false; this._zoomEnd = clamp3(zoom, this.minZoom, this.maxZoom); this._needsUpdate = true; if (!enableTransition) { this._zoom = this._zoomEnd; } const resolveImmediately = !enableTransition || approxEquals(this._zoom, this._zoomEnd, this.restThreshold); this._changedZoom = 0; return this._createOnRestPromise(resolveImmediately); } /** * @deprecated `pan()` has been renamed to `truck()` * @category Methods */ pan(x, y, enableTransition = false) { console.warn("`pan` has been renamed to `truck`"); return this.truck(x, y, enableTransition); } /** * Truck and pedestal camera using current azimuthal angle * @param x Horizontal translate amount * @param y Vertical translate amount * @param enableTransition Whether to move smoothly or immediately * @category Methods */ truck(x, y, enableTransition = false) { this._camera.updateMatrix(); _xColumn.setFromMatrixColumn(this._camera.matrix, 0); _yColumn.setFromMatrixColumn(this._camera.matrix, 1); _xColumn.multiplyScalar(x); _yColumn.multiplyScalar(-y); const offset = _v3A.copy(_xColumn).add(_yColumn); const to = _v3B.copy(this._targetEnd).add(offset); return this.moveTo(to.x, to.y, to.z, enableTransition); } /** * Move forward / backward. * @param distance Amount to move forward / backward. Negative value to move backward * @param enableTransition Whether to move smoothly or immediately * @category Methods */ forward(distance3, enableTransition = false) { _v3A.setFromMatrixColumn(this._camera.matrix, 0); _v3A.crossVectors(this._camera.up, _v3A); _v3A.multiplyScalar(distance3); const to = _v3B.copy(this._targetEnd).add(_v3A); return this.moveTo(to.x, to.y, to.z, enableTransition); } /** * Move up / down. * @param height Amount to move up / down. Negative value to move down * @param enableTransition Whether to move smoothly or immediately * @category Methods */ elevate(height, enableTransition = false) { _v3A.copy(this._camera.up).multiplyScalar(height); return this.moveTo(this._targetEnd.x + _v3A.x, this._targetEnd.y + _v3A.y, this._targetEnd.z + _v3A.z, enableTransition); } /** * Move target position to given point. * @param x x coord to move center position * @param y y coord to move center position * @param z z coord to move center position * @param enableTransition Whether to move smoothly or immediately * @category Methods */ moveTo(x, y, z, enableTransition = false) { this._isUserControllingTruck = false; const offset = _v3A.set(x, y, z).sub(this._targetEnd); this._encloseToBoundary(this._targetEnd, offset, this.boundaryFriction); this._needsUpdate = true; if (!enableTransition) { this._target.copy(this._targetEnd); } const resolveImmediately = !enableTransition || approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) && approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) && approxEquals(this._target.z, this._targetEnd.z, this.restThreshold); return this._createOnRestPromise(resolveImmediately); } /** * Look in the given point direction. * @param x point x. * @param y point y. * @param z point z. * @param enableTransition Whether to move smoothly or immediately. * @returns Transition end promise * @category Methods */ lookInDirectionOf(x, y, z, enableTransition = false) { const point = _v3A.set(x, y, z); const direction2 = point.sub(this._targetEnd).normalize(); const position2 = direction2.multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd); return this.setPosition(position2.x, position2.y, position2.z, enableTransition); } /** * Fit the viewport to the box or the bounding box of the object, using the nearest axis. paddings are in unit. * set `cover: true` to fill enter screen. * e.g. * ``` * cameraControls.fitToBox( myMesh ); * ``` * @param box3OrObject Axis aligned bounding box to fit the view. * @param enableTransition Whether to move smoothly or immediately. * @param options | `` { cover: boolean, paddingTop: number, paddingLeft: number, paddingBottom: number, paddingRight: number } * @returns Transition end promise * @category Methods */ fitToBox(box3OrObject, enableTransition, { cover = false, paddingLeft = 0, paddingRight = 0, paddingBottom = 0, paddingTop = 0 } = {}) { const promises = []; const aabb2 = box3OrObject.isBox3 ? _box3A.copy(box3OrObject) : _box3A.setFromObject(box3OrObject); if (aabb2.isEmpty()) { console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"); Promise.resolve(); } const theta = roundToStep(this._sphericalEnd.theta, PI_HALF); const phi = roundToStep(this._sphericalEnd.phi, PI_HALF); promises.push(this.rotateTo(theta, phi, enableTransition)); const normal2 = _v3A.setFromSpherical(this._sphericalEnd).normalize(); const rotation3 = _quaternionA.setFromUnitVectors(normal2, _AXIS_Z); const viewFromPolar = approxEquals(Math.abs(normal2.y), 1); if (viewFromPolar) { rotation3.multiply(_quaternionB.setFromAxisAngle(_AXIS_Y, theta)); } rotation3.multiply(this._yAxisUpSpaceInverse); const bb2 = _box3B.makeEmpty(); _v3B.copy(aabb2.min).applyQuaternion(rotation3); bb2.expandByPoint(_v3B); _v3B.copy(aabb2.min).setX(aabb2.max.x).applyQuaternion(rotation3); bb2.expandByPoint(_v3B); _v3B.copy(aabb2.min).setY(aabb2.max.y).applyQuaternion(rotation3); bb2.expandByPoint(_v3B); _v3B.copy(aabb2.max).setZ(aabb2.min.z).applyQuaternion(rotation3); bb2.expandByPoint(_v3B); _v3B.copy(aabb2.min).setZ(aabb2.max.z).applyQuaternion(rotation3); bb2.expandByPoint(_v3B); _v3B.copy(aabb2.max).setY(aabb2.min.y).applyQuaternion(rotation3); bb2.expandByPoint(_v3B); _v3B.copy(aabb2.max).setX(aabb2.min.x).applyQuaternion(rotation3); bb2.expandByPoint(_v3B); _v3B.copy(aabb2.max).applyQuaternion(rotation3); bb2.expandByPoint(_v3B); bb2.min.x -= paddingLeft; bb2.min.y -= paddingBottom; bb2.max.x += paddingRight; bb2.max.y += paddingTop; rotation3.setFromUnitVectors(_AXIS_Z, normal2); if (viewFromPolar) { rotation3.premultiply(_quaternionB.invert()); } rotation3.premultiply(this._yAxisUpSpace); const bbSize = bb2.getSize(_v3A); const center3 = bb2.getCenter(_v3B).applyQuaternion(rotation3); if (isPerspectiveCamera(this._camera)) { const distance3 = this.getDistanceToFitBox(bbSize.x, bbSize.y, bbSize.z, cover); promises.push(this.moveTo(center3.x, center3.y, center3.z, enableTransition)); promises.push(this.dollyTo(distance3, enableTransition)); promises.push(this.setFocalOffset(0, 0, 0, enableTransition)); } else if (isOrthographicCamera(this._camera)) { const camera = this._camera; const width = camera.right - camera.left; const height = camera.top - camera.bottom; const zoom = cover ? Math.max(width / bbSize.x, height / bbSize.y) : Math.min(width / bbSize.x, height / bbSize.y); promises.push(this.moveTo(center3.x, center3.y, center3.z, enableTransition)); promises.push(this.zoomTo(zoom, enableTransition)); promises.push(this.setFocalOffset(0, 0, 0, enableTransition)); } return Promise.all(promises); } /** * Fit the viewport to the sphere or the bounding sphere of the object. * @param sphereOrMesh * @param enableTransition * @category Methods */ fitToSphere(sphereOrMesh, enableTransition) { const promises = []; const isObject3D = "isObject3D" in sphereOrMesh; const boundingSphere = isObject3D ? _CameraControls.createBoundingSphere(sphereOrMesh, _sphere3) : _sphere3.copy(sphereOrMesh); promises.push(this.moveTo(boundingSphere.center.x, boundingSphere.center.y, boundingSphere.center.z, enableTransition)); if (isPerspectiveCamera(this._camera)) { const distanceToFit = this.getDistanceToFitSphere(boundingSphere.radius); promises.push(this.dollyTo(distanceToFit, enableTransition)); } else if (isOrthographicCamera(this._camera)) { const width = this._camera.right - this._camera.left; const height = this._camera.top - this._camera.bottom; const diameter = 2 * boundingSphere.radius; const zoom = Math.min(width / diameter, height / diameter); promises.push(this.zoomTo(zoom, enableTransition)); } promises.push(this.setFocalOffset(0, 0, 0, enableTransition)); return Promise.all(promises); } /** * Look at the `target` from the `position`. * @param positionX * @param positionY * @param positionZ * @param targetX * @param targetY * @param targetZ * @param enableTransition * @category Methods */ setLookAt(positionX, positionY, positionZ, targetX, targetY, targetZ, enableTransition = false) { this._isUserControllingRotate = false; this._isUserControllingDolly = false; this._isUserControllingTruck = false; this._lastDollyDirection = DOLLY_DIRECTION.NONE; this._changedDolly = 0; const target2 = _v3B.set(targetX, targetY, targetZ); const position2 = _v3A.set(positionX, positionY, positionZ); this._targetEnd.copy(target2); this._sphericalEnd.setFromVector3(position2.sub(target2).applyQuaternion(this._yAxisUpSpace)); this._needsUpdate = true; if (!enableTransition) { this._target.copy(this._targetEnd); this._spherical.copy(this._sphericalEnd); } const resolveImmediately = !enableTransition || approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) && approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) && approxEquals(this._target.z, this._targetEnd.z, this.restThreshold) && approxEquals(this._spherical.theta, this._sphericalEnd.theta, this.restThreshold) && approxEquals(this._spherical.phi, this._sphericalEnd.phi, this.restThreshold) && approxEquals(this._spherical.radius, this._sphericalEnd.radius, this.restThreshold); return this._createOnRestPromise(resolveImmediately); } /** * Interpolates between two states. * @param stateA * @param stateB * @param t * @param enableTransition * @category Methods */ lerp(stateA, stateB, t3, enableTransition = false) { this._isUserControllingRotate = false; this._isUserControllingDolly = false; this._isUserControllingTruck = false; this._lastDollyDirection = DOLLY_DIRECTION.NONE; this._changedDolly = 0; const targetA = _v3A.set(...stateA.target); if ("spherical" in stateA) { _sphericalA.set(...stateA.spherical); } else { const positionA = _v3B.set(...stateA.position); _sphericalA.setFromVector3(positionA.sub(targetA).applyQuaternion(this._yAxisUpSpace)); } const targetB = _v3C.set(...stateB.target); if ("spherical" in stateB) { _sphericalB.set(...stateB.spherical); } else { const positionB = _v3B.set(...stateB.position); _sphericalB.setFromVector3(positionB.sub(targetB).applyQuaternion(this._yAxisUpSpace)); } this._targetEnd.copy(targetA.lerp(targetB, t3)); const deltaTheta = _sphericalB.theta - _sphericalA.theta; const deltaPhi = _sphericalB.phi - _sphericalA.phi; const deltaRadius = _sphericalB.radius - _sphericalA.radius; this._sphericalEnd.set(_sphericalA.radius + deltaRadius * t3, _sphericalA.phi + deltaPhi * t3, _sphericalA.theta + deltaTheta * t3); this._needsUpdate = true; if (!enableTransition) { this._target.copy(this._targetEnd); this._spherical.copy(this._sphericalEnd); } const resolveImmediately = !enableTransition || approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) && approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) && approxEquals(this._target.z, this._targetEnd.z, this.restThreshold) && approxEquals(this._spherical.theta, this._sphericalEnd.theta, this.restThreshold) && approxEquals(this._spherical.phi, this._sphericalEnd.phi, this.restThreshold) && approxEquals(this._spherical.radius, this._sphericalEnd.radius, this.restThreshold); return this._createOnRestPromise(resolveImmediately); } /** * Similar to setLookAt, but it interpolates between two states. * @param positionAX * @param positionAY * @param positionAZ * @param targetAX * @param targetAY * @param targetAZ * @param positionBX * @param positionBY * @param positionBZ * @param targetBX * @param targetBY * @param targetBZ * @param t * @param enableTransition * @category Methods */ lerpLookAt(positionAX, positionAY, positionAZ, targetAX, targetAY, targetAZ, positionBX, positionBY, positionBZ, targetBX, targetBY, targetBZ, t3, enableTransition = false) { return this.lerp({ position: [positionAX, positionAY, positionAZ], target: [targetAX, targetAY, targetAZ] }, { position: [positionBX, positionBY, positionBZ], target: [targetBX, targetBY, targetBZ] }, t3, enableTransition); } /** * Set angle and distance by given position. * An alias of `setLookAt()`, without target change. Thus keep gazing at the current target * @param positionX * @param positionY * @param positionZ * @param enableTransition * @category Methods */ setPosition(positionX, positionY, positionZ, enableTransition = false) { return this.setLookAt(positionX, positionY, positionZ, this._targetEnd.x, this._targetEnd.y, this._targetEnd.z, enableTransition); } /** * Set the target position where gaze at. * An alias of `setLookAt()`, without position change. Thus keep the same position. * @param targetX * @param targetY * @param targetZ * @param enableTransition * @category Methods */ setTarget(targetX, targetY, targetZ, enableTransition = false) { const pos = this.getPosition(_v3A); const promise = this.setLookAt(pos.x, pos.y, pos.z, targetX, targetY, targetZ, enableTransition); this._sphericalEnd.phi = clamp3(this._sphericalEnd.phi, this.minPolarAngle, this.maxPolarAngle); return promise; } /** * Set focal offset using the screen parallel coordinates. z doesn't affect in Orthographic as with Dolly. * @param x * @param y * @param z * @param enableTransition * @category Methods */ setFocalOffset(x, y, z, enableTransition = false) { this._isUserControllingOffset = false; this._focalOffsetEnd.set(x, y, z); this._needsUpdate = true; if (!enableTransition) this._focalOffset.copy(this._focalOffsetEnd); const resolveImmediately = !enableTransition || approxEquals(this._focalOffset.x, this._focalOffsetEnd.x, this.restThreshold) && approxEquals(this._focalOffset.y, this._focalOffsetEnd.y, this.restThreshold) && approxEquals(this._focalOffset.z, this._focalOffsetEnd.z, this.restThreshold); return this._createOnRestPromise(resolveImmediately); } /** * Set orbit point without moving the camera. * SHOULD NOT RUN DURING ANIMATIONS. `setOrbitPoint()` will immediately fix the positions. * @param targetX * @param targetY * @param targetZ * @category Methods */ setOrbitPoint(targetX, targetY, targetZ) { this._camera.updateMatrixWorld(); _xColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 0); _yColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 1); _zColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 2); const position2 = _v3A.set(targetX, targetY, targetZ); const distance3 = position2.distanceTo(this._camera.position); const cameraToPoint = position2.sub(this._camera.position); _xColumn.multiplyScalar(cameraToPoint.x); _yColumn.multiplyScalar(cameraToPoint.y); _zColumn.multiplyScalar(cameraToPoint.z); _v3A.copy(_xColumn).add(_yColumn).add(_zColumn); _v3A.z = _v3A.z + distance3; this.dollyTo(distance3, false); this.setFocalOffset(-_v3A.x, _v3A.y, -_v3A.z, false); this.moveTo(targetX, targetY, targetZ, false); } /** * Set the boundary box that encloses the target of the camera. box3 is in THREE.Box3 * @param box3 * @category Methods */ setBoundary(box3) { if (!box3) { this._boundary.min.set(-Infinity, -Infinity, -Infinity); this._boundary.max.set(Infinity, Infinity, Infinity); this._needsUpdate = true; return; } this._boundary.copy(box3); this._boundary.clampPoint(this._targetEnd, this._targetEnd); this._needsUpdate = true; } /** * Set (or unset) the current viewport. * Set this when you want to use renderer viewport and .dollyToCursor feature at the same time. * @param viewportOrX * @param y * @param width * @param height * @category Methods */ setViewport(viewportOrX, y, width, height) { if (viewportOrX === null) { this._viewport = null; return; } this._viewport = this._viewport || new THREE.Vector4(); if (typeof viewportOrX === "number") { this._viewport.set(viewportOrX, y, width, height); } else { this._viewport.copy(viewportOrX); } } /** * Calculate the distance to fit the box. * @param width box width * @param height box height * @param depth box depth * @returns distance * @category Methods */ getDistanceToFitBox(width, height, depth, cover = false) { if (notSupportedInOrthographicCamera(this._camera, "getDistanceToFitBox")) return this._spherical.radius; const boundingRectAspect = width / height; const fov = this._camera.getEffectiveFOV() * DEG2RAD; const aspect = this._camera.aspect; const heightToFit = (cover ? boundingRectAspect > aspect : boundingRectAspect < aspect) ? height : width / aspect; return heightToFit * 0.5 / Math.tan(fov * 0.5) + depth * 0.5; } /** * Calculate the distance to fit the sphere. * @param radius sphere radius * @returns distance * @category Methods */ getDistanceToFitSphere(radius) { if (notSupportedInOrthographicCamera(this._camera, "getDistanceToFitSphere")) return this._spherical.radius; const vFOV = this._camera.getEffectiveFOV() * DEG2RAD; const hFOV = Math.atan(Math.tan(vFOV * 0.5) * this._camera.aspect) * 2; const fov = 1 < this._camera.aspect ? vFOV : hFOV; return radius / Math.sin(fov * 0.5); } /** * Returns the orbit center position, where the camera looking at. * @param out The receiving Vector3 instance to copy the result * @param receiveEndValue Whether receive the transition end coords or current. default is `true` * @category Methods */ getTarget(out7, receiveEndValue = true) { const _out = !!out7 && out7.isVector3 ? out7 : new THREE.Vector3(); return _out.copy(receiveEndValue ? this._targetEnd : this._target); } /** * Returns the camera position. * @param out The receiving Vector3 instance to copy the result * @param receiveEndValue Whether receive the transition end coords or current. default is `true` * @category Methods */ getPosition(out7, receiveEndValue = true) { const _out = !!out7 && out7.isVector3 ? out7 : new THREE.Vector3(); return _out.setFromSpherical(receiveEndValue ? this._sphericalEnd : this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(receiveEndValue ? this._targetEnd : this._target); } /** * Returns the spherical coordinates of the orbit. * @param out The receiving Spherical instance to copy the result * @param receiveEndValue Whether receive the transition end coords or current. default is `true` * @category Methods */ getSpherical(out7, receiveEndValue = true) { const _out = out7 || new THREE.Spherical(); return _out.copy(receiveEndValue ? this._sphericalEnd : this._spherical); } /** * Returns the focal offset, which is how much the camera appears to be translated in screen parallel coordinates. * @param out The receiving Vector3 instance to copy the result * @param receiveEndValue Whether receive the transition end coords or current. default is `true` * @category Methods */ getFocalOffset(out7, receiveEndValue = true) { const _out = !!out7 && out7.isVector3 ? out7 : new THREE.Vector3(); return _out.copy(receiveEndValue ? this._focalOffsetEnd : this._focalOffset); } /** * Normalize camera azimuth angle (horizontal rotation) between -180 and 180 degrees. * @returns This CameraControls instance. * @category Methods */ normalizeRotations() { this._sphericalEnd.theta = (this._sphericalEnd.theta % PI_2 + PI_2) % PI_2; if (this._sphericalEnd.theta > Math.PI) this._sphericalEnd.theta -= PI_2; this._spherical.theta += PI_2 * Math.round((this._sphericalEnd.theta - this._spherical.theta) / PI_2); return this; } /** * stop all transitions. */ stop() { this._focalOffset.copy(this._focalOffsetEnd); this._target.copy(this._targetEnd); this._spherical.copy(this._sphericalEnd); this._zoom = this._zoomEnd; } /** * Reset all rotation and position to defaults. * @param enableTransition * @category Methods */ reset(enableTransition = false) { if (!approxEquals(this._camera.up.x, this._cameraUp0.x) || !approxEquals(this._camera.up.y, this._cameraUp0.y) || !approxEquals(this._camera.up.z, this._cameraUp0.z)) { this._camera.up.copy(this._cameraUp0); const position2 = this.getPosition(_v3A); this.updateCameraUp(); this.setPosition(position2.x, position2.y, position2.z); } const promises = [ this.setLookAt(this._position0.x, this._position0.y, this._position0.z, this._target0.x, this._target0.y, this._target0.z, enableTransition), this.setFocalOffset(this._focalOffset0.x, this._focalOffset0.y, this._focalOffset0.z, enableTransition), this.zoomTo(this._zoom0, enableTransition) ]; return Promise.all(promises); } /** * Set current camera position as the default position. * @category Methods */ saveState() { this._cameraUp0.copy(this._camera.up); this.getTarget(this._target0); this.getPosition(this._position0); this._zoom0 = this._zoom; this._focalOffset0.copy(this._focalOffset); } /** * Sync camera-up direction. * When camera-up vector is changed, `.updateCameraUp()` must be called. * @category Methods */ updateCameraUp() { this._yAxisUpSpace.setFromUnitVectors(this._camera.up, _AXIS_Y); this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert(); } /** * Apply current camera-up direction to the camera. * The orbit system will be re-initialized with the current position. * @category Methods */ applyCameraUp() { const cameraDirection = _v3A.subVectors(this._target, this._camera.position).normalize(); const side = _v3B.crossVectors(cameraDirection, this._camera.up); this._camera.up.crossVectors(side, cameraDirection).normalize(); this._camera.updateMatrixWorld(); const position2 = this.getPosition(_v3A); this.updateCameraUp(); this.setPosition(position2.x, position2.y, position2.z); } /** * Update camera position and directions. * This should be called in your tick loop every time, and returns true if re-rendering is needed. * @param delta * @returns updated * @category Methods */ update(delta) { const deltaTheta = this._sphericalEnd.theta - this._spherical.theta; const deltaPhi = this._sphericalEnd.phi - this._spherical.phi; const deltaRadius = this._sphericalEnd.radius - this._spherical.radius; const deltaTarget = _deltaTarget.subVectors(this._targetEnd, this._target); const deltaOffset = _deltaOffset.subVectors(this._focalOffsetEnd, this._focalOffset); const deltaZoom = this._zoomEnd - this._zoom; if (approxZero(deltaTheta)) { this._thetaVelocity.value = 0; this._spherical.theta = this._sphericalEnd.theta; } else { const smoothTime = this._isUserControllingRotate ? this.draggingSmoothTime : this.smoothTime; this._spherical.theta = smoothDamp(this._spherical.theta, this._sphericalEnd.theta, this._thetaVelocity, smoothTime, Infinity, delta); this._needsUpdate = true; } if (approxZero(deltaPhi)) { this._phiVelocity.value = 0; this._spherical.phi = this._sphericalEnd.phi; } else { const smoothTime = this._isUserControllingRotate ? this.draggingSmoothTime : this.smoothTime; this._spherical.phi = smoothDamp(this._spherical.phi, this._sphericalEnd.phi, this._phiVelocity, smoothTime, Infinity, delta); this._needsUpdate = true; } if (approxZero(deltaRadius)) { this._radiusVelocity.value = 0; this._spherical.radius = this._sphericalEnd.radius; } else { const smoothTime = this._isUserControllingDolly ? this.draggingSmoothTime : this.smoothTime; this._spherical.radius = smoothDamp(this._spherical.radius, this._sphericalEnd.radius, this._radiusVelocity, smoothTime, this.maxSpeed, delta); this._needsUpdate = true; } if (approxZero(deltaTarget.x) && approxZero(deltaTarget.y) && approxZero(deltaTarget.z)) { this._targetVelocity.set(0, 0, 0); this._target.copy(this._targetEnd); } else { const smoothTime = this._isUserControllingTruck ? this.draggingSmoothTime : this.smoothTime; smoothDampVec3(this._target, this._targetEnd, this._targetVelocity, smoothTime, this.maxSpeed, delta, this._target); this._needsUpdate = true; } if (approxZero(deltaOffset.x) && approxZero(deltaOffset.y) && approxZero(deltaOffset.z)) { this._focalOffsetVelocity.set(0, 0, 0); this._focalOffset.copy(this._focalOffsetEnd); } else { const smoothTime = this._isUserControllingOffset ? this.draggingSmoothTime : this.smoothTime; smoothDampVec3(this._focalOffset, this._focalOffsetEnd, this._focalOffsetVelocity, smoothTime, this.maxSpeed, delta, this._focalOffset); this._needsUpdate = true; } if (approxZero(deltaZoom)) { this._zoomVelocity.value = 0; this._zoom = this._zoomEnd; } else { const smoothTime = this._isUserControllingZoom ? this.draggingSmoothTime : this.smoothTime; this._zoom = smoothDamp(this._zoom, this._zoomEnd, this._zoomVelocity, smoothTime, Infinity, delta); } if (this.dollyToCursor) { if (isPerspectiveCamera(this._camera) && this._changedDolly !== 0) { const dollyControlAmount = this._spherical.radius - this._lastDistance; const camera = this._camera; const cameraDirection = this._getCameraDirection(_cameraDirection); const planeX = _v3A.copy(cameraDirection).cross(camera.up).normalize(); if (planeX.lengthSq() === 0) planeX.x = 1; const planeY = _v3B.crossVectors(planeX, cameraDirection); const worldToScreen = this._sphericalEnd.radius * Math.tan(camera.getEffectiveFOV() * DEG2RAD * 0.5); const prevRadius = this._sphericalEnd.radius - dollyControlAmount; const lerpRatio = (prevRadius - this._sphericalEnd.radius) / this._sphericalEnd.radius; const cursor = _v3C.copy(this._targetEnd).add(planeX.multiplyScalar(this._dollyControlCoord.x * worldToScreen * camera.aspect)).add(planeY.multiplyScalar(this._dollyControlCoord.y * worldToScreen)); const newTargetEnd = _v3A.copy(this._targetEnd).lerp(cursor, lerpRatio); const isMin = this._lastDollyDirection === DOLLY_DIRECTION.IN && this._spherical.radius <= this.minDistance; const isMax = this._lastDollyDirection === DOLLY_DIRECTION.OUT && this.maxDistance <= this._spherical.radius; if (this.infinityDolly && (isMin || isMax)) { this._sphericalEnd.radius -= dollyControlAmount; this._spherical.radius -= dollyControlAmount; const dollyAmount = _v3B.copy(cameraDirection).multiplyScalar(-dollyControlAmount); newTargetEnd.add(dollyAmount); } this._boundary.clampPoint(newTargetEnd, newTargetEnd); const targetEndDiff = _v3B.subVectors(newTargetEnd, this._targetEnd); this._targetEnd.copy(newTargetEnd); this._target.add(targetEndDiff); this._changedDolly -= dollyControlAmount; if (approxZero(this._changedDolly)) this._changedDolly = 0; } else if (isOrthographicCamera(this._camera) && this._changedZoom !== 0) { const dollyControlAmount = this._zoom - this._lastZoom; const camera = this._camera; const worldCursorPosition = _v3A.set(this._dollyControlCoord.x, this._dollyControlCoord.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); const quaternion = _v3B.set(0, 0, -1).applyQuaternion(camera.quaternion); const cursor = _v3C.copy(worldCursorPosition).add(quaternion.multiplyScalar(-worldCursorPosition.dot(camera.up))); const prevZoom = this._zoom - dollyControlAmount; const lerpRatio = -(prevZoom - this._zoom) / this._zoom; const cameraDirection = this._getCameraDirection(_cameraDirection); const prevPlaneConstant = this._targetEnd.dot(cameraDirection); const newTargetEnd = _v3A.copy(this._targetEnd).lerp(cursor, lerpRatio); const newPlaneConstant = newTargetEnd.dot(cameraDirection); const pullBack = cameraDirection.multiplyScalar(newPlaneConstant - prevPlaneConstant); newTargetEnd.sub(pullBack); this._boundary.clampPoint(newTargetEnd, newTargetEnd); const targetEndDiff = _v3B.subVectors(newTargetEnd, this._targetEnd); this._targetEnd.copy(newTargetEnd); this._target.add(targetEndDiff); this._changedZoom -= dollyControlAmount; if (approxZero(this._changedZoom)) this._changedZoom = 0; } } if (this._camera.zoom !== this._zoom) { this._camera.zoom = this._zoom; this._camera.updateProjectionMatrix(); this._updateNearPlaneCorners(); this._needsUpdate = true; } this._dragNeedsUpdate = true; const maxDistance = this._collisionTest(); this._spherical.radius = Math.min(this._spherical.radius, maxDistance); this._spherical.makeSafe(); this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target); this._camera.lookAt(this._target); const affectOffset = !approxZero(this._focalOffset.x) || !approxZero(this._focalOffset.y) || !approxZero(this._focalOffset.z); if (affectOffset) { this._camera.matrix.compose(this._camera.position, this._camera.quaternion, this._camera.scale); _xColumn.setFromMatrixColumn(this._camera.matrix, 0); _yColumn.setFromMatrixColumn(this._camera.matrix, 1); _zColumn.setFromMatrixColumn(this._camera.matrix, 2); _xColumn.multiplyScalar(this._focalOffset.x); _yColumn.multiplyScalar(-this._focalOffset.y); _zColumn.multiplyScalar(this._focalOffset.z); _v3A.copy(_xColumn).add(_yColumn).add(_zColumn); this._camera.position.add(_v3A); this._camera.updateMatrixWorld(); } if (this._boundaryEnclosesCamera) { this._encloseToBoundary(this._camera.position.copy(this._target), _v3A.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse), 1); } const updated = this._needsUpdate; if (updated && !this._updatedLastTime) { this._hasRested = false; this.dispatchEvent({ type: "wake" }); this.dispatchEvent({ type: "update" }); } else if (updated) { this.dispatchEvent({ type: "update" }); if (approxZero(deltaTheta, this.restThreshold) && approxZero(deltaPhi, this.restThreshold) && approxZero(deltaRadius, this.restThreshold) && approxZero(deltaTarget.x, this.restThreshold) && approxZero(deltaTarget.y, this.restThreshold) && approxZero(deltaTarget.z, this.restThreshold) && approxZero(deltaOffset.x, this.restThreshold) && approxZero(deltaOffset.y, this.restThreshold) && approxZero(deltaOffset.z, this.restThreshold) && approxZero(deltaZoom, this.restThreshold) && !this._hasRested) { this._hasRested = true; this.dispatchEvent({ type: "rest" }); } } else if (!updated && this._updatedLastTime) { this.dispatchEvent({ type: "sleep" }); } this._lastDistance = this._spherical.radius; this._lastZoom = this._zoom; this._updatedLastTime = updated; this._needsUpdate = false; return updated; } /** * Get all state in JSON string * @category Methods */ toJSON() { return JSON.stringify({ enabled: this._enabled, minDistance: this.minDistance, maxDistance: infinityToMaxNumber(this.maxDistance), minZoom: this.minZoom, maxZoom: infinityToMaxNumber(this.maxZoom), minPolarAngle: this.minPolarAngle, maxPolarAngle: infinityToMaxNumber(this.maxPolarAngle), minAzimuthAngle: infinityToMaxNumber(this.minAzimuthAngle), maxAzimuthAngle: infinityToMaxNumber(this.maxAzimuthAngle), smoothTime: this.smoothTime, draggingSmoothTime: this.draggingSmoothTime, dollySpeed: this.dollySpeed, truckSpeed: this.truckSpeed, dollyToCursor: this.dollyToCursor, target: this._targetEnd.toArray(), position: _v3A.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(), zoom: this._zoomEnd, focalOffset: this._focalOffsetEnd.toArray(), target0: this._target0.toArray(), position0: this._position0.toArray(), zoom0: this._zoom0, focalOffset0: this._focalOffset0.toArray() }); } /** * Reproduce the control state with JSON. enableTransition is where anim or not in a boolean. * @param json * @param enableTransition * @category Methods */ fromJSON(json, enableTransition = false) { const obj = JSON.parse(json); this.enabled = obj.enabled; this.minDistance = obj.minDistance; this.maxDistance = maxNumberToInfinity(obj.maxDistance); this.minZoom = obj.minZoom; this.maxZoom = maxNumberToInfinity(obj.maxZoom); this.minPolarAngle = obj.minPolarAngle; this.maxPolarAngle = maxNumberToInfinity(obj.maxPolarAngle); this.minAzimuthAngle = maxNumberToInfinity(obj.minAzimuthAngle); this.maxAzimuthAngle = maxNumberToInfinity(obj.maxAzimuthAngle); this.smoothTime = obj.smoothTime; this.draggingSmoothTime = obj.draggingSmoothTime; this.dollySpeed = obj.dollySpeed; this.truckSpeed = obj.truckSpeed; this.dollyToCursor = obj.dollyToCursor; this._target0.fromArray(obj.target0); this._position0.fromArray(obj.position0); this._zoom0 = obj.zoom0; this._focalOffset0.fromArray(obj.focalOffset0); this.moveTo(obj.target[0], obj.target[1], obj.target[2], enableTransition); _sphericalA.setFromVector3(_v3A.fromArray(obj.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)); this.rotateTo(_sphericalA.theta, _sphericalA.phi, enableTransition); this.dollyTo(_sphericalA.radius, enableTransition); this.zoomTo(obj.zoom, enableTransition); this.setFocalOffset(obj.focalOffset[0], obj.focalOffset[1], obj.focalOffset[2], enableTransition); this._needsUpdate = true; } /** * Attach all internal event handlers to enable drag control. * @category Methods */ connect(domElement) { if (this._domElement) { console.warn("camera-controls is already connected."); return; } domElement.setAttribute("data-camera-controls-version", VERSION); this._addAllEventListeners(domElement); this._getClientRect(this._elementRect); } /** * Detach all internal event handlers to disable drag control. */ disconnect() { this.cancel(); this._removeAllEventListeners(); if (this._domElement) { this._domElement.removeAttribute("data-camera-controls-version"); this._domElement = void 0; } } /** * Dispose the cameraControls instance itself, remove all eventListeners. * @category Methods */ dispose() { this.removeAllEventListeners(); this.disconnect(); } // it's okay to expose public though _getTargetDirection(out7) { return out7.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse); } // it's okay to expose public though _getCameraDirection(out7) { return this._getTargetDirection(out7).negate(); } _findPointerById(pointerId2) { return this._activePointers.find((activePointer) => activePointer.pointerId === pointerId2); } _findPointerByMouseButton(mouseButton) { return this._activePointers.find((activePointer) => activePointer.mouseButton === mouseButton); } _disposePointer(pointer) { this._activePointers.splice(this._activePointers.indexOf(pointer), 1); } _encloseToBoundary(position2, offset, friction) { const offsetLength2 = offset.lengthSq(); if (offsetLength2 === 0) { return position2; } const newTarget = _v3B.copy(offset).add(position2); const clampedTarget = this._boundary.clampPoint(newTarget, _v3C); const deltaClampedTarget = clampedTarget.sub(newTarget); const deltaClampedTargetLength2 = deltaClampedTarget.lengthSq(); if (deltaClampedTargetLength2 === 0) { return position2.add(offset); } else if (deltaClampedTargetLength2 === offsetLength2) { return position2; } else if (friction === 0) { return position2.add(offset).add(deltaClampedTarget); } else { const offsetFactor = 1 + friction * deltaClampedTargetLength2 / offset.dot(deltaClampedTarget); return position2.add(_v3B.copy(offset).multiplyScalar(offsetFactor)).add(deltaClampedTarget.multiplyScalar(1 - friction)); } } _updateNearPlaneCorners() { if (isPerspectiveCamera(this._camera)) { const camera = this._camera; const near = camera.near; const fov = camera.getEffectiveFOV() * DEG2RAD; const heightHalf = Math.tan(fov * 0.5) * near; const widthHalf = heightHalf * camera.aspect; this._nearPlaneCorners[0].set(-widthHalf, -heightHalf, 0); this._nearPlaneCorners[1].set(widthHalf, -heightHalf, 0); this._nearPlaneCorners[2].set(widthHalf, heightHalf, 0); this._nearPlaneCorners[3].set(-widthHalf, heightHalf, 0); } else if (isOrthographicCamera(this._camera)) { const camera = this._camera; const zoomInv = 1 / camera.zoom; const left = camera.left * zoomInv; const right = camera.right * zoomInv; const top = camera.top * zoomInv; const bottom = camera.bottom * zoomInv; this._nearPlaneCorners[0].set(left, top, 0); this._nearPlaneCorners[1].set(right, top, 0); this._nearPlaneCorners[2].set(right, bottom, 0); this._nearPlaneCorners[3].set(left, bottom, 0); } } _truckInternal = (deltaX, deltaY, dragToOffset, screenSpacePanning) => { let truckX; let pedestalY; if (isPerspectiveCamera(this._camera)) { const offset = _v3A.copy(this._camera.position).sub(this._target); const fov = this._camera.getEffectiveFOV() * DEG2RAD; const targetDistance = offset.length() * Math.tan(fov * 0.5); truckX = this.truckSpeed * deltaX * targetDistance / this._elementRect.height; pedestalY = this.truckSpeed * deltaY * targetDistance / this._elementRect.height; } else if (isOrthographicCamera(this._camera)) { const camera = this._camera; truckX = this.truckSpeed * deltaX * (camera.right - camera.left) / camera.zoom / this._elementRect.width; pedestalY = this.truckSpeed * deltaY * (camera.top - camera.bottom) / camera.zoom / this._elementRect.height; } else { return; } if (screenSpacePanning) { dragToOffset ? this.setFocalOffset(this._focalOffsetEnd.x + truckX, this._focalOffsetEnd.y, this._focalOffsetEnd.z, true) : this.truck(truckX, 0, true); this.forward(-pedestalY, true); } else { dragToOffset ? this.setFocalOffset(this._focalOffsetEnd.x + truckX, this._focalOffsetEnd.y + pedestalY, this._focalOffsetEnd.z, true) : this.truck(truckX, pedestalY, true); } }; _rotateInternal = (deltaX, deltaY) => { const theta = PI_2 * this.azimuthRotateSpeed * deltaX / this._elementRect.height; const phi = PI_2 * this.polarRotateSpeed * deltaY / this._elementRect.height; this.rotate(theta, phi, true); }; _dollyInternal = (delta, x, y) => { const dollyScale = Math.pow(0.95, -delta * this.dollySpeed); const lastDistance = this._sphericalEnd.radius; const distance3 = this._sphericalEnd.radius * dollyScale; const clampedDistance = clamp3(distance3, this.minDistance, this.maxDistance); const overflowedDistance = clampedDistance - distance3; if (this.infinityDolly && this.dollyToCursor) { this._dollyToNoClamp(distance3, true); } else if (this.infinityDolly && !this.dollyToCursor) { this.dollyInFixed(overflowedDistance, true); this._dollyToNoClamp(clampedDistance, true); } else { this._dollyToNoClamp(clampedDistance, true); } if (this.dollyToCursor) { this._changedDolly += (this.infinityDolly ? distance3 : clampedDistance) - lastDistance; this._dollyControlCoord.set(x, y); } this._lastDollyDirection = Math.sign(-delta); }; _zoomInternal = (delta, x, y) => { const zoomScale = Math.pow(0.95, delta * this.dollySpeed); const lastZoom = this._zoom; const zoom = this._zoom * zoomScale; this.zoomTo(zoom, true); if (this.dollyToCursor) { this._changedZoom += zoom - lastZoom; this._dollyControlCoord.set(x, y); } }; // lateUpdate _collisionTest() { let distance3 = Infinity; const hasCollider = this.colliderMeshes.length >= 1; if (!hasCollider) return distance3; if (notSupportedInOrthographicCamera(this._camera, "_collisionTest")) return distance3; const rayDirection = this._getTargetDirection(_cameraDirection); _rotationMatrix.lookAt(_ORIGIN, rayDirection, this._camera.up); for (let i4 = 0; i4 < 4; i4++) { const nearPlaneCorner = _v3B.copy(this._nearPlaneCorners[i4]); nearPlaneCorner.applyMatrix4(_rotationMatrix); const origin2 = _v3C.addVectors(this._target, nearPlaneCorner); _raycaster.set(origin2, rayDirection); _raycaster.far = this._spherical.radius + 1; const intersects = _raycaster.intersectObjects(this.colliderMeshes); if (intersects.length !== 0 && intersects[0].distance < distance3) { distance3 = intersects[0].distance; } } return distance3; } /** * Get its client rect and package into given `DOMRect` . */ _getClientRect(target2) { if (!this._domElement) return; const rect = this._domElement.getBoundingClientRect(); target2.x = rect.left; target2.y = rect.top; if (this._viewport) { target2.x += this._viewport.x; target2.y += rect.height - this._viewport.w - this._viewport.y; target2.width = this._viewport.z; target2.height = this._viewport.w; } else { target2.width = rect.width; target2.height = rect.height; } return target2; } _createOnRestPromise(resolveImmediately) { if (resolveImmediately) return Promise.resolve(); this._hasRested = false; this.dispatchEvent({ type: "transitionstart" }); return new Promise((resolve) => { const onResolve = () => { this.removeEventListener("rest", onResolve); resolve(); }; this.addEventListener("rest", onResolve); }); } // eslint-disable-next-line @typescript-eslint/no-unused-vars _addAllEventListeners(_domElement) { } _removeAllEventListeners() { } /** * backward compatible * @deprecated use smoothTime (in seconds) instead * @category Properties */ get dampingFactor() { console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."); return 0; } /** * backward compatible * @deprecated use smoothTime (in seconds) instead * @category Properties */ set dampingFactor(_) { console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."); } /** * backward compatible * @deprecated use draggingSmoothTime (in seconds) instead * @category Properties */ get draggingDampingFactor() { console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."); return 0; } /** * backward compatible * @deprecated use draggingSmoothTime (in seconds) instead * @category Properties */ set draggingDampingFactor(_) { console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."); } static createBoundingSphere(object3d, out7 = new THREE.Sphere()) { const boundingSphere = out7; const center3 = boundingSphere.center; _box3A.makeEmpty(); object3d.traverseVisible((object) => { if (!object.isMesh) return; _box3A.expandByObject(object); }); _box3A.getCenter(center3); let maxRadiusSq = 0; object3d.traverseVisible((object) => { if (!object.isMesh) return; const mesh = object; if (!mesh.geometry) return; const geometry3 = mesh.geometry.clone(); geometry3.applyMatrix4(mesh.matrixWorld); const bufferGeometry = geometry3; const position2 = bufferGeometry.attributes.position; for (let i4 = 0, l2 = position2.count; i4 < l2; i4++) { _v3A.fromBufferAttribute(position2, i4); maxRadiusSq = Math.max(maxRadiusSq, center3.distanceToSquared(_v3A)); } }); boundingSphere.radius = Math.sqrt(maxRadiusSq); return boundingSphere; } }; // node_modules/@react-three/drei/core/CameraControls.js var CameraControls3 = (0, import_react12.forwardRef)((props, ref) => { const { impl: SubclassImpl, camera, domElement, makeDefault, onControlStart, onControl, onControlEnd, onTransitionStart, onUpdate, onWake, onRest, onSleep, onStart, onEnd, onChange, regress, ...restProps } = props; const Impl = SubclassImpl !== null && SubclassImpl !== void 0 ? SubclassImpl : CameraControls2; (0, import_react12.useMemo)(() => { const subsetOfTHREE = { Box3, MathUtils: { clamp: MathUtils.clamp }, Matrix4, Quaternion, Raycaster, Sphere, Spherical, Vector2, Vector3, Vector4 }; Impl.install({ THREE: subsetOfTHREE }); extend({ CameraControlsImpl: Impl }); }, [Impl]); const defaultCamera = useThree((state) => state.camera); const gl = useThree((state) => state.gl); const invalidate = useThree((state) => state.invalidate); const events = useThree((state) => state.events); const setEvents = useThree((state) => state.setEvents); const set = useThree((state) => state.set); const get = useThree((state) => state.get); const performance2 = useThree((state) => state.performance); const explCamera = camera || defaultCamera; const explDomElement = domElement || events.connected || gl.domElement; const controls = (0, import_react12.useMemo)(() => new Impl(explCamera), [Impl, explCamera]); useFrame((state, delta) => { controls.update(delta); }, -1); (0, import_react12.useEffect)(() => { controls.connect(explDomElement); return () => void controls.disconnect(); }, [explDomElement, controls]); (0, import_react12.useEffect)(() => { function invalidateAndRegress() { invalidate(); if (regress) performance2.regress(); } const handleControlStart = (e2) => { invalidateAndRegress(); onControlStart == null || onControlStart(e2); onStart == null || onStart(e2); }; const handleControl = (e2) => { invalidateAndRegress(); onControl == null || onControl(e2); onChange == null || onChange(e2); }; const handleControlEnd = (e2) => { onControlEnd == null || onControlEnd(e2); onEnd == null || onEnd(e2); }; const handleTransitionStart = (e2) => { invalidateAndRegress(); onTransitionStart == null || onTransitionStart(e2); onChange == null || onChange(e2); }; const handleUpdate = (e2) => { invalidateAndRegress(); onUpdate == null || onUpdate(e2); onChange == null || onChange(e2); }; const handleWake = (e2) => { invalidateAndRegress(); onWake == null || onWake(e2); onChange == null || onChange(e2); }; const handleRest = (e2) => { onRest == null || onRest(e2); }; const handleSleep = (e2) => { onSleep == null || onSleep(e2); }; controls.addEventListener("controlstart", handleControlStart); controls.addEventListener("control", handleControl); controls.addEventListener("controlend", handleControlEnd); controls.addEventListener("transitionstart", handleTransitionStart); controls.addEventListener("update", handleUpdate); controls.addEventListener("wake", handleWake); controls.addEventListener("rest", handleRest); controls.addEventListener("sleep", handleSleep); return () => { controls.removeEventListener("controlstart", handleControlStart); controls.removeEventListener("control", handleControl); controls.removeEventListener("controlend", handleControlEnd); controls.removeEventListener("transitionstart", handleTransitionStart); controls.removeEventListener("update", handleUpdate); controls.removeEventListener("wake", handleWake); controls.removeEventListener("rest", handleRest); controls.removeEventListener("sleep", handleSleep); }; }, [controls, invalidate, setEvents, regress, performance2, onControlStart, onControl, onControlEnd, onTransitionStart, onUpdate, onWake, onRest, onSleep, onChange, onStart, onEnd]); (0, import_react12.useEffect)(() => { if (makeDefault) { const old = get().controls; set({ controls }); return () => set({ controls: old }); } }, [makeDefault, controls]); return React52.createElement("primitive", _extends({ ref, object: controls }, restProps)); }); // node_modules/@react-three/drei/core/MotionPathControls.js var React53 = __toESM(require_react()); var isObject3DRef = (ref) => (ref == null ? void 0 : ref.current) instanceof Object3D; var MotionContext = React53.createContext(null); function useMotion() { const context12 = React53.useContext(MotionContext); if (!context12) throw new Error("useMotion hook must be used in a MotionPathControls component."); return context12; } function Debug({ points = 50, color = "black" }) { const { path } = useMotion(); const [dots, setDots] = React53.useState([]); const material = React53.useMemo(() => new MeshBasicMaterial({ color }), [color]); const geometry3 = React53.useMemo(() => new SphereGeometry(0.025, 16, 16), []); const last = React53.useRef([]); React53.useEffect(() => { if (path.curves !== last.current) { setDots(path.getPoints(points)); last.current = path.curves; } }); return dots.map((item, index2) => React53.createElement("mesh", { key: index2, material, geometry: geometry3, position: [item.x, item.y, item.z] })); } var MotionPathControls = React53.forwardRef(({ children, curves = [], debug = false, debugColor = "black", object, focus, loop = true, offset = void 0, smooth = false, eps: eps2 = 1e-5, damping = 0.1, focusDamping = 0.1, maxSpeed = Infinity, ...props }, fref) => { const { camera } = useThree(); const ref = React53.useRef(null); const pos = React53.useRef(offset !== null && offset !== void 0 ? offset : 0); const path = React53.useMemo(() => new CurvePath(), []); const state = React53.useMemo(() => ({ focus, object: (object == null ? void 0 : object.current) instanceof Object3D ? object : { current: camera }, path, current: pos.current, offset: pos.current, point: new Vector3(), tangent: new Vector3(), next: new Vector3() }), [focus, object]); const instanceRef = useInstanceHandle(ref); React53.useLayoutEffect(() => { const instance2 = instanceRef.current; path.curves = []; const _curves = curves.length > 0 ? curves : instance2.children.map((instance3) => instance3.object); for (let i4 = 0; i4 < _curves.length; i4++) path.add(_curves[i4]); if (smooth) { const points = path.getPoints(typeof smooth === "number" ? smooth : 1); const catmull = new CatmullRomCurve3(points); path.curves = [catmull]; } path.updateArcLengths(); }); React53.useImperativeHandle(fref, () => Object.assign(ref.current, { motion: state }), [state]); React53.useLayoutEffect(() => { pos.current = misc.repeat(pos.current, 1); }, [offset]); const vec = React53.useMemo(() => new Vector3(), []); useFrame((_state, delta) => { const lastOffset = state.offset; easing.damp(pos, "current", offset !== void 0 ? offset : state.current, damping, delta, maxSpeed, void 0, eps2); state.offset = loop ? misc.repeat(pos.current, 1) : misc.clamp(pos.current, 0, 1); if (path.getCurveLengths().length > 0) { path.getPointAt(state.offset, state.point); path.getTangentAt(state.offset, state.tangent).normalize(); path.getPointAt(misc.repeat(pos.current - (lastOffset - state.offset), 1), state.next); const target2 = (object == null ? void 0 : object.current) instanceof Object3D ? object.current : camera; target2.position.copy(state.point); if (focus) { easing.dampLookAt(target2, isObject3DRef(focus) ? focus.current.getWorldPosition(vec) : focus, focusDamping, delta, maxSpeed, void 0, eps2); } } }); return React53.createElement("group", _extends({ ref }, props), React53.createElement(MotionContext.Provider, { value: state }, children, debug && React53.createElement(Debug, { color: debugColor }))); }); // node_modules/@react-three/drei/core/GizmoHelper.js var React55 = __toESM(require_react()); // node_modules/@react-three/drei/core/Hud.js var React54 = __toESM(require_react()); function RenderHud({ defaultScene, defaultCamera, renderPriority = 1 }) { const { gl, scene, camera } = useThree(); let oldCLear; useFrame(() => { oldCLear = gl.autoClear; if (renderPriority === 1) { gl.autoClear = true; gl.render(defaultScene, defaultCamera); } gl.autoClear = false; gl.clearDepth(); gl.render(scene, camera); gl.autoClear = oldCLear; }, renderPriority); return React54.createElement("group", { onPointerOver: () => null }); } function Hud({ children, renderPriority = 1 }) { const { scene: defaultScene, camera: defaultCamera } = useThree(); const [hudScene] = React54.useState(() => new Scene()); return React54.createElement(React54.Fragment, null, createPortal(React54.createElement(React54.Fragment, null, children, React54.createElement(RenderHud, { defaultScene, defaultCamera, renderPriority })), hudScene, { events: { priority: renderPriority + 1 } })); } // node_modules/@react-three/drei/core/GizmoHelper.js var Context = React55.createContext({}); var useGizmoContext = () => { return React55.useContext(Context); }; var turnRate = 2 * Math.PI; var dummy = new Object3D(); var matrix4 = new Matrix4(); var [q1, q2] = [new Quaternion(), new Quaternion()]; var target = new Vector3(); var targetPosition2 = new Vector3(); var isOrbitControls = (controls) => { return "minPolarAngle" in controls; }; var isCameraControls = (controls) => { return "getTarget" in controls; }; var GizmoHelper = ({ alignment = "bottom-right", margin = [80, 80], renderPriority = 1, onUpdate, onTarget, children }) => { const size2 = useThree((state) => state.size); const mainCamera = useThree((state) => state.camera); const defaultControls = useThree((state) => state.controls); const invalidate = useThree((state) => state.invalidate); const gizmoRef = React55.useRef(null); const virtualCam = React55.useRef(null); const animating = React55.useRef(false); const radius = React55.useRef(0); const focusPoint = React55.useRef(new Vector3(0, 0, 0)); const defaultUp = React55.useRef(new Vector3(0, 0, 0)); React55.useEffect(() => { defaultUp.current.copy(mainCamera.up); dummy.up.copy(mainCamera.up); }, [mainCamera]); const tweenCamera = React55.useCallback((direction2) => { animating.current = true; if (defaultControls || onTarget) { focusPoint.current = (onTarget == null ? void 0 : onTarget()) || (isCameraControls(defaultControls) ? defaultControls.getTarget(focusPoint.current) : defaultControls == null ? void 0 : defaultControls.target); } radius.current = mainCamera.position.distanceTo(target); q1.copy(mainCamera.quaternion); targetPosition2.copy(direction2).multiplyScalar(radius.current).add(target); dummy.lookAt(targetPosition2); q2.copy(dummy.quaternion); invalidate(); }, [defaultControls, mainCamera, onTarget, invalidate]); useFrame((_, delta) => { if (virtualCam.current && gizmoRef.current) { var _gizmoRef$current; if (animating.current) { if (q1.angleTo(q2) < 0.01) { animating.current = false; if (isOrbitControls(defaultControls)) { mainCamera.up.copy(defaultUp.current); } } else { const step = delta * turnRate; q1.rotateTowards(q2, step); mainCamera.position.set(0, 0, 1).applyQuaternion(q1).multiplyScalar(radius.current).add(focusPoint.current); mainCamera.up.set(0, 1, 0).applyQuaternion(q1).normalize(); mainCamera.quaternion.copy(q1); if (isCameraControls(defaultControls)) defaultControls.setPosition(mainCamera.position.x, mainCamera.position.y, mainCamera.position.z); if (onUpdate) onUpdate(); else if (defaultControls) defaultControls.update(delta); invalidate(); } } matrix4.copy(mainCamera.matrix).invert(); (_gizmoRef$current = gizmoRef.current) == null || _gizmoRef$current.quaternion.setFromRotationMatrix(matrix4); } }); const gizmoHelperContext = React55.useMemo(() => ({ tweenCamera }), [tweenCamera]); const [marginX, marginY] = margin; const x = alignment.endsWith("-center") ? 0 : alignment.endsWith("-left") ? -size2.width / 2 + marginX : size2.width / 2 - marginX; const y = alignment.startsWith("center-") ? 0 : alignment.startsWith("top-") ? size2.height / 2 - marginY : -size2.height / 2 + marginY; return React55.createElement(Hud, { renderPriority }, React55.createElement(Context.Provider, { value: gizmoHelperContext }, React55.createElement(OrthographicCamera2, { makeDefault: true, ref: virtualCam, position: [0, 0, 200] }), React55.createElement("group", { ref: gizmoRef, position: [x, y, 0] }, children))); }; // node_modules/@react-three/drei/core/GizmoViewcube.js var React56 = __toESM(require_react()); var colors = { bg: "#f0f0f0", hover: "#999", text: "black", stroke: "black" }; var defaultFaces = ["Right", "Left", "Top", "Bottom", "Front", "Back"]; var makePositionVector = (xyz) => new Vector3(...xyz).multiplyScalar(0.38); var corners = [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1]].map(makePositionVector); var cornerDimensions = [0.25, 0.25, 0.25]; var edges = [[1, 1, 0], [1, 0, 1], [1, 0, -1], [1, -1, 0], [0, 1, 1], [0, 1, -1], [0, -1, 1], [0, -1, -1], [-1, 1, 0], [-1, 0, 1], [-1, 0, -1], [-1, -1, 0]].map(makePositionVector); var edgeDimensions = edges.map((edge) => edge.toArray().map((axis) => axis == 0 ? 0.5 : 0.25)); var FaceMaterial = ({ hover, index: index2, font = "20px Inter var, Arial, sans-serif", faces = defaultFaces, color = colors.bg, hoverColor = colors.hover, textColor = colors.text, strokeColor = colors.stroke, opacity = 1 }) => { const gl = useThree((state) => state.gl); const texture = React56.useMemo(() => { const canvas = document.createElement("canvas"); canvas.width = 128; canvas.height = 128; const context12 = canvas.getContext("2d"); context12.fillStyle = color; context12.fillRect(0, 0, canvas.width, canvas.height); context12.strokeStyle = strokeColor; context12.strokeRect(0, 0, canvas.width, canvas.height); context12.font = font; context12.textAlign = "center"; context12.fillStyle = textColor; context12.fillText(faces[index2].toUpperCase(), 64, 76); return new CanvasTexture(canvas); }, [index2, faces, font, color, textColor, strokeColor]); return React56.createElement("meshBasicMaterial", { map: texture, "map-anisotropy": gl.capabilities.getMaxAnisotropy() || 1, attach: `material-${index2}`, color: hover ? hoverColor : "white", transparent: true, opacity }); }; var FaceCube = (props) => { const { tweenCamera } = useGizmoContext(); const [hover, setHover] = React56.useState(null); const handlePointerOut = (e2) => { e2.stopPropagation(); setHover(null); }; const handleClick = (e2) => { e2.stopPropagation(); tweenCamera(e2.face.normal); }; const handlePointerMove = (e2) => { e2.stopPropagation(); setHover(Math.floor(e2.faceIndex / 2)); }; return React56.createElement("mesh", { onPointerOut: handlePointerOut, onPointerMove: handlePointerMove, onClick: props.onClick || handleClick }, [...Array(6)].map((_, index2) => React56.createElement(FaceMaterial, _extends({ key: index2, index: index2, hover: hover === index2 }, props))), React56.createElement("boxGeometry", null)); }; var EdgeCube = ({ onClick, dimensions, position: position2, hoverColor = colors.hover }) => { const { tweenCamera } = useGizmoContext(); const [hover, setHover] = React56.useState(false); const handlePointerOut = (e2) => { e2.stopPropagation(); setHover(false); }; const handlePointerOver = (e2) => { e2.stopPropagation(); setHover(true); }; const handleClick = (e2) => { e2.stopPropagation(); tweenCamera(position2); }; return React56.createElement("mesh", { scale: 1.01, position: position2, onPointerOver: handlePointerOver, onPointerOut: handlePointerOut, onClick: onClick || handleClick }, React56.createElement("meshBasicMaterial", { color: hover ? hoverColor : "white", transparent: true, opacity: 0.6, visible: hover }), React56.createElement("boxGeometry", { args: dimensions })); }; var GizmoViewcube = (props) => { return React56.createElement("group", { scale: [60, 60, 60] }, React56.createElement(FaceCube, props), edges.map((edge, index2) => React56.createElement(EdgeCube, _extends({ key: index2, position: edge, dimensions: edgeDimensions[index2] }, props))), corners.map((corner, index2) => React56.createElement(EdgeCube, _extends({ key: index2, position: corner, dimensions: cornerDimensions }, props)))); }; // node_modules/@react-three/drei/core/GizmoViewport.js var React57 = __toESM(require_react()); function Axis({ scale: scale5 = [0.8, 0.05, 0.05], color, rotation: rotation3 }) { return React57.createElement("group", { rotation: rotation3 }, React57.createElement("mesh", { position: [0.4, 0, 0] }, React57.createElement("boxGeometry", { args: scale5 }), React57.createElement("meshBasicMaterial", { color, toneMapped: false }))); } function AxisHead({ onClick, font, disabled, arcStyle, label, labelColor, axisHeadScale = 1, ...props }) { const gl = useThree((state) => state.gl); const texture = React57.useMemo(() => { const canvas = document.createElement("canvas"); canvas.width = 64; canvas.height = 64; const context12 = canvas.getContext("2d"); context12.beginPath(); context12.arc(32, 32, 16, 0, 2 * Math.PI); context12.closePath(); context12.fillStyle = arcStyle; context12.fill(); if (label) { context12.font = font; context12.textAlign = "center"; context12.fillStyle = labelColor; context12.fillText(label, 32, 41); } return new CanvasTexture(canvas); }, [arcStyle, label, labelColor, font]); const [active, setActive] = React57.useState(false); const scale5 = (label ? 1 : 0.75) * (active ? 1.2 : 1) * axisHeadScale; const handlePointerOver = (e2) => { e2.stopPropagation(); setActive(true); }; const handlePointerOut = (e2) => { e2.stopPropagation(); setActive(false); }; return React57.createElement("sprite", _extends({ scale: scale5, onPointerOver: !disabled ? handlePointerOver : void 0, onPointerOut: !disabled ? onClick || handlePointerOut : void 0 }, props), React57.createElement("spriteMaterial", { map: texture, "map-anisotropy": gl.capabilities.getMaxAnisotropy() || 1, alphaTest: 0.3, opacity: label ? 1 : 0.75, toneMapped: false })); } var GizmoViewport = ({ hideNegativeAxes, hideAxisHeads, disabled, font = "18px Inter var, Arial, sans-serif", axisColors = ["#ff2060", "#20df80", "#2080ff"], axisHeadScale = 1, axisScale, labels = ["X", "Y", "Z"], labelColor = "#000", onClick, ...props }) => { const [colorX, colorY, colorZ] = axisColors; const { tweenCamera } = useGizmoContext(); const axisHeadProps = { font, disabled, labelColor, onClick, axisHeadScale, onPointerDown: !disabled ? (e2) => { tweenCamera(e2.object.position); e2.stopPropagation(); } : void 0 }; return React57.createElement("group", _extends({ scale: 40 }, props), React57.createElement(Axis, { color: colorX, rotation: [0, 0, 0], scale: axisScale }), React57.createElement(Axis, { color: colorY, rotation: [0, 0, Math.PI / 2], scale: axisScale }), React57.createElement(Axis, { color: colorZ, rotation: [0, -Math.PI / 2, 0], scale: axisScale }), !hideAxisHeads && React57.createElement(React57.Fragment, null, React57.createElement(AxisHead, _extends({ arcStyle: colorX, position: [1, 0, 0], label: labels[0] }, axisHeadProps)), React57.createElement(AxisHead, _extends({ arcStyle: colorY, position: [0, 1, 0], label: labels[1] }, axisHeadProps)), React57.createElement(AxisHead, _extends({ arcStyle: colorZ, position: [0, 0, 1], label: labels[2] }, axisHeadProps)), !hideNegativeAxes && React57.createElement(React57.Fragment, null, React57.createElement(AxisHead, _extends({ arcStyle: colorX, position: [-1, 0, 0] }, axisHeadProps)), React57.createElement(AxisHead, _extends({ arcStyle: colorY, position: [0, -1, 0] }, axisHeadProps)), React57.createElement(AxisHead, _extends({ arcStyle: colorZ, position: [0, 0, -1] }, axisHeadProps))))); }; // node_modules/@react-three/drei/core/Grid.js var React58 = __toESM(require_react()); var GridMaterial = shaderMaterial( { cellSize: 0.5, sectionSize: 1, fadeDistance: 100, fadeStrength: 1, fadeFrom: 1, cellThickness: 0.5, sectionThickness: 1, cellColor: new Color(), sectionColor: new Color(), infiniteGrid: false, followCamera: false, worldCamProjPosition: new Vector3(), worldPlanePosition: new Vector3() }, /* glsl */ ` varying vec3 localPosition; varying vec4 worldPosition; uniform vec3 worldCamProjPosition; uniform vec3 worldPlanePosition; uniform float fadeDistance; uniform bool infiniteGrid; uniform bool followCamera; void main() { localPosition = position.xzy; if (infiniteGrid) localPosition *= 1.0 + fadeDistance; worldPosition = modelMatrix * vec4(localPosition, 1.0); if (followCamera) { worldPosition.xyz += (worldCamProjPosition - worldPlanePosition); localPosition = (inverse(modelMatrix) * worldPosition).xyz; } gl_Position = projectionMatrix * viewMatrix * worldPosition; } `, /* glsl */ ` varying vec3 localPosition; varying vec4 worldPosition; uniform vec3 worldCamProjPosition; uniform float cellSize; uniform float sectionSize; uniform vec3 cellColor; uniform vec3 sectionColor; uniform float fadeDistance; uniform float fadeStrength; uniform float fadeFrom; uniform float cellThickness; uniform float sectionThickness; float getGrid(float size, float thickness) { vec2 r = localPosition.xz / size; vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r); float line = min(grid.x, grid.y) + 1.0 - thickness; return 1.0 - min(line, 1.0); } void main() { float g1 = getGrid(cellSize, cellThickness); float g2 = getGrid(sectionSize, sectionThickness); vec3 from = worldCamProjPosition*vec3(fadeFrom); float dist = distance(from, worldPosition.xyz); float d = 1.0 - min(dist / fadeDistance, 1.0); vec3 color = mix(cellColor, sectionColor, min(1.0, sectionThickness * g2)); gl_FragColor = vec4(color, (g1 + g2) * pow(d, fadeStrength)); gl_FragColor.a = mix(0.75 * gl_FragColor.a, gl_FragColor.a, g2); if (gl_FragColor.a <= 0.0) discard; #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> } ` ); var Grid = React58.forwardRef(({ args, cellColor = "#000000", sectionColor = "#2080ff", cellSize = 0.5, sectionSize = 1, followCamera = false, infiniteGrid = false, fadeDistance = 100, fadeStrength = 1, fadeFrom = 1, cellThickness = 0.5, sectionThickness = 1, side = BackSide, ...props }, fRef) => { extend({ GridMaterial }); const ref = React58.useRef(null); React58.useImperativeHandle(fRef, () => ref.current, []); const plane = new Plane(); const upVector = new Vector3(0, 1, 0); const zeroVector = new Vector3(0, 0, 0); useFrame((state) => { plane.setFromNormalAndCoplanarPoint(upVector, zeroVector).applyMatrix4(ref.current.matrixWorld); const gridMaterial = ref.current.material; const worldCamProjPosition = gridMaterial.uniforms.worldCamProjPosition; const worldPlanePosition = gridMaterial.uniforms.worldPlanePosition; plane.projectPoint(state.camera.position, worldCamProjPosition.value); worldPlanePosition.value.set(0, 0, 0).applyMatrix4(ref.current.matrixWorld); }); const uniforms1 = { cellSize, sectionSize, cellColor, sectionColor, cellThickness, sectionThickness }; const uniforms2 = { fadeDistance, fadeStrength, fadeFrom, infiniteGrid, followCamera }; return React58.createElement("mesh", _extends({ ref, frustumCulled: false }, props), React58.createElement("gridMaterial", _extends({ transparent: true, "extensions-derivatives": true, side }, uniforms1, uniforms2)), React58.createElement("planeGeometry", { args })); }); // node_modules/@react-three/drei/core/CubeTexture.js var React59 = __toESM(require_react()); function useCubeTexture(files, { path }) { const [cubeTexture] = useLoader(CubeTextureLoader, [files], (loader2) => loader2.setPath(path)); return cubeTexture; } useCubeTexture.preload = (files, { path }) => useLoader.preload(CubeTextureLoader, [files], (loader2) => loader2.setPath(path)); function CubeTexture2({ children, files, ...options }) { const texture = useCubeTexture(files, { ...options }); return React59.createElement(React59.Fragment, null, children == null ? void 0 : children(texture)); } // node_modules/@react-three/drei/core/Fbx.js var React60 = __toESM(require_react()); function useFBX(path) { return useLoader(FBXLoader, path); } useFBX.preload = (path) => useLoader.preload(FBXLoader, path); useFBX.clear = (input) => useLoader.clear(FBXLoader, input); function Fbx({ path, ...props }) { const fbx = useFBX(path); const object = fbx.children[0]; return React60.createElement(Clone, _extends({}, props, { object })); } // node_modules/@react-three/drei/core/Ktx2.js var React61 = __toESM(require_react()); var import_react13 = __toESM(require_react()); var cdn = "https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master"; function useKTX2(input, basisPath = `${cdn}/basis/`) { const gl = useThree((state) => state.gl); const textures = useLoader(KTX2Loader, IsObject(input) ? Object.values(input) : input, (loader2) => { loader2.detectSupport(gl); loader2.setTranscoderPath(basisPath); }); (0, import_react13.useEffect)(() => { const array = Array.isArray(textures) ? textures : [textures]; array.forEach(gl.initTexture); }, [gl, textures]); if (IsObject(input)) { const keys = Object.keys(input); const keyed = {}; keys.forEach((key) => Object.assign(keyed, { [key]: textures[keys.indexOf(key)] })); return keyed; } else { return textures; } } useKTX2.preload = (url, basisPath = `${cdn}/basis/`) => useLoader.preload(KTX2Loader, url, (loader2) => { loader2.setTranscoderPath(basisPath); }); useKTX2.clear = (input) => useLoader.clear(KTX2Loader, input); var Ktx2 = ({ children, input, basisPath }) => { const texture = useKTX2(input, basisPath); return React61.createElement(React61.Fragment, null, children == null ? void 0 : children(texture)); }; // node_modules/@react-three/drei/core/VideoTexture.js var React62 = __toESM(require_react()); var import_react14 = __toESM(require_react()); var IS_BROWSER = ((_window$document2, _window$navigator2) => typeof window !== "undefined" && typeof ((_window$document2 = window.document) == null ? void 0 : _window$document2.createElement) === "function" && typeof ((_window$navigator2 = window.navigator) == null ? void 0 : _window$navigator2.userAgent) === "string")(); var _HLSModule = null; async function getHls(...args) { var _HLSModule2; (_HLSModule2 = _HLSModule) !== null && _HLSModule2 !== void 0 ? _HLSModule2 : _HLSModule = await import("./hls-Q6LDPZPT.js"); const Ctor = _HLSModule.default; if (Ctor.isSupported()) { return new Ctor(...args); } return null; } function useVideoTexture(srcOrSrcObject, { unsuspend = "loadedmetadata", start = true, hls: hlsConfig = {}, crossOrigin = "anonymous", muted = true, loop = true, playsInline = true, onVideoFrame, ...videoProps } = {}) { const gl = useThree((state) => state.gl); const hlsRef = (0, import_react14.useRef)(null); const texture = suspend(() => new Promise(async (res) => { let src = void 0; let srcObject = void 0; if (typeof srcOrSrcObject === "string") { src = srcOrSrcObject; } else { srcObject = srcOrSrcObject; } const video2 = Object.assign(document.createElement("video"), { src, srcObject, crossOrigin, loop, muted, playsInline, ...videoProps }); if (src && IS_BROWSER && src.endsWith(".m3u8")) { const hls = hlsRef.current = await getHls(hlsConfig); if (hls) { hls.on(Events.MEDIA_ATTACHED, () => void hls.loadSource(src)); hls.attachMedia(video2); } } const texture2 = new VideoTexture(video2); texture2.colorSpace = gl.outputColorSpace; video2.addEventListener(unsuspend, () => res(texture2)); }), [srcOrSrcObject]); const video = texture.source.data; useVideoFrame(video, onVideoFrame); (0, import_react14.useEffect)(() => { start && texture.image.play(); return () => { if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; } }; }, [texture, start]); return texture; } var VideoTexture2 = (0, import_react14.forwardRef)(({ children, src, ...config }, fref) => { const texture = useVideoTexture(src, config); (0, import_react14.useEffect)(() => { return () => void texture.dispose(); }, [texture]); (0, import_react14.useImperativeHandle)(fref, () => texture, [texture]); return React62.createElement(React62.Fragment, null, children == null ? void 0 : children(texture)); }); var useVideoFrame = (video, f2) => { (0, import_react14.useEffect)(() => { if (!f2) return; if (!video.requestVideoFrameCallback) return; let handle; const callback = (...args) => { f2(...args); handle = video.requestVideoFrameCallback(callback); }; video.requestVideoFrameCallback(callback); return () => video.cancelVideoFrameCallback(handle); }, [video, f2]); }; // node_modules/@react-three/drei/core/useSpriteLoader.js var React63 = __toESM(require_react()); var import_react15 = __toESM(require_react()); var getFirstFrame = (frames, frameName) => { if (Array.isArray(frames)) { return frames[0]; } else { const k = frameName !== null && frameName !== void 0 ? frameName : Object.keys(frames)[0]; return frames[k][0]; } }; var checkIfFrameIsEmpty = (frameData) => { for (let i4 = 3; i4 < frameData.length; i4 += 4) { if (frameData[i4] !== 0) { return false; } } return true; }; function useSpriteLoader(input, json, animationNames, numberOfFrames, onLoad, canvasRenderingContext2DSettings) { const viewportRef = React63.useRef(useThree((state) => state.viewport)); const spriteDataRef = React63.useRef(null); const totalFrames = React63.useRef(0); const aspectFactor = 0.1; const inputRef = React63.useRef(input); const jsonRef = React63.useRef(json); const animationFramesRef = React63.useRef(animationNames); const [spriteData, setSpriteData] = (0, import_react15.useState)(null); const [spriteTexture, setSpriteTexture] = React63.useState(new Texture()); const textureLoader = React63.useMemo(() => new TextureLoader(), []); const [spriteObj, setSpriteObj] = (0, import_react15.useState)(null); const calculateAspectRatio = React63.useCallback((width, height, factor) => { const adaptedHeight = height * (viewportRef.current.aspect > width / height ? viewportRef.current.width / width : viewportRef.current.height / height); const adaptedWidth = width * (viewportRef.current.aspect > width / height ? viewportRef.current.width / width : viewportRef.current.height / height); const scaleX = adaptedWidth * factor; const scaleY = adaptedHeight * factor; const currentMaxScale = 1; let finalMaxScaleW = Math.min(currentMaxScale, scaleX); let finalMaxScaleH = Math.min(currentMaxScale, scaleY); if (scaleX > currentMaxScale) { finalMaxScaleW = currentMaxScale; finalMaxScaleH = scaleY / scaleX * currentMaxScale; } return new Vector3(finalMaxScaleW, finalMaxScaleH, 1); }, []); const getRowsAndColumns = React63.useCallback((texture, totalFrames2) => { if (texture.image) { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d", canvasRenderingContext2DSettings); if (!ctx) { throw new Error("Failed to get 2d context"); } canvas.width = texture.image.width; canvas.height = texture.image.height; ctx.drawImage(texture.image, 0, 0); const width = texture.image.width; const height = texture.image.height; const cols = Math.round(Math.sqrt(totalFrames2 * (width / height))); const rows = Math.round(totalFrames2 / cols); const frameWidth = width / cols; const frameHeight = height / rows; const emptyFrames = []; for (let row = 0; row < rows; row++) { for (let col3 = 0; col3 < cols; col3++) { const frameIndex = row * cols + col3; if (frameIndex >= totalFrames2) { emptyFrames.push({ row, col: col3 }); continue; } const frameData = ctx.getImageData(col3 * frameWidth, row * frameHeight, frameWidth, frameHeight).data; const isEmpty = checkIfFrameIsEmpty(frameData); if (isEmpty) { emptyFrames.push({ row, col: col3 }); } } } return { rows, columns: cols, frameWidth, frameHeight, emptyFrames }; } else { return { rows: 0, columns: 0, frameWidth: 0, frameHeight: 0, emptyFrames: [] }; } }, [canvasRenderingContext2DSettings]); const calculateScaleRatio = React63.useCallback((frames) => { const processFrameArray = (frameArray) => { let largestFrame = null; for (const frame of frameArray) { const { w, h } = frame.frame; const area = w * h; if (!largestFrame || area > largestFrame.area) { largestFrame = { w, h, area }; } } const frameArr = frameArray.map((frame) => { const { w, h } = frame.frame; const area = w * h; const scaleRatio = largestFrame ? area === largestFrame.area ? 1 : Math.sqrt(area / largestFrame.area) : 1; return { ...frame, scaleRatio }; }); return frameArr; }; if (Array.isArray(frames)) { return processFrameArray(frames); } else { const result = {}; for (const key in frames) { result[key] = processFrameArray(frames[key]); } return result; } }, []); const parseFrames = React63.useCallback(() => { const sprites = {}; const data = spriteDataRef.current; const delimiters = animationFramesRef.current; if (data) { if (delimiters && Array.isArray(data["frames"])) { for (let i4 = 0; i4 < delimiters.length; i4++) { sprites[delimiters[i4]] = []; for (const value of data["frames"]) { const frameData = value["frame"]; const sourceWidth = value["sourceSize"]["w"]; const sourceHeight = value["sourceSize"]["h"]; if (typeof value["filename"] === "string" && value["filename"].toLowerCase().indexOf(delimiters[i4].toLowerCase()) !== -1) { sprites[delimiters[i4]].push({ ...value, frame: frameData, sourceSize: { w: sourceWidth, h: sourceHeight } }); } } } for (const frame in sprites) { const scaleRatioData = calculateScaleRatio(sprites[frame]); if (Array.isArray(scaleRatioData)) { sprites[frame] = scaleRatioData; } } return sprites; } else if (delimiters && typeof data["frames"] === "object") { for (let i4 = 0; i4 < delimiters.length; i4++) { sprites[delimiters[i4]] = []; for (const innerKey in data["frames"]) { const value = data["frames"][innerKey]; const frameData = value["frame"]; const sourceWidth = value["sourceSize"]["w"]; const sourceHeight = value["sourceSize"]["h"]; if (typeof innerKey === "string" && innerKey.toLowerCase().indexOf(delimiters[i4].toLowerCase()) !== -1) { sprites[delimiters[i4]].push({ ...value, frame: frameData, sourceSize: { w: sourceWidth, h: sourceHeight } }); } } } for (const frame in sprites) { const scaleRatioData = calculateScaleRatio(sprites[frame]); if (Array.isArray(scaleRatioData)) { sprites[frame] = scaleRatioData; } } return sprites; } else { let spritesArr = []; if (data != null && data.frames) { if (Array.isArray(data.frames)) { spritesArr = data.frames.map((frame) => ({ ...frame, x: frame.frame.x, y: frame.frame.y, w: frame.frame.w, h: frame.frame.h })); } else { spritesArr = Object.values(data.frames).flat().map((frame) => ({ ...frame, x: frame.frame.x, y: frame.frame.y, w: frame.frame.w, h: frame.frame.h })); } } return calculateScaleRatio(spritesArr); } } return []; }, [calculateScaleRatio, spriteDataRef]); const parseSpriteData = React63.useCallback((json2, _spriteTexture) => { let aspect = new Vector3(1, 1, 1); if (json2 === null) { if (_spriteTexture && numberOfFrames) { const width = _spriteTexture.image.width; const height = _spriteTexture.image.height; totalFrames.current = numberOfFrames; const { rows, columns, frameWidth, frameHeight, emptyFrames } = getRowsAndColumns(_spriteTexture, numberOfFrames); const nonJsonFrames = { frames: [], meta: { version: "1.0", size: { w: width, h: height }, rows, columns, frameWidth, frameHeight, scale: "1" } }; for (let row = 0; row < rows; row++) { for (let col3 = 0; col3 < columns; col3++) { const isExcluded = (emptyFrames !== null && emptyFrames !== void 0 ? emptyFrames : []).some((coord) => coord.row === row && coord.col === col3); if (isExcluded) { continue; } if (Array.isArray(nonJsonFrames.frames)) { nonJsonFrames.frames.push({ frame: { x: col3 * frameWidth, y: row * frameHeight, w: frameWidth, h: frameHeight }, scaleRatio: 1, rotated: false, trimmed: false, spriteSourceSize: { x: 0, y: 0, w: frameWidth, h: frameHeight }, sourceSize: { w: frameWidth, h: frameHeight } }); } } } aspect = calculateAspectRatio(frameWidth, frameHeight, aspectFactor); spriteDataRef.current = nonJsonFrames; } if (spriteDataRef.current && spriteDataRef.current.frames) { spriteDataRef.current.frames = calculateScaleRatio(spriteDataRef.current.frames); } } else if (_spriteTexture) { spriteDataRef.current = json2; spriteDataRef.current.frames = parseFrames(); totalFrames.current = Array.isArray(json2.frames) ? json2.frames.length : Object.keys(json2.frames).length; const { w, h } = getFirstFrame(json2.frames).sourceSize; aspect = calculateAspectRatio(w, h, aspectFactor); } setSpriteData(spriteDataRef.current); if ("encoding" in _spriteTexture) { _spriteTexture.encoding = 3001; } else if ("colorSpace" in _spriteTexture) { _spriteTexture.colorSpace = SRGBColorSpace; } setSpriteTexture(_spriteTexture); setSpriteObj({ spriteTexture: _spriteTexture, spriteData: spriteDataRef.current, aspect }); }, [getRowsAndColumns, numberOfFrames, parseFrames, calculateAspectRatio, calculateScaleRatio]); const loadJsonAndTextureAndExecuteCallback = React63.useCallback((jsonUrl, textureUrl, callback) => { const jsonPromise = fetch(jsonUrl).then((response) => response.json()); const texturePromise = new Promise((resolve) => { textureLoader.load(textureUrl, resolve); }); Promise.all([jsonPromise, texturePromise]).then((response) => { callback(response[0], response[1]); }); }, [textureLoader]); const loadStandaloneSprite = React63.useCallback((textureUrl) => { if (!textureUrl && !inputRef.current) { throw new Error("Either textureUrl or input must be provided"); } const validUrl = textureUrl !== null && textureUrl !== void 0 ? textureUrl : inputRef.current; if (!validUrl) { throw new Error("A valid texture URL must be provided"); } textureLoader.load(validUrl, (texture) => parseSpriteData(null, texture)); }, [textureLoader, parseSpriteData]); const loadJsonAndTexture = React63.useCallback((textureUrl, jsonUrl) => { if (jsonUrl && textureUrl) { loadJsonAndTextureAndExecuteCallback(jsonUrl, textureUrl, parseSpriteData); } else { loadStandaloneSprite(textureUrl); } }, [loadJsonAndTextureAndExecuteCallback, loadStandaloneSprite, parseSpriteData]); React63.useLayoutEffect(() => { if (jsonRef.current && inputRef.current) { loadJsonAndTextureAndExecuteCallback(jsonRef.current, inputRef.current, parseSpriteData); } else if (inputRef.current) { loadStandaloneSprite(); } const _inputRef = inputRef.current; return () => { if (_inputRef) { useLoader.clear(TextureLoader, _inputRef); } }; }, [loadJsonAndTextureAndExecuteCallback, loadStandaloneSprite, parseSpriteData]); React63.useLayoutEffect(() => { onLoad == null || onLoad(spriteTexture, spriteData !== null && spriteData !== void 0 ? spriteData : null); }, [spriteTexture, spriteData, onLoad]); return { spriteObj, loadJsonAndTexture }; } useSpriteLoader.preload = (url) => useLoader.preload(TextureLoader, url); useSpriteLoader.clear = (input) => useLoader.clear(TextureLoader, input); // node_modules/@react-three/drei/core/Helper.js var React64 = __toESM(require_react()); function useHelper(object3D, helperConstructor, ...args) { const helper = React64.useRef(null); const scene = useThree((state) => state.scene); React64.useLayoutEffect(() => { let currentHelper = void 0; if (object3D && object3D != null && object3D.current && helperConstructor) { helper.current = currentHelper = new helperConstructor(object3D.current, ...args); } if (currentHelper) { currentHelper.traverse((child) => child.raycast = () => null); scene.add(currentHelper); return () => { helper.current = void 0; scene.remove(currentHelper); currentHelper.dispose == null || currentHelper.dispose(); }; } }, [scene, helperConstructor, object3D, ...args]); useFrame(() => { var _helper$current; return void ((_helper$current = helper.current) == null || _helper$current.update == null ? void 0 : _helper$current.update()); }); return helper; } var Helper = ({ type: helperConstructor, args = [] }) => { const thisRef = React64.useRef(null); const parentRef = React64.useRef(null); React64.useLayoutEffect(() => { parentRef.current = thisRef.current.parent; }); useHelper(parentRef, helperConstructor, ...args); return React64.createElement("object3D", { ref: thisRef }); }; // node_modules/@react-three/drei/core/Stats.js var React66 = __toESM(require_react()); var import_stats = __toESM(require_stats_min()); // node_modules/@react-three/drei/helpers/useEffectfulState.js var React65 = __toESM(require_react()); function call2(ref, value) { if (typeof ref === "function") ref(value); else if (ref != null) ref.current = value; } function useEffectfulState(fn, deps = [], cb2) { const [state, set] = React65.useState(); React65.useLayoutEffect(() => { const value = fn(); set(value); call2(cb2, value); return () => call2(cb2, null); }, deps); return state; } // node_modules/@react-three/drei/core/Stats.js function Stats({ showPanel = 0, className, parent }) { const stats = useEffectfulState(() => new import_stats.default(), []); React66.useEffect(() => { if (stats) { const node = parent && parent.current || document.body; stats.showPanel(showPanel); node == null || node.appendChild(stats.dom); const classNames = (className !== null && className !== void 0 ? className : "").split(" ").filter((cls) => cls); if (classNames.length) stats.dom.classList.add(...classNames); const begin = addEffect(() => stats.begin()); const end = addAfterEffect(() => stats.end()); return () => { if (classNames.length) stats.dom.classList.remove(...classNames); node == null || node.removeChild(stats.dom); begin(); end(); }; } }, [parent, stats, className, showPanel]); return null; } // node_modules/@react-three/drei/core/StatsGl.js var React67 = __toESM(require_react()); // node_modules/stats-gl/dist/panel.js var Panel = class { constructor(name, fg, bg) { this.name = name; this.fg = fg; this.bg = bg; this.gradient = null; this.PR = Math.round(window.devicePixelRatio || 1); this.WIDTH = 90 * this.PR; this.HEIGHT = 48 * this.PR; this.TEXT_X = 3 * this.PR; this.TEXT_Y = 2 * this.PR; this.GRAPH_X = 3 * this.PR; this.GRAPH_Y = 15 * this.PR; this.GRAPH_WIDTH = 84 * this.PR; this.GRAPH_HEIGHT = 30 * this.PR; this.canvas = document.createElement("canvas"); this.canvas.width = this.WIDTH; this.canvas.height = this.HEIGHT; this.canvas.style.width = "90px"; this.canvas.style.height = "48px"; this.canvas.style.position = "absolute"; this.canvas.style.cssText = "width:90px;height:48px"; this.context = this.canvas.getContext("2d"); this.initializeCanvas(); } createGradient() { if (!this.context) throw new Error("No context"); const gradient = this.context.createLinearGradient( 0, this.GRAPH_Y, 0, this.GRAPH_Y + this.GRAPH_HEIGHT ); let startColor; const endColor = this.fg; switch (this.fg.toLowerCase()) { case "#0ff": startColor = "#006666"; break; case "#0f0": startColor = "#006600"; break; case "#ff0": startColor = "#666600"; break; case "#e1e1e1": startColor = "#666666"; break; default: startColor = this.bg; break; } gradient.addColorStop(0, startColor); gradient.addColorStop(1, endColor); return gradient; } initializeCanvas() { if (!this.context) return; this.context.font = "bold " + 9 * this.PR + "px Helvetica,Arial,sans-serif"; this.context.textBaseline = "top"; this.gradient = this.createGradient(); this.context.fillStyle = this.bg; this.context.fillRect(0, 0, this.WIDTH, this.HEIGHT); this.context.fillStyle = this.fg; this.context.fillText(this.name, this.TEXT_X, this.TEXT_Y); this.context.fillStyle = this.fg; this.context.fillRect(this.GRAPH_X, this.GRAPH_Y, this.GRAPH_WIDTH, this.GRAPH_HEIGHT); this.context.fillStyle = this.bg; this.context.globalAlpha = 0.9; this.context.fillRect(this.GRAPH_X, this.GRAPH_Y, this.GRAPH_WIDTH, this.GRAPH_HEIGHT); } update(value, valueGraph, maxValue, maxGraph, decimals = 0) { if (!this.context || !this.gradient) return; const min = Math.min(Infinity, value); const max2 = Math.max(maxValue, value); maxGraph = Math.max(maxGraph, valueGraph); this.context.globalAlpha = 1; this.context.fillStyle = this.bg; this.context.fillRect(0, 0, this.WIDTH, this.GRAPH_Y); this.context.fillStyle = this.fg; this.context.fillText( `${value.toFixed(decimals)} ${this.name} (${min.toFixed(decimals)}-${parseFloat( max2.toFixed(decimals) )})`, this.TEXT_X, this.TEXT_Y ); this.context.drawImage( this.canvas, this.GRAPH_X + this.PR, this.GRAPH_Y, this.GRAPH_WIDTH - this.PR, this.GRAPH_HEIGHT, this.GRAPH_X, this.GRAPH_Y, this.GRAPH_WIDTH - this.PR, this.GRAPH_HEIGHT ); const columnHeight = this.GRAPH_HEIGHT - (1 - valueGraph / maxGraph) * this.GRAPH_HEIGHT; if (columnHeight > 0) { this.context.globalAlpha = 1; this.context.fillStyle = this.gradient; this.context.fillRect( this.GRAPH_X + this.GRAPH_WIDTH - this.PR, this.GRAPH_Y + this.GRAPH_HEIGHT - columnHeight, this.PR, columnHeight ); } } }; // node_modules/stats-gl/dist/main.js var _Stats = class _Stats2 { constructor({ trackGPU = false, logsPerSecond = 30, samplesLog = 60, samplesGraph = 10, precision = 2, minimal = false, horizontal = true, mode = 0 } = {}) { this.gl = null; this.ext = null; this.activeQuery = null; this.gpuQueries = []; this.threeRendererPatched = false; this.frames = 0; this.renderCount = 0; this.isRunningCPUProfiling = false; this.totalCpuDuration = 0; this.totalGpuDuration = 0; this.totalGpuDurationCompute = 0; this.totalFps = 0; this.gpuPanel = null; this.gpuPanelCompute = null; this.averageFps = { logs: [], graph: [] }; this.averageCpu = { logs: [], graph: [] }; this.averageGpu = { logs: [], graph: [] }; this.averageGpuCompute = { logs: [], graph: [] }; this.handleClick = (event) => { event.preventDefault(); this.showPanel(++this.mode % this.dom.children.length); }; this.handleResize = () => { this.resizePanel(this.fpsPanel, 0); this.resizePanel(this.msPanel, 1); if (this.gpuPanel) this.resizePanel(this.gpuPanel, 2); if (this.gpuPanelCompute) this.resizePanel(this.gpuPanelCompute, 3); }; this.mode = mode; this.horizontal = horizontal; this.minimal = minimal; this.trackGPU = trackGPU; this.samplesLog = samplesLog; this.samplesGraph = samplesGraph; this.precision = precision; this.logsPerSecond = logsPerSecond; this.dom = document.createElement("div"); this.initializeDOM(); this.beginTime = performance.now(); this.prevTime = this.beginTime; this.prevCpuTime = this.beginTime; this.fpsPanel = this.addPanel(new _Stats2.Panel("FPS", "#0ff", "#002"), 0); this.msPanel = this.addPanel(new _Stats2.Panel("CPU", "#0f0", "#020"), 1); this.setupEventListeners(); } initializeDOM() { this.dom.style.cssText = ` position: fixed; top: 0; left: 0; opacity: 0.9; z-index: 10000; ${this.minimal ? "cursor: pointer;" : ""} `; } setupEventListeners() { if (this.minimal) { this.dom.addEventListener("click", this.handleClick); this.showPanel(this.mode); } else { window.addEventListener("resize", this.handleResize); } } async init(canvasOrGL) { if (!canvasOrGL) { console.error('Stats: The "canvas" parameter is undefined.'); return; } if (this.handleThreeRenderer(canvasOrGL)) return; if (await this.handleWebGPURenderer(canvasOrGL)) return; if (!this.initializeWebGL(canvasOrGL)) return; } handleThreeRenderer(renderer) { if (renderer.isWebGLRenderer && !this.threeRendererPatched) { this.patchThreeRenderer(renderer); this.gl = renderer.getContext(); if (this.trackGPU) { this.initializeGPUTracking(); } return true; } return false; } async handleWebGPURenderer(renderer) { if (renderer.isWebGPURenderer) { if (this.trackGPU) { renderer.backend.trackTimestamp = true; if (await renderer.hasFeatureAsync("timestamp-query")) { this.initializeWebGPUPanels(); } } this.info = renderer.info; return true; } return false; } initializeWebGPUPanels() { this.gpuPanel = this.addPanel(new _Stats2.Panel("GPU", "#ff0", "#220"), 2); this.gpuPanelCompute = this.addPanel( new _Stats2.Panel("CPT", "#e1e1e1", "#212121"), 3 ); } initializeWebGL(canvasOrGL) { if (canvasOrGL instanceof WebGL2RenderingContext) { this.gl = canvasOrGL; } else if (canvasOrGL instanceof HTMLCanvasElement || canvasOrGL instanceof OffscreenCanvas) { this.gl = canvasOrGL.getContext("webgl2"); if (!this.gl) { console.error("Stats: Unable to obtain WebGL2 context."); return false; } } else { console.error( "Stats: Invalid input type. Expected WebGL2RenderingContext, HTMLCanvasElement, or OffscreenCanvas." ); return false; } return true; } initializeGPUTracking() { if (this.gl) { this.ext = this.gl.getExtension("EXT_disjoint_timer_query_webgl2"); if (this.ext) { this.gpuPanel = this.addPanel(new _Stats2.Panel("GPU", "#ff0", "#220"), 2); } } } begin() { if (!this.isRunningCPUProfiling) { this.beginProfiling("cpu-started"); } if (!this.gl || !this.ext) return; if (this.activeQuery) { this.gl.endQuery(this.ext.TIME_ELAPSED_EXT); } this.activeQuery = this.gl.createQuery(); if (this.activeQuery) { this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT, this.activeQuery); } } end() { this.renderCount++; if (this.gl && this.ext && this.activeQuery) { this.gl.endQuery(this.ext.TIME_ELAPSED_EXT); this.gpuQueries.push({ query: this.activeQuery }); this.activeQuery = null; } } update() { if (!this.info) { this.processGpuQueries(); } else { this.processWebGPUTimestamps(); } this.endProfiling("cpu-started", "cpu-finished", "cpu-duration"); this.updateAverages(); this.resetCounters(); } processWebGPUTimestamps() { this.totalGpuDuration = this.info.render.timestamp; this.totalGpuDurationCompute = this.info.compute.timestamp; this.addToAverage(this.totalGpuDurationCompute, this.averageGpuCompute); } updateAverages() { this.addToAverage(this.totalCpuDuration, this.averageCpu); this.addToAverage(this.totalGpuDuration, this.averageGpu); } resetCounters() { this.renderCount = 0; if (this.totalCpuDuration === 0) { this.beginProfiling("cpu-started"); } this.totalCpuDuration = 0; this.totalFps = 0; this.beginTime = this.endInternal(); } resizePanel(panel, offset) { panel.canvas.style.position = "absolute"; if (this.minimal) { panel.canvas.style.display = "none"; } else { panel.canvas.style.display = "block"; if (this.horizontal) { panel.canvas.style.top = "0px"; panel.canvas.style.left = offset * panel.WIDTH / panel.PR + "px"; } else { panel.canvas.style.left = "0px"; panel.canvas.style.top = offset * panel.HEIGHT / panel.PR + "px"; } } } addPanel(panel, offset) { if (panel.canvas) { this.dom.appendChild(panel.canvas); this.resizePanel(panel, offset); } return panel; } showPanel(id) { for (let i4 = 0; i4 < this.dom.children.length; i4++) { const child = this.dom.children[i4]; child.style.display = i4 === id ? "block" : "none"; } this.mode = id; } processGpuQueries() { if (!this.gl || !this.ext) return; this.totalGpuDuration = 0; this.gpuQueries.forEach((queryInfo, index2) => { if (this.gl) { const available = this.gl.getQueryParameter(queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE); const disjoint = this.gl.getParameter(this.ext.GPU_DISJOINT_EXT); if (available && !disjoint) { const elapsed = this.gl.getQueryParameter(queryInfo.query, this.gl.QUERY_RESULT); const duration = elapsed * 1e-6; this.totalGpuDuration += duration; this.gl.deleteQuery(queryInfo.query); this.gpuQueries.splice(index2, 1); } } }); } endInternal() { this.frames++; const time = (performance || Date).now(); const elapsed = time - this.prevTime; if (time >= this.prevCpuTime + 1e3 / this.logsPerSecond) { const fps = Math.round(this.frames * 1e3 / elapsed); this.addToAverage(fps, this.averageFps); this.updatePanel(this.fpsPanel, this.averageFps, 0); this.updatePanel(this.msPanel, this.averageCpu, this.precision); this.updatePanel(this.gpuPanel, this.averageGpu, this.precision); if (this.gpuPanelCompute) { this.updatePanel(this.gpuPanelCompute, this.averageGpuCompute); } this.frames = 0; this.prevCpuTime = time; this.prevTime = time; } return time; } addToAverage(value, averageArray) { averageArray.logs.push(value); if (averageArray.logs.length > this.samplesLog) { averageArray.logs.shift(); } averageArray.graph.push(value); if (averageArray.graph.length > this.samplesGraph) { averageArray.graph.shift(); } } beginProfiling(marker) { if (window.performance) { window.performance.mark(marker); this.isRunningCPUProfiling = true; } } endProfiling(startMarker, endMarker, measureName) { if (window.performance && endMarker && this.isRunningCPUProfiling) { window.performance.mark(endMarker); const cpuMeasure = performance.measure(measureName, startMarker, endMarker); this.totalCpuDuration += cpuMeasure.duration; this.isRunningCPUProfiling = false; } } updatePanel(panel, averageArray, precision = 2) { if (averageArray.logs.length > 0) { let sumLog = 0; let max2 = 0.01; for (let i4 = 0; i4 < averageArray.logs.length; i4++) { sumLog += averageArray.logs[i4]; if (averageArray.logs[i4] > max2) { max2 = averageArray.logs[i4]; } } let sumGraph = 0; let maxGraph = 0.01; for (let i4 = 0; i4 < averageArray.graph.length; i4++) { sumGraph += averageArray.graph[i4]; if (averageArray.graph[i4] > maxGraph) { maxGraph = averageArray.graph[i4]; } } if (panel) { panel.update(sumLog / Math.min(averageArray.logs.length, this.samplesLog), sumGraph / Math.min(averageArray.graph.length, this.samplesGraph), max2, maxGraph, precision); } } } get domElement() { return this.dom; } patchThreeRenderer(renderer) { const originalRenderMethod = renderer.render; const statsInstance = this; renderer.render = function(scene, camera) { statsInstance.begin(); originalRenderMethod.call(this, scene, camera); statsInstance.end(); }; this.threeRendererPatched = true; } }; _Stats.Panel = Panel; var Stats2 = _Stats; // node_modules/@react-three/drei/core/StatsGl.js var StatsGl = React67.forwardRef(function StatsGl2({ className, parent, id, clearStatsGlStyle, ...props }, fref) { const gl = useThree((state) => state.gl); const stats = React67.useMemo(() => { const stats2 = new Stats2({ ...props }); stats2.init(gl); return stats2; }, [gl]); React67.useImperativeHandle(fref, () => stats.domElement, [stats]); React67.useEffect(() => { if (stats) { const node = parent && parent.current || document.body; node == null || node.appendChild(stats.domElement); stats.domElement.querySelectorAll("canvas").forEach((canvas) => { canvas.style.removeProperty("position"); }); if (id) stats.domElement.id = id; if (clearStatsGlStyle) stats.domElement.removeAttribute("style"); stats.domElement.removeAttribute("style"); const classNames = (className !== null && className !== void 0 ? className : "").split(" ").filter((cls) => cls); if (classNames.length) stats.domElement.classList.add(...classNames); const end = addAfterEffect(() => stats.update()); return () => { if (classNames.length) stats.domElement.classList.remove(...classNames); node == null || node.removeChild(stats.domElement); end(); }; } }, [parent, stats, className, id, clearStatsGlStyle]); return null; }); // node_modules/@react-three/drei/core/useDepthBuffer.js var React68 = __toESM(require_react()); function useDepthBuffer({ size: size2 = 256, frames = Infinity } = {}) { const dpr = useThree((state) => state.viewport.dpr); const { width, height } = useThree((state) => state.size); const w = size2 || width * dpr; const h = size2 || height * dpr; const depthConfig = React68.useMemo(() => { const depthTexture = new DepthTexture(w, h); depthTexture.format = DepthFormat; depthTexture.type = UnsignedShortType; return { depthTexture }; }, [w, h]); let count = 0; const depthFBO = useFBO(w, h, depthConfig); useFrame((state) => { if (frames === Infinity || count < frames) { state.gl.setRenderTarget(depthFBO); state.gl.render(state.scene, state.camera); state.gl.setRenderTarget(null); count++; } }); return depthFBO.depthTexture; } // node_modules/@react-three/drei/core/useAspect.js function useAspect(width, height, factor = 1) { const v5 = useThree((state) => state.viewport); const adaptedHeight = height * (v5.aspect > width / height ? v5.width / width : v5.height / height); const adaptedWidth = width * (v5.aspect > width / height ? v5.width / width : v5.height / height); return [adaptedWidth * factor, adaptedHeight * factor, 1]; } // node_modules/@react-three/drei/core/useCamera.js var React69 = __toESM(require_react()); function useCamera(camera, props) { const pointer = useThree((state) => state.pointer); const [raycast2] = React69.useState(() => { const raycaster = new Raycaster(); if (props) applyProps(raycaster, props); return function(_, intersects) { raycaster.setFromCamera(pointer, camera instanceof Camera ? camera : camera.current); const rc = this.constructor.prototype.raycast.bind(this); if (rc) rc(raycaster, intersects); }; }); return raycast2; } // node_modules/@react-three/drei/core/DetectGPU.js var React70 = __toESM(require_react()); // node_modules/detect-gpu/dist/detect-gpu.esm.js function e(e2, t3, r2, n2) { return new (r2 || (r2 = Promise))((function(o2, a6) { function i4(e3) { try { d2(n2.next(e3)); } catch (e4) { a6(e4); } } function c2(e3) { try { d2(n2.throw(e3)); } catch (e4) { a6(e4); } } function d2(e3) { var t4; e3.done ? o2(e3.value) : (t4 = e3.value, t4 instanceof r2 ? t4 : new r2((function(e4) { e4(t4); }))).then(i4, c2); } d2((n2 = n2.apply(e2, t3 || [])).next()); })); } var t2 = ["geforce 320m", "geforce 8600", "geforce 8600m gt", "geforce 8800 gs", "geforce 8800 gt", "geforce 9400", "geforce 9400m g", "geforce 9400m", "geforce 9600m gt", "geforce 9600m", "geforce fx go5200", "geforce gt 120", "geforce gt 130", "geforce gt 330m", "geforce gtx 285", "google swiftshader", "intel g41", "intel g45", "intel gma 4500mhd", "intel gma x3100", "intel hd 3000", "intel q45", "legacy", "mali-2", "mali-3", "mali-4", "quadro fx 1500", "quadro fx 4", "quadro fx 5", "radeon hd 2400", "radeon hd 2600", "radeon hd 4670", "radeon hd 4850", "radeon hd 4870", "radeon hd 5670", "radeon hd 5750", "radeon hd 6290", "radeon hd 6300", "radeon hd 6310", "radeon hd 6320", "radeon hd 6490m", "radeon hd 6630m", "radeon hd 6750m", "radeon hd 6770m", "radeon hd 6970m", "sgx 543", "sgx543"]; function r(e2) { return e2 = e2.toLowerCase().replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i, "$1").replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g, "").replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/, "$1"); } var n = "undefined" == typeof window; var o = (() => { if (n) return; const { userAgent: e2, platform: t3, maxTouchPoints: r2 } = window.navigator, o2 = /(iphone|ipod|ipad)/i.test(e2), a6 = "iPad" === t3 || "MacIntel" === t3 && r2 > 0 && !window.MSStream; return { isIpad: a6, isMobile: /android/i.test(e2) || o2 || a6, isSafari12: /Version\/12.+Safari/.test(e2), isFirefox: /Firefox/.test(e2) }; })(); function a5(e2, t3, r2) { if (!r2) return [t3]; const n2 = (function(e3) { const t4 = "\n precision highp float;\n attribute vec3 aPosition;\n varying float vvv;\n void main() {\n vvv = 0.31622776601683794;\n gl_Position = vec4(aPosition, 1.0);\n }\n ", r3 = "\n precision highp float;\n varying float vvv;\n void main() {\n vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * vvv;\n enc = fract(enc);\n enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n gl_FragColor = enc;\n }\n ", n3 = e3.createShader(35633), o2 = e3.createShader(35632), a7 = e3.createProgram(); if (!(o2 && n3 && a7)) return; e3.shaderSource(n3, t4), e3.shaderSource(o2, r3), e3.compileShader(n3), e3.compileShader(o2), e3.attachShader(a7, n3), e3.attachShader(a7, o2), e3.linkProgram(a7), e3.detachShader(a7, n3), e3.detachShader(a7, o2), e3.deleteShader(n3), e3.deleteShader(o2), e3.useProgram(a7); const i5 = e3.createBuffer(); e3.bindBuffer(34962, i5), e3.bufferData(34962, new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0]), 35044); const c5 = e3.getAttribLocation(a7, "aPosition"); e3.vertexAttribPointer(c5, 3, 5126, false, 0, 0), e3.enableVertexAttribArray(c5), e3.clearColor(1, 1, 1, 1), e3.clear(16384), e3.viewport(0, 0, 1, 1), e3.drawArrays(4, 0, 3); const d3 = new Uint8Array(4); return e3.readPixels(0, 0, 1, 1, 6408, 5121, d3), e3.deleteProgram(a7), e3.deleteBuffer(i5), d3.join(""); })(e2), a6 = "801621810", i4 = "8016218135", c2 = "80162181161", d2 = (null == o ? void 0 : o.isIpad) ? [["a7", c2, 12], ["a8", i4, 15], ["a8x", i4, 15], ["a9", i4, 15], ["a9x", i4, 15], ["a10", i4, 15], ["a10x", i4, 15], ["a12", a6, 15], ["a12x", a6, 15], ["a12z", a6, 15], ["a14", a6, 15], ["a15", a6, 15], ["m1", a6, 15], ["m2", a6, 15]] : [["a7", c2, 12], ["a8", i4, 12], ["a9", i4, 15], ["a10", i4, 15], ["a11", a6, 15], ["a12", a6, 15], ["a13", a6, 15], ["a14", a6, 15], ["a15", a6, 15], ["a16", a6, 15], ["a17", a6, 15]]; let l2; "80162181255" === n2 ? l2 = d2.filter((([, , e3]) => e3 >= 14)) : (l2 = d2.filter((([, e3]) => e3 === n2)), l2.length || (l2 = d2)); return l2.map((([e3]) => `apple ${e3} gpu`)); } var i2 = class extends Error { constructor(e2) { super(e2), Object.setPrototypeOf(this, new.target.prototype); } }; var c = []; var d = []; function l(e2, t3) { if (e2 === t3) return 0; const r2 = e2; e2.length > t3.length && (e2 = t3, t3 = r2); let n2 = e2.length, o2 = t3.length; for (; n2 > 0 && e2.charCodeAt(~-n2) === t3.charCodeAt(~-o2); ) n2--, o2--; let a6, i4 = 0; for (; i4 < n2 && e2.charCodeAt(i4) === t3.charCodeAt(i4); ) i4++; if (n2 -= i4, o2 -= i4, 0 === n2) return o2; let l2, s2, f2 = 0, u = 0, g = 0; for (; u < n2; ) d[u] = e2.charCodeAt(i4 + u), c[u] = ++u; for (; g < o2; ) for (a6 = t3.charCodeAt(i4 + g), l2 = g++, f2 = g, u = 0; u < n2; u++) s2 = a6 === d[u] ? l2 : l2 + 1, l2 = c[u], f2 = c[u] = l2 > f2 ? s2 > f2 ? f2 + 1 : s2 : s2 > l2 ? l2 + 1 : s2; return f2; } function s(e2) { return null != e2; } var f = ({ mobileTiers: c2 = [0, 15, 30, 60], desktopTiers: d2 = [0, 15, 30, 60], override: f2 = {}, glContext: u, failIfMajorPerformanceCaveat: g = false, benchmarksURL: h = "https://unpkg.com/detect-gpu@5.0.70/dist/benchmarks" } = {}) => e(void 0, void 0, void 0, (function* () { const p2 = {}; if (n) return { tier: 0, type: "SSR" }; const { isIpad: m = !!(null == o ? void 0 : o.isIpad), isMobile: v5 = !!(null == o ? void 0 : o.isMobile), screenSize: w = window.screen, loadBenchmarks: x = ((t3) => e(void 0, void 0, void 0, (function* () { const e2 = yield fetch(`${h}/${t3}`).then(((e3) => e3.json())); if (parseInt(e2.shift().split(".")[0], 10) < 4) throw new i2("Detect GPU benchmark data is out of date. Please update to version 4x"); return e2; }))) } = f2; let { renderer: A } = f2; const P = (e2, t3, r2, n2, o2) => ({ device: o2, fps: n2, gpu: r2, isMobile: v5, tier: e2, type: t3 }); let S, b5 = ""; if (A) A = r(A), S = [A]; else { const e2 = u || (function(e3, t4 = false) { const r2 = { alpha: false, antialias: false, depth: false, failIfMajorPerformanceCaveat: t4, powerPreference: "high-performance", stencil: false }; e3 && delete r2.powerPreference; const n2 = window.document.createElement("canvas"), o2 = n2.getContext("webgl", r2) || n2.getContext("experimental-webgl", r2); return null != o2 ? o2 : void 0; })(null == o ? void 0 : o.isSafari12, g); if (!e2) return P(0, "WEBGL_UNSUPPORTED"); const t3 = (null == o ? void 0 : o.isFirefox) ? null : e2.getExtension("WEBGL_debug_renderer_info"); if (A = t3 ? e2.getParameter(t3.UNMASKED_RENDERER_WEBGL) : e2.getParameter(e2.RENDERER), !A) return P(1, "FALLBACK"); b5 = A, A = r(A), S = (function(e3, t4, r2) { return "apple gpu" === t4 ? a5(e3, t4, r2) : [t4]; })(e2, A, v5); } const E = (yield Promise.all(S.map((function(t3) { var r2; return e(this, void 0, void 0, (function* () { const e2 = ((e3) => { const t4 = v5 ? ["adreno", "apple", "mali-t", "mali", "nvidia", "powervr", "samsung"] : ["intel", "apple", "amd", "radeon", "nvidia", "geforce", "adreno"]; for (const r3 of t4) if (e3.includes(r3)) return r3; })(t3); if (!e2) return; const n2 = `${v5 ? "m" : "d"}-${e2}${m ? "-ipad" : ""}.json`, o2 = p2[n2] = null !== (r2 = p2[n2]) && void 0 !== r2 ? r2 : x(n2); let a6; try { a6 = yield o2; } catch (e3) { if (e3 instanceof i2) throw e3; return; } const c5 = (function(e3) { var t4; const r3 = (e3 = e3.replace(/\([^)]+\)/, "")).match(/\d+/) || e3.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g); return null !== (t4 = null == r3 ? void 0 : r3.join("").replace(/\W|amd/g, "")) && void 0 !== t4 ? t4 : ""; })(t3); let d3 = a6.filter((([, e3]) => e3 === c5)); d3.length || (d3 = a6.filter((([e3]) => e3.includes(t3)))); const s2 = d3.length; if (0 === s2) return; const f3 = t3.split(/[.,()\[\]/\s]/g).sort().filter(((e3, t4, r3) => 0 === t4 || e3 !== r3[t4 - 1])).join(" "); let u2, [g2, , , , h2] = s2 > 1 ? d3.map(((e3) => [e3, l(f3, e3[2])])).sort((([, e3], [, t4]) => e3 - t4))[0][0] : d3[0], A2 = Number.MAX_VALUE; const { devicePixelRatio: P2 } = window, S2 = w.width * P2 * w.height * P2; for (const e3 of h2) { const [t4, r3] = e3, n3 = t4 * r3, o3 = Math.abs(S2 - n3); o3 < A2 && (A2 = o3, u2 = e3); } if (!u2) return; const [, , b6, E2] = u2; return [A2, b6, g2, E2]; })); })))).filter(s).sort((([e2 = Number.MAX_VALUE, t3], [r2 = Number.MAX_VALUE, n2]) => e2 === r2 ? t3 - n2 : e2 - r2)); if (!E.length) { const e2 = t2.find(((e3) => A.includes(e3))); return e2 ? P(0, "BLOCKLISTED", e2) : P(1, "FALLBACK", `${A} (${b5})`); } const [, y, C, L] = E[0]; if (-1 === y) return P(0, "BLOCKLISTED", C, y, L); const M = v5 ? c2 : d2; let $ = 0; for (let e2 = 0; e2 < M.length; e2++) y >= M[e2] && ($ = e2); return P($, "BENCHMARK", C, y, L); })); // node_modules/@react-three/drei/core/DetectGPU.js var useDetectGPU = (props) => suspend(() => f(props), ["useDetectGPU"]); function DetectGPU({ children, ...options }) { const result = useDetectGPU(options); return React70.createElement(React70.Fragment, null, children == null ? void 0 : children(result)); } // node_modules/@react-three/drei/core/Bvh.js var React71 = __toESM(require_react()); // node_modules/three-mesh-bvh/src/core/Constants.js var CENTER = 0; var AVERAGE = 1; var SAH = 2; var CONTAINED = 2; var TRIANGLE_INTERSECT_COST = 1.25; var TRAVERSAL_COST = 1; var BYTES_PER_NODE = 6 * 4 + 4 + 4; var IS_LEAFNODE_FLAG = 65535; var FLOAT32_EPSILON = Math.pow(2, -24); var SKIP_GENERATION = /* @__PURE__ */ Symbol("SKIP_GENERATION"); // node_modules/three-mesh-bvh/src/core/build/geometryUtils.js function getVertexCount(geo) { return geo.index ? geo.index.count : geo.attributes.position.count; } function getTriCount(geo) { return getVertexCount(geo) / 3; } function getIndexArray(vertexCount, BufferConstructor = ArrayBuffer) { if (vertexCount > 65535) { return new Uint32Array(new BufferConstructor(4 * vertexCount)); } else { return new Uint16Array(new BufferConstructor(2 * vertexCount)); } } function ensureIndex(geo, options) { if (!geo.index) { const vertexCount = geo.attributes.position.count; const BufferConstructor = options.useSharedArrayBuffer ? SharedArrayBuffer : ArrayBuffer; const index2 = getIndexArray(vertexCount, BufferConstructor); geo.setIndex(new BufferAttribute(index2, 1)); for (let i4 = 0; i4 < vertexCount; i4++) { index2[i4] = i4; } } } function getFullGeometryRange(geo, range) { const triCount = getTriCount(geo); const drawRange = range ? range : geo.drawRange; const start = drawRange.start / 3; const end = (drawRange.start + drawRange.count) / 3; const offset = Math.max(0, start); const count = Math.min(triCount, end) - offset; return [{ offset: Math.floor(offset), count: Math.floor(count) }]; } function getRootIndexRanges(geo, range) { if (!geo.groups || !geo.groups.length) { return getFullGeometryRange(geo, range); } const ranges = []; const rangeBoundaries = /* @__PURE__ */ new Set(); const drawRange = range ? range : geo.drawRange; const drawRangeStart = drawRange.start / 3; const drawRangeEnd = (drawRange.start + drawRange.count) / 3; for (const group of geo.groups) { const groupStart = group.start / 3; const groupEnd = (group.start + group.count) / 3; rangeBoundaries.add(Math.max(drawRangeStart, groupStart)); rangeBoundaries.add(Math.min(drawRangeEnd, groupEnd)); } const sortedBoundaries = Array.from(rangeBoundaries.values()).sort((a6, b5) => a6 - b5); for (let i4 = 0; i4 < sortedBoundaries.length - 1; i4++) { const start = sortedBoundaries[i4]; const end = sortedBoundaries[i4 + 1]; ranges.push({ offset: Math.floor(start), count: Math.floor(end - start) }); } return ranges; } function hasGroupGaps(geometry3, range) { const vertexCount = getTriCount(geometry3); const groups = getRootIndexRanges(geometry3, range).sort((a6, b5) => a6.offset - b5.offset); const finalGroup = groups[groups.length - 1]; finalGroup.count = Math.min(vertexCount - finalGroup.offset, finalGroup.count); let total = 0; groups.forEach(({ count }) => total += count); return vertexCount !== total; } // node_modules/three-mesh-bvh/src/core/build/computeBoundsUtils.js function getBounds(triangleBounds, offset, count, target2, centroidTarget) { let minx = Infinity; let miny = Infinity; let minz = Infinity; let maxx = -Infinity; let maxy = -Infinity; let maxz = -Infinity; let cminx = Infinity; let cminy = Infinity; let cminz = Infinity; let cmaxx = -Infinity; let cmaxy = -Infinity; let cmaxz = -Infinity; for (let i4 = offset * 6, end = (offset + count) * 6; i4 < end; i4 += 6) { const cx = triangleBounds[i4 + 0]; const hx = triangleBounds[i4 + 1]; const lx = cx - hx; const rx = cx + hx; if (lx < minx) minx = lx; if (rx > maxx) maxx = rx; if (cx < cminx) cminx = cx; if (cx > cmaxx) cmaxx = cx; const cy = triangleBounds[i4 + 2]; const hy = triangleBounds[i4 + 3]; const ly = cy - hy; const ry = cy + hy; if (ly < miny) miny = ly; if (ry > maxy) maxy = ry; if (cy < cminy) cminy = cy; if (cy > cmaxy) cmaxy = cy; const cz = triangleBounds[i4 + 4]; const hz = triangleBounds[i4 + 5]; const lz = cz - hz; const rz = cz + hz; if (lz < minz) minz = lz; if (rz > maxz) maxz = rz; if (cz < cminz) cminz = cz; if (cz > cmaxz) cmaxz = cz; } target2[0] = minx; target2[1] = miny; target2[2] = minz; target2[3] = maxx; target2[4] = maxy; target2[5] = maxz; centroidTarget[0] = cminx; centroidTarget[1] = cminy; centroidTarget[2] = cminz; centroidTarget[3] = cmaxx; centroidTarget[4] = cmaxy; centroidTarget[5] = cmaxz; } function computeTriangleBounds(geo, target2 = null, offset = null, count = null) { const posAttr = geo.attributes.position; const index2 = geo.index ? geo.index.array : null; const triCount = getTriCount(geo); const normalized = posAttr.normalized; let triangleBounds; if (target2 === null) { triangleBounds = new Float32Array(triCount * 6); offset = 0; count = triCount; } else { triangleBounds = target2; offset = offset || 0; count = count || triCount; } const posArr = posAttr.array; const bufferOffset = posAttr.offset || 0; let stride = 3; if (posAttr.isInterleavedBufferAttribute) { stride = posAttr.data.stride; } const getters = ["getX", "getY", "getZ"]; for (let tri = offset; tri < offset + count; tri++) { const tri3 = tri * 3; const tri6 = tri * 6; let ai = tri3 + 0; let bi = tri3 + 1; let ci = tri3 + 2; if (index2) { ai = index2[ai]; bi = index2[bi]; ci = index2[ci]; } if (!normalized) { ai = ai * stride + bufferOffset; bi = bi * stride + bufferOffset; ci = ci * stride + bufferOffset; } for (let el = 0; el < 3; el++) { let a6, b5, c2; if (normalized) { a6 = posAttr[getters[el]](ai); b5 = posAttr[getters[el]](bi); c2 = posAttr[getters[el]](ci); } else { a6 = posArr[ai + el]; b5 = posArr[bi + el]; c2 = posArr[ci + el]; } let min = a6; if (b5 < min) min = b5; if (c2 < min) min = c2; let max2 = a6; if (b5 > max2) max2 = b5; if (c2 > max2) max2 = c2; const halfExtents = (max2 - min) / 2; const el2 = el * 2; triangleBounds[tri6 + el2 + 0] = min + halfExtents; triangleBounds[tri6 + el2 + 1] = halfExtents + (Math.abs(min) + halfExtents) * FLOAT32_EPSILON; } } return triangleBounds; } // node_modules/three-mesh-bvh/src/utils/ArrayBoxUtilities.js function arrayToBox(nodeIndex32, array, target2) { target2.min.x = array[nodeIndex32]; target2.min.y = array[nodeIndex32 + 1]; target2.min.z = array[nodeIndex32 + 2]; target2.max.x = array[nodeIndex32 + 3]; target2.max.y = array[nodeIndex32 + 4]; target2.max.z = array[nodeIndex32 + 5]; return target2; } function getLongestEdgeIndex(bounds) { let splitDimIdx = -1; let splitDist = -Infinity; for (let i4 = 0; i4 < 3; i4++) { const dist = bounds[i4 + 3] - bounds[i4]; if (dist > splitDist) { splitDist = dist; splitDimIdx = i4; } } return splitDimIdx; } function copyBounds(source, target2) { target2.set(source); } function unionBounds(a6, b5, target2) { let aVal, bVal; for (let d2 = 0; d2 < 3; d2++) { const d3 = d2 + 3; aVal = a6[d2]; bVal = b5[d2]; target2[d2] = aVal < bVal ? aVal : bVal; aVal = a6[d3]; bVal = b5[d3]; target2[d3] = aVal > bVal ? aVal : bVal; } } function expandByTriangleBounds(startIndex, triangleBounds, bounds) { for (let d2 = 0; d2 < 3; d2++) { const tCenter = triangleBounds[startIndex + 2 * d2]; const tHalf = triangleBounds[startIndex + 2 * d2 + 1]; const tMin = tCenter - tHalf; const tMax = tCenter + tHalf; if (tMin < bounds[d2]) { bounds[d2] = tMin; } if (tMax > bounds[d2 + 3]) { bounds[d2 + 3] = tMax; } } } function computeSurfaceArea(bounds) { const d0 = bounds[3] - bounds[0]; const d1 = bounds[4] - bounds[1]; const d2 = bounds[5] - bounds[2]; return 2 * (d0 * d1 + d1 * d2 + d2 * d0); } // node_modules/three-mesh-bvh/src/core/build/splitUtils.js var BIN_COUNT = 32; var binsSort = (a6, b5) => a6.candidate - b5.candidate; var sahBins = new Array(BIN_COUNT).fill().map(() => { return { count: 0, bounds: new Float32Array(6), rightCacheBounds: new Float32Array(6), leftCacheBounds: new Float32Array(6), candidate: 0 }; }); var leftBounds = new Float32Array(6); function getOptimalSplit(nodeBoundingData, centroidBoundingData, triangleBounds, offset, count, strategy) { let axis = -1; let pos = 0; if (strategy === CENTER) { axis = getLongestEdgeIndex(centroidBoundingData); if (axis !== -1) { pos = (centroidBoundingData[axis] + centroidBoundingData[axis + 3]) / 2; } } else if (strategy === AVERAGE) { axis = getLongestEdgeIndex(nodeBoundingData); if (axis !== -1) { pos = getAverage(triangleBounds, offset, count, axis); } } else if (strategy === SAH) { const rootSurfaceArea = computeSurfaceArea(nodeBoundingData); let bestCost = TRIANGLE_INTERSECT_COST * count; const cStart = offset * 6; const cEnd = (offset + count) * 6; for (let a6 = 0; a6 < 3; a6++) { const axisLeft = centroidBoundingData[a6]; const axisRight = centroidBoundingData[a6 + 3]; const axisLength = axisRight - axisLeft; const binWidth = axisLength / BIN_COUNT; if (count < BIN_COUNT / 4) { const truncatedBins = [...sahBins]; truncatedBins.length = count; let b5 = 0; for (let c2 = cStart; c2 < cEnd; c2 += 6, b5++) { const bin = truncatedBins[b5]; bin.candidate = triangleBounds[c2 + 2 * a6]; bin.count = 0; const { bounds, leftCacheBounds, rightCacheBounds } = bin; for (let d2 = 0; d2 < 3; d2++) { rightCacheBounds[d2] = Infinity; rightCacheBounds[d2 + 3] = -Infinity; leftCacheBounds[d2] = Infinity; leftCacheBounds[d2 + 3] = -Infinity; bounds[d2] = Infinity; bounds[d2 + 3] = -Infinity; } expandByTriangleBounds(c2, triangleBounds, bounds); } truncatedBins.sort(binsSort); let splitCount = count; for (let bi = 0; bi < splitCount; bi++) { const bin = truncatedBins[bi]; while (bi + 1 < splitCount && truncatedBins[bi + 1].candidate === bin.candidate) { truncatedBins.splice(bi + 1, 1); splitCount--; } } for (let c2 = cStart; c2 < cEnd; c2 += 6) { const center3 = triangleBounds[c2 + 2 * a6]; for (let bi = 0; bi < splitCount; bi++) { const bin = truncatedBins[bi]; if (center3 >= bin.candidate) { expandByTriangleBounds(c2, triangleBounds, bin.rightCacheBounds); } else { expandByTriangleBounds(c2, triangleBounds, bin.leftCacheBounds); bin.count++; } } } for (let bi = 0; bi < splitCount; bi++) { const bin = truncatedBins[bi]; const leftCount = bin.count; const rightCount = count - bin.count; const leftBounds2 = bin.leftCacheBounds; const rightBounds = bin.rightCacheBounds; let leftProb = 0; if (leftCount !== 0) { leftProb = computeSurfaceArea(leftBounds2) / rootSurfaceArea; } let rightProb = 0; if (rightCount !== 0) { rightProb = computeSurfaceArea(rightBounds) / rootSurfaceArea; } const cost = TRAVERSAL_COST + TRIANGLE_INTERSECT_COST * (leftProb * leftCount + rightProb * rightCount); if (cost < bestCost) { axis = a6; bestCost = cost; pos = bin.candidate; } } } else { for (let i4 = 0; i4 < BIN_COUNT; i4++) { const bin = sahBins[i4]; bin.count = 0; bin.candidate = axisLeft + binWidth + i4 * binWidth; const bounds = bin.bounds; for (let d2 = 0; d2 < 3; d2++) { bounds[d2] = Infinity; bounds[d2 + 3] = -Infinity; } } for (let c2 = cStart; c2 < cEnd; c2 += 6) { const triCenter = triangleBounds[c2 + 2 * a6]; const relativeCenter = triCenter - axisLeft; let binIndex = ~~(relativeCenter / binWidth); if (binIndex >= BIN_COUNT) binIndex = BIN_COUNT - 1; const bin = sahBins[binIndex]; bin.count++; expandByTriangleBounds(c2, triangleBounds, bin.bounds); } const lastBin = sahBins[BIN_COUNT - 1]; copyBounds(lastBin.bounds, lastBin.rightCacheBounds); for (let i4 = BIN_COUNT - 2; i4 >= 0; i4--) { const bin = sahBins[i4]; const nextBin = sahBins[i4 + 1]; unionBounds(bin.bounds, nextBin.rightCacheBounds, bin.rightCacheBounds); } let leftCount = 0; for (let i4 = 0; i4 < BIN_COUNT - 1; i4++) { const bin = sahBins[i4]; const binCount = bin.count; const bounds = bin.bounds; const nextBin = sahBins[i4 + 1]; const rightBounds = nextBin.rightCacheBounds; if (binCount !== 0) { if (leftCount === 0) { copyBounds(bounds, leftBounds); } else { unionBounds(bounds, leftBounds, leftBounds); } } leftCount += binCount; let leftProb = 0; let rightProb = 0; if (leftCount !== 0) { leftProb = computeSurfaceArea(leftBounds) / rootSurfaceArea; } const rightCount = count - leftCount; if (rightCount !== 0) { rightProb = computeSurfaceArea(rightBounds) / rootSurfaceArea; } const cost = TRAVERSAL_COST + TRIANGLE_INTERSECT_COST * (leftProb * leftCount + rightProb * rightCount); if (cost < bestCost) { axis = a6; bestCost = cost; pos = bin.candidate; } } } } } else { console.warn(`MeshBVH: Invalid build strategy value ${strategy} used.`); } return { axis, pos }; } function getAverage(triangleBounds, offset, count, axis) { let avg = 0; for (let i4 = offset, end = offset + count; i4 < end; i4++) { avg += triangleBounds[i4 * 6 + axis * 2]; } return avg / count; } // node_modules/three-mesh-bvh/src/core/MeshBVHNode.js var MeshBVHNode = class { constructor() { this.boundingData = new Float32Array(6); } }; // node_modules/three-mesh-bvh/src/core/build/sortUtils.generated.js function partition(indirectBuffer, index2, triangleBounds, offset, count, split) { let left = offset; let right = offset + count - 1; const pos = split.pos; const axisOffset = split.axis * 2; while (true) { while (left <= right && triangleBounds[left * 6 + axisOffset] < pos) { left++; } while (left <= right && triangleBounds[right * 6 + axisOffset] >= pos) { right--; } if (left < right) { for (let i4 = 0; i4 < 3; i4++) { let t0 = index2[left * 3 + i4]; index2[left * 3 + i4] = index2[right * 3 + i4]; index2[right * 3 + i4] = t0; } for (let i4 = 0; i4 < 6; i4++) { let tb = triangleBounds[left * 6 + i4]; triangleBounds[left * 6 + i4] = triangleBounds[right * 6 + i4]; triangleBounds[right * 6 + i4] = tb; } left++; right--; } else { return left; } } } // node_modules/three-mesh-bvh/src/core/build/sortUtils_indirect.generated.js function partition_indirect(indirectBuffer, index2, triangleBounds, offset, count, split) { let left = offset; let right = offset + count - 1; const pos = split.pos; const axisOffset = split.axis * 2; while (true) { while (left <= right && triangleBounds[left * 6 + axisOffset] < pos) { left++; } while (left <= right && triangleBounds[right * 6 + axisOffset] >= pos) { right--; } if (left < right) { let t3 = indirectBuffer[left]; indirectBuffer[left] = indirectBuffer[right]; indirectBuffer[right] = t3; for (let i4 = 0; i4 < 6; i4++) { let tb = triangleBounds[left * 6 + i4]; triangleBounds[left * 6 + i4] = triangleBounds[right * 6 + i4]; triangleBounds[right * 6 + i4] = tb; } left++; right--; } else { return left; } } } // node_modules/three-mesh-bvh/src/core/utils/nodeBufferUtils.js function IS_LEAF(n16, uint16Array2) { return uint16Array2[n16 + 15] === 65535; } function OFFSET(n32, uint32Array2) { return uint32Array2[n32 + 6]; } function COUNT(n16, uint16Array2) { return uint16Array2[n16 + 14]; } function LEFT_NODE(n32) { return n32 + 8; } function RIGHT_NODE(n32, uint32Array2) { return uint32Array2[n32 + 6]; } function SPLIT_AXIS(n32, uint32Array2) { return uint32Array2[n32 + 7]; } function BOUNDING_DATA_INDEX(n32) { return n32; } // node_modules/three-mesh-bvh/src/core/build/buildUtils.js var float32Array; var uint32Array; var uint16Array; var uint8Array; var MAX_POINTER = Math.pow(2, 32); function countNodes(node) { if ("count" in node) { return 1; } else { return 1 + countNodes(node.left) + countNodes(node.right); } } function populateBuffer(byteOffset, node, buffer2) { float32Array = new Float32Array(buffer2); uint32Array = new Uint32Array(buffer2); uint16Array = new Uint16Array(buffer2); uint8Array = new Uint8Array(buffer2); return _populateBuffer(byteOffset, node); } function _populateBuffer(byteOffset, node) { const stride4Offset = byteOffset / 4; const stride2Offset = byteOffset / 2; const isLeaf = "count" in node; const boundingData = node.boundingData; for (let i4 = 0; i4 < 6; i4++) { float32Array[stride4Offset + i4] = boundingData[i4]; } if (isLeaf) { if (node.buffer) { const buffer2 = node.buffer; uint8Array.set(new Uint8Array(buffer2), byteOffset); for (let offset = byteOffset, l2 = byteOffset + buffer2.byteLength; offset < l2; offset += BYTES_PER_NODE) { const offset2 = offset / 2; if (!IS_LEAF(offset2, uint16Array)) { uint32Array[offset / 4 + 6] += stride4Offset; } } return byteOffset + buffer2.byteLength; } else { const offset = node.offset; const count = node.count; uint32Array[stride4Offset + 6] = offset; uint16Array[stride2Offset + 14] = count; uint16Array[stride2Offset + 15] = IS_LEAFNODE_FLAG; return byteOffset + BYTES_PER_NODE; } } else { const left = node.left; const right = node.right; const splitAxis = node.splitAxis; let nextUnusedPointer; nextUnusedPointer = _populateBuffer(byteOffset + BYTES_PER_NODE, left); if (nextUnusedPointer / 4 > MAX_POINTER) { throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits."); } uint32Array[stride4Offset + 6] = nextUnusedPointer / 4; nextUnusedPointer = _populateBuffer(nextUnusedPointer, right); uint32Array[stride4Offset + 7] = splitAxis; return nextUnusedPointer; } } // node_modules/three-mesh-bvh/src/core/build/buildTree.js function generateIndirectBuffer(geometry3, useSharedArrayBuffer) { const triCount = (geometry3.index ? geometry3.index.count : geometry3.attributes.position.count) / 3; const useUint32 = triCount > 2 ** 16; const byteCount = useUint32 ? 4 : 2; const buffer2 = useSharedArrayBuffer ? new SharedArrayBuffer(triCount * byteCount) : new ArrayBuffer(triCount * byteCount); const indirectBuffer = useUint32 ? new Uint32Array(buffer2) : new Uint16Array(buffer2); for (let i4 = 0, l2 = indirectBuffer.length; i4 < l2; i4++) { indirectBuffer[i4] = i4; } return indirectBuffer; } function buildTree(bvh, triangleBounds, offset, count, options) { const { maxDepth, verbose, maxLeafTris, strategy, onProgress, indirect } = options; const indirectBuffer = bvh._indirectBuffer; const geometry3 = bvh.geometry; const indexArray = geometry3.index ? geometry3.index.array : null; const partionFunc = indirect ? partition_indirect : partition; const totalTriangles = getTriCount(geometry3); const cacheCentroidBoundingData = new Float32Array(6); let reachedMaxDepth = false; const root = new MeshBVHNode(); getBounds(triangleBounds, offset, count, root.boundingData, cacheCentroidBoundingData); splitNode(root, offset, count, cacheCentroidBoundingData); return root; function triggerProgress(trianglesProcessed) { if (onProgress) { onProgress(trianglesProcessed / totalTriangles); } } function splitNode(node, offset2, count2, centroidBoundingData = null, depth = 0) { if (!reachedMaxDepth && depth >= maxDepth) { reachedMaxDepth = true; if (verbose) { console.warn(`MeshBVH: Max depth of ${maxDepth} reached when generating BVH. Consider increasing maxDepth.`); console.warn(geometry3); } } if (count2 <= maxLeafTris || depth >= maxDepth) { triggerProgress(offset2 + count2); node.offset = offset2; node.count = count2; return node; } const split = getOptimalSplit(node.boundingData, centroidBoundingData, triangleBounds, offset2, count2, strategy); if (split.axis === -1) { triggerProgress(offset2 + count2); node.offset = offset2; node.count = count2; return node; } const splitOffset = partionFunc(indirectBuffer, indexArray, triangleBounds, offset2, count2, split); if (splitOffset === offset2 || splitOffset === offset2 + count2) { triggerProgress(offset2 + count2); node.offset = offset2; node.count = count2; } else { node.splitAxis = split.axis; const left = new MeshBVHNode(); const lstart = offset2; const lcount = splitOffset - offset2; node.left = left; getBounds(triangleBounds, lstart, lcount, left.boundingData, cacheCentroidBoundingData); splitNode(left, lstart, lcount, cacheCentroidBoundingData, depth + 1); const right = new MeshBVHNode(); const rstart = splitOffset; const rcount = count2 - lcount; node.right = right; getBounds(triangleBounds, rstart, rcount, right.boundingData, cacheCentroidBoundingData); splitNode(right, rstart, rcount, cacheCentroidBoundingData, depth + 1); } return node; } } function buildPackedTree(bvh, options) { const geometry3 = bvh.geometry; if (options.indirect) { bvh._indirectBuffer = generateIndirectBuffer(geometry3, options.useSharedArrayBuffer); if (hasGroupGaps(geometry3, options.range) && !options.verbose) { console.warn( 'MeshBVH: Provided geometry contains groups or a range that do not fully span the vertex contents while using the "indirect" option. BVH may incorrectly report intersections on unrendered portions of the geometry.' ); } } if (!bvh._indirectBuffer) { ensureIndex(geometry3, options); } const BufferConstructor = options.useSharedArrayBuffer ? SharedArrayBuffer : ArrayBuffer; const triangleBounds = computeTriangleBounds(geometry3); const geometryRanges = options.indirect ? getFullGeometryRange(geometry3, options.range) : getRootIndexRanges(geometry3, options.range); bvh._roots = geometryRanges.map((range) => { const root = buildTree(bvh, triangleBounds, range.offset, range.count, options); const nodeCount = countNodes(root); const buffer2 = new BufferConstructor(BYTES_PER_NODE * nodeCount); populateBuffer(0, root, buffer2); return buffer2; }); } // node_modules/three-mesh-bvh/src/math/SeparatingAxisBounds.js var SeparatingAxisBounds = class { constructor() { this.min = Infinity; this.max = -Infinity; } setFromPointsField(points, field) { let min = Infinity; let max2 = -Infinity; for (let i4 = 0, l2 = points.length; i4 < l2; i4++) { const p2 = points[i4]; const val = p2[field]; min = val < min ? val : min; max2 = val > max2 ? val : max2; } this.min = min; this.max = max2; } setFromPoints(axis, points) { let min = Infinity; let max2 = -Infinity; for (let i4 = 0, l2 = points.length; i4 < l2; i4++) { const p2 = points[i4]; const val = axis.dot(p2); min = val < min ? val : min; max2 = val > max2 ? val : max2; } this.min = min; this.max = max2; } isSeparated(other) { return this.min > other.max || other.min > this.max; } }; SeparatingAxisBounds.prototype.setFromBox = (function() { const p2 = new Vector3(); return function setFromBox(axis, box) { const boxMin = box.min; const boxMax = box.max; let min = Infinity; let max2 = -Infinity; for (let x = 0; x <= 1; x++) { for (let y = 0; y <= 1; y++) { for (let z = 0; z <= 1; z++) { p2.x = boxMin.x * x + boxMax.x * (1 - x); p2.y = boxMin.y * y + boxMax.y * (1 - y); p2.z = boxMin.z * z + boxMax.z * (1 - z); const val = axis.dot(p2); min = Math.min(val, min); max2 = Math.max(val, max2); } } } this.min = min; this.max = max2; }; })(); var areIntersecting = (function() { const cacheSatBounds = new SeparatingAxisBounds(); return function areIntersecting2(shape1, shape2) { const points1 = shape1.points; const satAxes1 = shape1.satAxes; const satBounds1 = shape1.satBounds; const points2 = shape2.points; const satAxes2 = shape2.satAxes; const satBounds2 = shape2.satBounds; for (let i4 = 0; i4 < 3; i4++) { const sb = satBounds1[i4]; const sa = satAxes1[i4]; cacheSatBounds.setFromPoints(sa, points2); if (sb.isSeparated(cacheSatBounds)) return false; } for (let i4 = 0; i4 < 3; i4++) { const sb = satBounds2[i4]; const sa = satAxes2[i4]; cacheSatBounds.setFromPoints(sa, points1); if (sb.isSeparated(cacheSatBounds)) return false; } }; })(); // node_modules/three-mesh-bvh/src/math/MathUtilities.js var closestPointLineToLine = (function() { const dir1 = new Vector3(); const dir2 = new Vector3(); const v02 = new Vector3(); return function closestPointLineToLine2(l1, l2, result) { const v0 = l1.start; const v10 = dir1; const v22 = l2.start; const v32 = dir2; v02.subVectors(v0, v22); dir1.subVectors(l1.end, l1.start); dir2.subVectors(l2.end, l2.start); const d0232 = v02.dot(v32); const d3210 = v32.dot(v10); const d3232 = v32.dot(v32); const d0210 = v02.dot(v10); const d1010 = v10.dot(v10); const denom = d1010 * d3232 - d3210 * d3210; let d2, d22; if (denom !== 0) { d2 = (d0232 * d3210 - d0210 * d3232) / denom; } else { d2 = 0; } d22 = (d0232 + d2 * d3210) / d3232; result.x = d2; result.y = d22; }; })(); var closestPointsSegmentToSegment = (function() { const paramResult = new Vector2(); const temp14 = new Vector3(); const temp23 = new Vector3(); return function closestPointsSegmentToSegment2(l1, l2, target1, target2) { closestPointLineToLine(l1, l2, paramResult); let d2 = paramResult.x; let d22 = paramResult.y; if (d2 >= 0 && d2 <= 1 && d22 >= 0 && d22 <= 1) { l1.at(d2, target1); l2.at(d22, target2); return; } else if (d2 >= 0 && d2 <= 1) { if (d22 < 0) { l2.at(0, target2); } else { l2.at(1, target2); } l1.closestPointToPoint(target2, true, target1); return; } else if (d22 >= 0 && d22 <= 1) { if (d2 < 0) { l1.at(0, target1); } else { l1.at(1, target1); } l2.closestPointToPoint(target1, true, target2); return; } else { let p2; if (d2 < 0) { p2 = l1.start; } else { p2 = l1.end; } let p22; if (d22 < 0) { p22 = l2.start; } else { p22 = l2.end; } const closestPoint2 = temp14; const closestPoint22 = temp23; l1.closestPointToPoint(p22, true, temp14); l2.closestPointToPoint(p2, true, temp23); if (closestPoint2.distanceToSquared(p22) <= closestPoint22.distanceToSquared(p2)) { target1.copy(closestPoint2); target2.copy(p22); return; } else { target1.copy(p2); target2.copy(closestPoint22); return; } } }; })(); var sphereIntersectTriangle = (function() { const closestPointTemp = new Vector3(); const projectedPointTemp = new Vector3(); const planeTemp = new Plane(); const lineTemp = new Line3(); return function sphereIntersectTriangle2(sphere, triangle4) { const { radius, center: center3 } = sphere; const { a: a6, b: b5, c: c2 } = triangle4; lineTemp.start = a6; lineTemp.end = b5; const closestPoint1 = lineTemp.closestPointToPoint(center3, true, closestPointTemp); if (closestPoint1.distanceTo(center3) <= radius) return true; lineTemp.start = a6; lineTemp.end = c2; const closestPoint2 = lineTemp.closestPointToPoint(center3, true, closestPointTemp); if (closestPoint2.distanceTo(center3) <= radius) return true; lineTemp.start = b5; lineTemp.end = c2; const closestPoint3 = lineTemp.closestPointToPoint(center3, true, closestPointTemp); if (closestPoint3.distanceTo(center3) <= radius) return true; const plane = triangle4.getPlane(planeTemp); const dp = Math.abs(plane.distanceToPoint(center3)); if (dp <= radius) { const pp = plane.projectPoint(center3, projectedPointTemp); const cp = triangle4.containsPoint(pp); if (cp) return true; } return false; }; })(); // node_modules/three-mesh-bvh/src/math/ExtendedTriangle.js var ZERO_EPSILON = 1e-15; function isNearZero(value) { return Math.abs(value) < ZERO_EPSILON; } var ExtendedTriangle = class extends Triangle { constructor(...args) { super(...args); this.isExtendedTriangle = true; this.satAxes = new Array(4).fill().map(() => new Vector3()); this.satBounds = new Array(4).fill().map(() => new SeparatingAxisBounds()); this.points = [this.a, this.b, this.c]; this.sphere = new Sphere(); this.plane = new Plane(); this.needsUpdate = true; } intersectsSphere(sphere) { return sphereIntersectTriangle(sphere, this); } update() { const a6 = this.a; const b5 = this.b; const c2 = this.c; const points = this.points; const satAxes = this.satAxes; const satBounds = this.satBounds; const axis0 = satAxes[0]; const sab0 = satBounds[0]; this.getNormal(axis0); sab0.setFromPoints(axis0, points); const axis1 = satAxes[1]; const sab1 = satBounds[1]; axis1.subVectors(a6, b5); sab1.setFromPoints(axis1, points); const axis2 = satAxes[2]; const sab2 = satBounds[2]; axis2.subVectors(b5, c2); sab2.setFromPoints(axis2, points); const axis3 = satAxes[3]; const sab3 = satBounds[3]; axis3.subVectors(c2, a6); sab3.setFromPoints(axis3, points); this.sphere.setFromPoints(this.points); this.plane.setFromNormalAndCoplanarPoint(axis0, a6); this.needsUpdate = false; } }; ExtendedTriangle.prototype.closestPointToSegment = (function() { const point1 = new Vector3(); const point2 = new Vector3(); const edge = new Line3(); return function distanceToSegment(segment, target1 = null, target2 = null) { const { start, end } = segment; const points = this.points; let distSq; let closestDistanceSq = Infinity; for (let i4 = 0; i4 < 3; i4++) { const nexti = (i4 + 1) % 3; edge.start.copy(points[i4]); edge.end.copy(points[nexti]); closestPointsSegmentToSegment(edge, segment, point1, point2); distSq = point1.distanceToSquared(point2); if (distSq < closestDistanceSq) { closestDistanceSq = distSq; if (target1) target1.copy(point1); if (target2) target2.copy(point2); } } this.closestPointToPoint(start, point1); distSq = start.distanceToSquared(point1); if (distSq < closestDistanceSq) { closestDistanceSq = distSq; if (target1) target1.copy(point1); if (target2) target2.copy(start); } this.closestPointToPoint(end, point1); distSq = end.distanceToSquared(point1); if (distSq < closestDistanceSq) { closestDistanceSq = distSq; if (target1) target1.copy(point1); if (target2) target2.copy(end); } return Math.sqrt(closestDistanceSq); }; })(); ExtendedTriangle.prototype.intersectsTriangle = (function() { const saTri2 = new ExtendedTriangle(); const arr1 = new Array(3); const arr2 = new Array(3); const cachedSatBounds = new SeparatingAxisBounds(); const cachedSatBounds2 = new SeparatingAxisBounds(); const cachedAxis = new Vector3(); const dir = new Vector3(); const dir1 = new Vector3(); const dir2 = new Vector3(); const tempDir = new Vector3(); const edge = new Line3(); const edge1 = new Line3(); const edge2 = new Line3(); const tempPoint = new Vector3(); function triIntersectPlane(tri, plane, targetEdge) { const points = tri.points; let count = 0; let startPointIntersection = -1; for (let i4 = 0; i4 < 3; i4++) { const { start, end } = edge; start.copy(points[i4]); end.copy(points[(i4 + 1) % 3]); edge.delta(dir); const startIntersects = isNearZero(plane.distanceToPoint(start)); if (isNearZero(plane.normal.dot(dir)) && startIntersects) { targetEdge.copy(edge); count = 2; break; } const doesIntersect = plane.intersectLine(edge, tempPoint); if (!doesIntersect && startIntersects) { tempPoint.copy(start); } if ((doesIntersect || startIntersects) && !isNearZero(tempPoint.distanceTo(end))) { if (count <= 1) { const point = count === 1 ? targetEdge.start : targetEdge.end; point.copy(tempPoint); if (startIntersects) { startPointIntersection = count; } } else if (count >= 2) { const point = startPointIntersection === 1 ? targetEdge.start : targetEdge.end; point.copy(tempPoint); count = 2; break; } count++; if (count === 2 && startPointIntersection === -1) { break; } } } return count; } return function intersectsTriangle(other, target2 = null, suppressLog = false) { if (this.needsUpdate) { this.update(); } if (!other.isExtendedTriangle) { saTri2.copy(other); saTri2.update(); other = saTri2; } else if (other.needsUpdate) { other.update(); } const plane1 = this.plane; const plane2 = other.plane; if (Math.abs(plane1.normal.dot(plane2.normal)) > 1 - 1e-10) { const satBounds1 = this.satBounds; const satAxes1 = this.satAxes; arr2[0] = other.a; arr2[1] = other.b; arr2[2] = other.c; for (let i4 = 0; i4 < 4; i4++) { const sb = satBounds1[i4]; const sa = satAxes1[i4]; cachedSatBounds.setFromPoints(sa, arr2); if (sb.isSeparated(cachedSatBounds)) return false; } const satBounds2 = other.satBounds; const satAxes2 = other.satAxes; arr1[0] = this.a; arr1[1] = this.b; arr1[2] = this.c; for (let i4 = 0; i4 < 4; i4++) { const sb = satBounds2[i4]; const sa = satAxes2[i4]; cachedSatBounds.setFromPoints(sa, arr1); if (sb.isSeparated(cachedSatBounds)) return false; } for (let i4 = 0; i4 < 4; i4++) { const sa1 = satAxes1[i4]; for (let i22 = 0; i22 < 4; i22++) { const sa2 = satAxes2[i22]; cachedAxis.crossVectors(sa1, sa2); cachedSatBounds.setFromPoints(cachedAxis, arr1); cachedSatBounds2.setFromPoints(cachedAxis, arr2); if (cachedSatBounds.isSeparated(cachedSatBounds2)) return false; } } if (target2) { if (!suppressLog) { console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."); } target2.start.set(0, 0, 0); target2.end.set(0, 0, 0); } return true; } else { const count1 = triIntersectPlane(this, plane2, edge1); if (count1 === 1 && other.containsPoint(edge1.end)) { if (target2) { target2.start.copy(edge1.end); target2.end.copy(edge1.end); } return true; } else if (count1 !== 2) { return false; } const count2 = triIntersectPlane(other, plane1, edge2); if (count2 === 1 && this.containsPoint(edge2.end)) { if (target2) { target2.start.copy(edge2.end); target2.end.copy(edge2.end); } return true; } else if (count2 !== 2) { return false; } edge1.delta(dir1); edge2.delta(dir2); if (dir1.dot(dir2) < 0) { let tmp = edge2.start; edge2.start = edge2.end; edge2.end = tmp; } const s1 = edge1.start.dot(dir1); const e1 = edge1.end.dot(dir1); const s2 = edge2.start.dot(dir1); const e2 = edge2.end.dot(dir1); const separated1 = e1 < s2; const separated2 = s1 < e2; if (s1 !== e2 && s2 !== e1 && separated1 === separated2) { return false; } if (target2) { tempDir.subVectors(edge1.start, edge2.start); if (tempDir.dot(dir1) > 0) { target2.start.copy(edge1.start); } else { target2.start.copy(edge2.start); } tempDir.subVectors(edge1.end, edge2.end); if (tempDir.dot(dir1) < 0) { target2.end.copy(edge1.end); } else { target2.end.copy(edge2.end); } } return true; } }; })(); ExtendedTriangle.prototype.distanceToPoint = (function() { const target2 = new Vector3(); return function distanceToPoint(point) { this.closestPointToPoint(point, target2); return point.distanceTo(target2); }; })(); ExtendedTriangle.prototype.distanceToTriangle = (function() { const point = new Vector3(); const point2 = new Vector3(); const cornerFields = ["a", "b", "c"]; const line1 = new Line3(); const line2 = new Line3(); return function distanceToTriangle(other, target1 = null, target2 = null) { const lineTarget = target1 || target2 ? line1 : null; if (this.intersectsTriangle(other, lineTarget)) { if (target1 || target2) { if (target1) lineTarget.getCenter(target1); if (target2) lineTarget.getCenter(target2); } return 0; } let closestDistanceSq = Infinity; for (let i4 = 0; i4 < 3; i4++) { let dist; const field = cornerFields[i4]; const otherVec = other[field]; this.closestPointToPoint(otherVec, point); dist = otherVec.distanceToSquared(point); if (dist < closestDistanceSq) { closestDistanceSq = dist; if (target1) target1.copy(point); if (target2) target2.copy(otherVec); } const thisVec = this[field]; other.closestPointToPoint(thisVec, point); dist = thisVec.distanceToSquared(point); if (dist < closestDistanceSq) { closestDistanceSq = dist; if (target1) target1.copy(thisVec); if (target2) target2.copy(point); } } for (let i4 = 0; i4 < 3; i4++) { const f11 = cornerFields[i4]; const f12 = cornerFields[(i4 + 1) % 3]; line1.set(this[f11], this[f12]); for (let i22 = 0; i22 < 3; i22++) { const f21 = cornerFields[i22]; const f22 = cornerFields[(i22 + 1) % 3]; line2.set(other[f21], other[f22]); closestPointsSegmentToSegment(line1, line2, point, point2); const dist = point.distanceToSquared(point2); if (dist < closestDistanceSq) { closestDistanceSq = dist; if (target1) target1.copy(point); if (target2) target2.copy(point2); } } } return Math.sqrt(closestDistanceSq); }; })(); // node_modules/three-mesh-bvh/src/math/OrientedBox.js var OrientedBox = class { constructor(min, max2, matrix6) { this.isOrientedBox = true; this.min = new Vector3(); this.max = new Vector3(); this.matrix = new Matrix4(); this.invMatrix = new Matrix4(); this.points = new Array(8).fill().map(() => new Vector3()); this.satAxes = new Array(3).fill().map(() => new Vector3()); this.satBounds = new Array(3).fill().map(() => new SeparatingAxisBounds()); this.alignedSatBounds = new Array(3).fill().map(() => new SeparatingAxisBounds()); this.needsUpdate = false; if (min) this.min.copy(min); if (max2) this.max.copy(max2); if (matrix6) this.matrix.copy(matrix6); } set(min, max2, matrix6) { this.min.copy(min); this.max.copy(max2); this.matrix.copy(matrix6); this.needsUpdate = true; } copy(other) { this.min.copy(other.min); this.max.copy(other.max); this.matrix.copy(other.matrix); this.needsUpdate = true; } }; OrientedBox.prototype.update = /* @__PURE__ */ (function() { return function update2() { const matrix6 = this.matrix; const min = this.min; const max2 = this.max; const points = this.points; for (let x = 0; x <= 1; x++) { for (let y = 0; y <= 1; y++) { for (let z = 0; z <= 1; z++) { const i4 = (1 << 0) * x | (1 << 1) * y | (1 << 2) * z; const v5 = points[i4]; v5.x = x ? max2.x : min.x; v5.y = y ? max2.y : min.y; v5.z = z ? max2.z : min.z; v5.applyMatrix4(matrix6); } } } const satBounds = this.satBounds; const satAxes = this.satAxes; const minVec = points[0]; for (let i4 = 0; i4 < 3; i4++) { const axis = satAxes[i4]; const sb = satBounds[i4]; const index2 = 1 << i4; const pi = points[index2]; axis.subVectors(minVec, pi); sb.setFromPoints(axis, points); } const alignedSatBounds = this.alignedSatBounds; alignedSatBounds[0].setFromPointsField(points, "x"); alignedSatBounds[1].setFromPointsField(points, "y"); alignedSatBounds[2].setFromPointsField(points, "z"); this.invMatrix.copy(this.matrix).invert(); this.needsUpdate = false; }; })(); OrientedBox.prototype.intersectsBox = (function() { const aabbBounds = new SeparatingAxisBounds(); return function intersectsBox(box) { if (this.needsUpdate) { this.update(); } const min = box.min; const max2 = box.max; const satBounds = this.satBounds; const satAxes = this.satAxes; const alignedSatBounds = this.alignedSatBounds; aabbBounds.min = min.x; aabbBounds.max = max2.x; if (alignedSatBounds[0].isSeparated(aabbBounds)) return false; aabbBounds.min = min.y; aabbBounds.max = max2.y; if (alignedSatBounds[1].isSeparated(aabbBounds)) return false; aabbBounds.min = min.z; aabbBounds.max = max2.z; if (alignedSatBounds[2].isSeparated(aabbBounds)) return false; for (let i4 = 0; i4 < 3; i4++) { const axis = satAxes[i4]; const sb = satBounds[i4]; aabbBounds.setFromBox(axis, box); if (sb.isSeparated(aabbBounds)) return false; } return true; }; })(); OrientedBox.prototype.intersectsTriangle = (function() { const saTri = new ExtendedTriangle(); const pointsArr = new Array(3); const cachedSatBounds = new SeparatingAxisBounds(); const cachedSatBounds2 = new SeparatingAxisBounds(); const cachedAxis = new Vector3(); return function intersectsTriangle(triangle4) { if (this.needsUpdate) { this.update(); } if (!triangle4.isExtendedTriangle) { saTri.copy(triangle4); saTri.update(); triangle4 = saTri; } else if (triangle4.needsUpdate) { triangle4.update(); } const satBounds = this.satBounds; const satAxes = this.satAxes; pointsArr[0] = triangle4.a; pointsArr[1] = triangle4.b; pointsArr[2] = triangle4.c; for (let i4 = 0; i4 < 3; i4++) { const sb = satBounds[i4]; const sa = satAxes[i4]; cachedSatBounds.setFromPoints(sa, pointsArr); if (sb.isSeparated(cachedSatBounds)) return false; } const triSatBounds = triangle4.satBounds; const triSatAxes = triangle4.satAxes; const points = this.points; for (let i4 = 0; i4 < 3; i4++) { const sb = triSatBounds[i4]; const sa = triSatAxes[i4]; cachedSatBounds.setFromPoints(sa, points); if (sb.isSeparated(cachedSatBounds)) return false; } for (let i4 = 0; i4 < 3; i4++) { const sa1 = satAxes[i4]; for (let i22 = 0; i22 < 4; i22++) { const sa2 = triSatAxes[i22]; cachedAxis.crossVectors(sa1, sa2); cachedSatBounds.setFromPoints(cachedAxis, pointsArr); cachedSatBounds2.setFromPoints(cachedAxis, points); if (cachedSatBounds.isSeparated(cachedSatBounds2)) return false; } } return true; }; })(); OrientedBox.prototype.closestPointToPoint = /* @__PURE__ */ (function() { return function closestPointToPoint2(point, target1) { if (this.needsUpdate) { this.update(); } target1.copy(point).applyMatrix4(this.invMatrix).clamp(this.min, this.max).applyMatrix4(this.matrix); return target1; }; })(); OrientedBox.prototype.distanceToPoint = (function() { const target2 = new Vector3(); return function distanceToPoint(point) { this.closestPointToPoint(point, target2); return point.distanceTo(target2); }; })(); OrientedBox.prototype.distanceToBox = (function() { const xyzFields = ["x", "y", "z"]; const segments1 = new Array(12).fill().map(() => new Line3()); const segments2 = new Array(12).fill().map(() => new Line3()); const point1 = new Vector3(); const point2 = new Vector3(); return function distanceToBox(box, threshold = 0, target1 = null, target2 = null) { if (this.needsUpdate) { this.update(); } if (this.intersectsBox(box)) { if (target1 || target2) { box.getCenter(point2); this.closestPointToPoint(point2, point1); box.closestPointToPoint(point1, point2); if (target1) target1.copy(point1); if (target2) target2.copy(point2); } return 0; } const threshold2 = threshold * threshold; const min = box.min; const max2 = box.max; const points = this.points; let closestDistanceSq = Infinity; for (let i4 = 0; i4 < 8; i4++) { const p2 = points[i4]; point2.copy(p2).clamp(min, max2); const dist = p2.distanceToSquared(point2); if (dist < closestDistanceSq) { closestDistanceSq = dist; if (target1) target1.copy(p2); if (target2) target2.copy(point2); if (dist < threshold2) return Math.sqrt(dist); } } let count = 0; for (let i4 = 0; i4 < 3; i4++) { for (let i1 = 0; i1 <= 1; i1++) { for (let i22 = 0; i22 <= 1; i22++) { const nextIndex = (i4 + 1) % 3; const nextIndex2 = (i4 + 2) % 3; const index2 = i1 << nextIndex | i22 << nextIndex2; const index22 = 1 << i4 | i1 << nextIndex | i22 << nextIndex2; const p1 = points[index2]; const p2 = points[index22]; const line1 = segments1[count]; line1.set(p1, p2); const f1 = xyzFields[i4]; const f2 = xyzFields[nextIndex]; const f3 = xyzFields[nextIndex2]; const line2 = segments2[count]; const start = line2.start; const end = line2.end; start[f1] = min[f1]; start[f2] = i1 ? min[f2] : max2[f2]; start[f3] = i22 ? min[f3] : max2[f2]; end[f1] = max2[f1]; end[f2] = i1 ? min[f2] : max2[f2]; end[f3] = i22 ? min[f3] : max2[f2]; count++; } } } for (let x = 0; x <= 1; x++) { for (let y = 0; y <= 1; y++) { for (let z = 0; z <= 1; z++) { point2.x = x ? max2.x : min.x; point2.y = y ? max2.y : min.y; point2.z = z ? max2.z : min.z; this.closestPointToPoint(point2, point1); const dist = point2.distanceToSquared(point1); if (dist < closestDistanceSq) { closestDistanceSq = dist; if (target1) target1.copy(point1); if (target2) target2.copy(point2); if (dist < threshold2) return Math.sqrt(dist); } } } } for (let i4 = 0; i4 < 12; i4++) { const l1 = segments1[i4]; for (let i22 = 0; i22 < 12; i22++) { const l2 = segments2[i22]; closestPointsSegmentToSegment(l1, l2, point1, point2); const dist = point1.distanceToSquared(point2); if (dist < closestDistanceSq) { closestDistanceSq = dist; if (target1) target1.copy(point1); if (target2) target2.copy(point2); if (dist < threshold2) return Math.sqrt(dist); } } } return Math.sqrt(closestDistanceSq); }; })(); // node_modules/three-mesh-bvh/src/utils/PrimitivePool.js var PrimitivePool = class { constructor(getNewPrimitive) { this._getNewPrimitive = getNewPrimitive; this._primitives = []; } getPrimitive() { const primitives = this._primitives; if (primitives.length === 0) { return this._getNewPrimitive(); } else { return primitives.pop(); } } releasePrimitive(primitive) { this._primitives.push(primitive); } }; // node_modules/three-mesh-bvh/src/utils/ExtendedTrianglePool.js var ExtendedTrianglePoolBase = class extends PrimitivePool { constructor() { super(() => new ExtendedTriangle()); } }; var ExtendedTrianglePool = new ExtendedTrianglePoolBase(); // node_modules/three-mesh-bvh/src/core/utils/BufferStack.js var _BufferStack = class { constructor() { this.float32Array = null; this.uint16Array = null; this.uint32Array = null; const stack = []; let prevBuffer = null; this.setBuffer = (buffer2) => { if (prevBuffer) { stack.push(prevBuffer); } prevBuffer = buffer2; this.float32Array = new Float32Array(buffer2); this.uint16Array = new Uint16Array(buffer2); this.uint32Array = new Uint32Array(buffer2); }; this.clearBuffer = () => { prevBuffer = null; this.float32Array = null; this.uint16Array = null; this.uint32Array = null; if (stack.length !== 0) { this.setBuffer(stack.pop()); } }; } }; var BufferStack = new _BufferStack(); // node_modules/three-mesh-bvh/src/core/cast/shapecast.js var _box1; var _box22; var boxStack = []; var boxPool = new PrimitivePool(() => new Box3()); function shapecast(bvh, root, intersectsBounds, intersectsRange, boundsTraverseOrder, byteOffset) { _box1 = boxPool.getPrimitive(); _box22 = boxPool.getPrimitive(); boxStack.push(_box1, _box22); BufferStack.setBuffer(bvh._roots[root]); const result = shapecastTraverse(0, bvh.geometry, intersectsBounds, intersectsRange, boundsTraverseOrder, byteOffset); BufferStack.clearBuffer(); boxPool.releasePrimitive(_box1); boxPool.releasePrimitive(_box22); boxStack.pop(); boxStack.pop(); const length3 = boxStack.length; if (length3 > 0) { _box22 = boxStack[length3 - 1]; _box1 = boxStack[length3 - 2]; } return result; } function shapecastTraverse(nodeIndex32, geometry3, intersectsBoundsFunc, intersectsRangeFunc, nodeScoreFunc = null, nodeIndexByteOffset = 0, depth = 0) { const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack; let nodeIndex16 = nodeIndex32 * 2; const isLeaf = IS_LEAF(nodeIndex16, uint16Array2); if (isLeaf) { const offset = OFFSET(nodeIndex32, uint32Array2); const count = COUNT(nodeIndex16, uint16Array2); arrayToBox(BOUNDING_DATA_INDEX(nodeIndex32), float32Array2, _box1); return intersectsRangeFunc(offset, count, false, depth, nodeIndexByteOffset + nodeIndex32, _box1); } else { let getLeftOffset = function(nodeIndex322) { const { uint16Array: uint16Array3, uint32Array: uint32Array3 } = BufferStack; let nodeIndex162 = nodeIndex322 * 2; while (!IS_LEAF(nodeIndex162, uint16Array3)) { nodeIndex322 = LEFT_NODE(nodeIndex322); nodeIndex162 = nodeIndex322 * 2; } return OFFSET(nodeIndex322, uint32Array3); }, getRightEndOffset = function(nodeIndex322) { const { uint16Array: uint16Array3, uint32Array: uint32Array3 } = BufferStack; let nodeIndex162 = nodeIndex322 * 2; while (!IS_LEAF(nodeIndex162, uint16Array3)) { nodeIndex322 = RIGHT_NODE(nodeIndex322, uint32Array3); nodeIndex162 = nodeIndex322 * 2; } return OFFSET(nodeIndex322, uint32Array3) + COUNT(nodeIndex162, uint16Array3); }; const left = LEFT_NODE(nodeIndex32); const right = RIGHT_NODE(nodeIndex32, uint32Array2); let c1 = left; let c2 = right; let score1, score2; let box1, box2; if (nodeScoreFunc) { box1 = _box1; box2 = _box22; arrayToBox(BOUNDING_DATA_INDEX(c1), float32Array2, box1); arrayToBox(BOUNDING_DATA_INDEX(c2), float32Array2, box2); score1 = nodeScoreFunc(box1); score2 = nodeScoreFunc(box2); if (score2 < score1) { c1 = right; c2 = left; const temp5 = score1; score1 = score2; score2 = temp5; box1 = box2; } } if (!box1) { box1 = _box1; arrayToBox(BOUNDING_DATA_INDEX(c1), float32Array2, box1); } const isC1Leaf = IS_LEAF(c1 * 2, uint16Array2); const c1Intersection = intersectsBoundsFunc(box1, isC1Leaf, score1, depth + 1, nodeIndexByteOffset + c1); let c1StopTraversal; if (c1Intersection === CONTAINED) { const offset = getLeftOffset(c1); const end = getRightEndOffset(c1); const count = end - offset; c1StopTraversal = intersectsRangeFunc(offset, count, true, depth + 1, nodeIndexByteOffset + c1, box1); } else { c1StopTraversal = c1Intersection && shapecastTraverse( c1, geometry3, intersectsBoundsFunc, intersectsRangeFunc, nodeScoreFunc, nodeIndexByteOffset, depth + 1 ); } if (c1StopTraversal) return true; box2 = _box22; arrayToBox(BOUNDING_DATA_INDEX(c2), float32Array2, box2); const isC2Leaf = IS_LEAF(c2 * 2, uint16Array2); const c2Intersection = intersectsBoundsFunc(box2, isC2Leaf, score2, depth + 1, nodeIndexByteOffset + c2); let c2StopTraversal; if (c2Intersection === CONTAINED) { const offset = getLeftOffset(c2); const end = getRightEndOffset(c2); const count = end - offset; c2StopTraversal = intersectsRangeFunc(offset, count, true, depth + 1, nodeIndexByteOffset + c2, box2); } else { c2StopTraversal = c2Intersection && shapecastTraverse( c2, geometry3, intersectsBoundsFunc, intersectsRangeFunc, nodeScoreFunc, nodeIndexByteOffset, depth + 1 ); } if (c2StopTraversal) return true; return false; } } // node_modules/three-mesh-bvh/src/core/cast/closestPointToPoint.js var temp = new Vector3(); var temp1 = new Vector3(); function closestPointToPoint(bvh, point, target2 = {}, minThreshold = 0, maxThreshold = Infinity) { const minThresholdSq = minThreshold * minThreshold; const maxThresholdSq = maxThreshold * maxThreshold; let closestDistanceSq = Infinity; let closestDistanceTriIndex = null; bvh.shapecast( { boundsTraverseOrder: (box) => { temp.copy(point).clamp(box.min, box.max); return temp.distanceToSquared(point); }, intersectsBounds: (box, isLeaf, score) => { return score < closestDistanceSq && score < maxThresholdSq; }, intersectsTriangle: (tri, triIndex) => { tri.closestPointToPoint(point, temp); const distSq = point.distanceToSquared(temp); if (distSq < closestDistanceSq) { temp1.copy(temp); closestDistanceSq = distSq; closestDistanceTriIndex = triIndex; } if (distSq < minThresholdSq) { return true; } else { return false; } } } ); if (closestDistanceSq === Infinity) return null; const closestDistance = Math.sqrt(closestDistanceSq); if (!target2.point) target2.point = temp1.clone(); else target2.point.copy(temp1); target2.distance = closestDistance, target2.faceIndex = closestDistanceTriIndex; return target2; } // node_modules/three-mesh-bvh/src/utils/ThreeRayIntersectUtilities.js var IS_GT_REVISION_169 = parseInt(REVISION) >= 169; var _vA2 = new Vector3(); var _vB2 = new Vector3(); var _vC2 = new Vector3(); var _uvA = new Vector2(); var _uvB = new Vector2(); var _uvC = new Vector2(); var _normalA = new Vector3(); var _normalB = new Vector3(); var _normalC = new Vector3(); var _intersectionPoint = new Vector3(); function checkIntersection(ray4, pA, pB, pC, point, side, near, far) { let intersect; if (side === BackSide) { intersect = ray4.intersectTriangle(pC, pB, pA, true, point); } else { intersect = ray4.intersectTriangle(pA, pB, pC, side !== DoubleSide, point); } if (intersect === null) return null; const distance3 = ray4.origin.distanceTo(point); if (distance3 < near || distance3 > far) return null; return { distance: distance3, point: point.clone() }; } function checkBufferGeometryIntersection(ray4, position2, normal2, uv, uv1, a6, b5, c2, side, near, far) { _vA2.fromBufferAttribute(position2, a6); _vB2.fromBufferAttribute(position2, b5); _vC2.fromBufferAttribute(position2, c2); const intersection3 = checkIntersection(ray4, _vA2, _vB2, _vC2, _intersectionPoint, side, near, far); if (intersection3) { const barycoord = new Vector3(); Triangle.getBarycoord(_intersectionPoint, _vA2, _vB2, _vC2, barycoord); if (uv) { _uvA.fromBufferAttribute(uv, a6); _uvB.fromBufferAttribute(uv, b5); _uvC.fromBufferAttribute(uv, c2); intersection3.uv = Triangle.getInterpolation(_intersectionPoint, _vA2, _vB2, _vC2, _uvA, _uvB, _uvC, new Vector2()); } if (uv1) { _uvA.fromBufferAttribute(uv1, a6); _uvB.fromBufferAttribute(uv1, b5); _uvC.fromBufferAttribute(uv1, c2); intersection3.uv1 = Triangle.getInterpolation(_intersectionPoint, _vA2, _vB2, _vC2, _uvA, _uvB, _uvC, new Vector2()); } if (normal2) { _normalA.fromBufferAttribute(normal2, a6); _normalB.fromBufferAttribute(normal2, b5); _normalC.fromBufferAttribute(normal2, c2); intersection3.normal = Triangle.getInterpolation(_intersectionPoint, _vA2, _vB2, _vC2, _normalA, _normalB, _normalC, new Vector3()); if (intersection3.normal.dot(ray4.direction) > 0) { intersection3.normal.multiplyScalar(-1); } } const face = { a: a6, b: b5, c: c2, normal: new Vector3(), materialIndex: 0 }; Triangle.getNormal(_vA2, _vB2, _vC2, face.normal); intersection3.face = face; intersection3.faceIndex = a6; if (IS_GT_REVISION_169) { intersection3.barycoord = barycoord; } } return intersection3; } function intersectTri(geo, side, ray4, tri, intersections, near, far) { const triOffset = tri * 3; let a6 = triOffset + 0; let b5 = triOffset + 1; let c2 = triOffset + 2; const index2 = geo.index; if (geo.index) { a6 = index2.getX(a6); b5 = index2.getX(b5); c2 = index2.getX(c2); } const { position: position2, normal: normal2, uv, uv1 } = geo.attributes; const intersection3 = checkBufferGeometryIntersection(ray4, position2, normal2, uv, uv1, a6, b5, c2, side, near, far); if (intersection3) { intersection3.faceIndex = tri; if (intersections) intersections.push(intersection3); return intersection3; } return null; } // node_modules/three-mesh-bvh/src/utils/TriangleUtilities.js function setTriangle(tri, i4, index2, pos) { const ta = tri.a; const tb = tri.b; const tc = tri.c; let i0 = i4; let i1 = i4 + 1; let i22 = i4 + 2; if (index2) { i0 = index2.getX(i0); i1 = index2.getX(i1); i22 = index2.getX(i22); } ta.x = pos.getX(i0); ta.y = pos.getY(i0); ta.z = pos.getZ(i0); tb.x = pos.getX(i1); tb.y = pos.getY(i1); tb.z = pos.getZ(i1); tc.x = pos.getX(i22); tc.y = pos.getY(i22); tc.z = pos.getZ(i22); } var tempV1 = new Vector3(); var tempV2 = new Vector3(); var tempV3 = new Vector3(); var tempUV1 = new Vector2(); var tempUV2 = new Vector2(); var tempUV3 = new Vector2(); // node_modules/three-mesh-bvh/src/core/utils/iterationUtils.generated.js function intersectTris(bvh, side, ray4, offset, count, intersections, near, far) { const { geometry: geometry3, _indirectBuffer } = bvh; for (let i4 = offset, end = offset + count; i4 < end; i4++) { intersectTri(geometry3, side, ray4, i4, intersections, near, far); } } function intersectClosestTri(bvh, side, ray4, offset, count, near, far) { const { geometry: geometry3, _indirectBuffer } = bvh; let dist = Infinity; let res = null; for (let i4 = offset, end = offset + count; i4 < end; i4++) { let intersection3; intersection3 = intersectTri(geometry3, side, ray4, i4, null, near, far); if (intersection3 && intersection3.distance < dist) { res = intersection3; dist = intersection3.distance; } } return res; } function iterateOverTriangles(offset, count, bvh, intersectsTriangleFunc, contained, depth, triangle4) { const { geometry: geometry3 } = bvh; const { index: index2 } = geometry3; const pos = geometry3.attributes.position; for (let i4 = offset, l2 = count + offset; i4 < l2; i4++) { let tri; tri = i4; setTriangle(triangle4, tri * 3, index2, pos); triangle4.needsUpdate = true; if (intersectsTriangleFunc(triangle4, tri, contained, depth)) { return true; } } return false; } // node_modules/three-mesh-bvh/src/core/cast/refit.generated.js function refit(bvh, nodeIndices = null) { if (nodeIndices && Array.isArray(nodeIndices)) { nodeIndices = new Set(nodeIndices); } const geometry3 = bvh.geometry; const indexArr = geometry3.index ? geometry3.index.array : null; const posAttr = geometry3.attributes.position; let buffer2, uint32Array2, uint16Array2, float32Array2; let byteOffset = 0; const roots = bvh._roots; for (let i4 = 0, l2 = roots.length; i4 < l2; i4++) { buffer2 = roots[i4]; uint32Array2 = new Uint32Array(buffer2); uint16Array2 = new Uint16Array(buffer2); float32Array2 = new Float32Array(buffer2); _traverse2(0, byteOffset); byteOffset += buffer2.byteLength; } function _traverse2(node32Index, byteOffset2, force = false) { const node16Index = node32Index * 2; const isLeaf = uint16Array2[node16Index + 15] === IS_LEAFNODE_FLAG; if (isLeaf) { const offset = uint32Array2[node32Index + 6]; const count = uint16Array2[node16Index + 14]; let minx = Infinity; let miny = Infinity; let minz = Infinity; let maxx = -Infinity; let maxy = -Infinity; let maxz = -Infinity; for (let i4 = 3 * offset, l2 = 3 * (offset + count); i4 < l2; i4++) { let index2 = indexArr[i4]; const x = posAttr.getX(index2); const y = posAttr.getY(index2); const z = posAttr.getZ(index2); if (x < minx) minx = x; if (x > maxx) maxx = x; if (y < miny) miny = y; if (y > maxy) maxy = y; if (z < minz) minz = z; if (z > maxz) maxz = z; } if (float32Array2[node32Index + 0] !== minx || float32Array2[node32Index + 1] !== miny || float32Array2[node32Index + 2] !== minz || float32Array2[node32Index + 3] !== maxx || float32Array2[node32Index + 4] !== maxy || float32Array2[node32Index + 5] !== maxz) { float32Array2[node32Index + 0] = minx; float32Array2[node32Index + 1] = miny; float32Array2[node32Index + 2] = minz; float32Array2[node32Index + 3] = maxx; float32Array2[node32Index + 4] = maxy; float32Array2[node32Index + 5] = maxz; return true; } else { return false; } } else { const left = node32Index + 8; const right = uint32Array2[node32Index + 6]; const offsetLeft = left + byteOffset2; const offsetRight = right + byteOffset2; let forceChildren = force; let includesLeft = false; let includesRight = false; if (nodeIndices) { if (!forceChildren) { includesLeft = nodeIndices.has(offsetLeft); includesRight = nodeIndices.has(offsetRight); forceChildren = !includesLeft && !includesRight; } } else { includesLeft = true; includesRight = true; } const traverseLeft = forceChildren || includesLeft; const traverseRight = forceChildren || includesRight; let leftChange = false; if (traverseLeft) { leftChange = _traverse2(left, byteOffset2, forceChildren); } let rightChange = false; if (traverseRight) { rightChange = _traverse2(right, byteOffset2, forceChildren); } const didChange = leftChange || rightChange; if (didChange) { for (let i4 = 0; i4 < 3; i4++) { const lefti = left + i4; const righti = right + i4; const minLeftValue = float32Array2[lefti]; const maxLeftValue = float32Array2[lefti + 3]; const minRightValue = float32Array2[righti]; const maxRightValue = float32Array2[righti + 3]; float32Array2[node32Index + i4] = minLeftValue < minRightValue ? minLeftValue : minRightValue; float32Array2[node32Index + i4 + 3] = maxLeftValue > maxRightValue ? maxLeftValue : maxRightValue; } } return didChange; } } } // node_modules/three-mesh-bvh/src/core/utils/intersectUtils.js function intersectRay(nodeIndex32, array, ray4, near, far) { let tmin, tmax, tymin, tymax, tzmin, tzmax; const invdirx = 1 / ray4.direction.x, invdiry = 1 / ray4.direction.y, invdirz = 1 / ray4.direction.z; const ox = ray4.origin.x; const oy = ray4.origin.y; const oz = ray4.origin.z; let minx = array[nodeIndex32]; let maxx = array[nodeIndex32 + 3]; let miny = array[nodeIndex32 + 1]; let maxy = array[nodeIndex32 + 3 + 1]; let minz = array[nodeIndex32 + 2]; let maxz = array[nodeIndex32 + 3 + 2]; if (invdirx >= 0) { tmin = (minx - ox) * invdirx; tmax = (maxx - ox) * invdirx; } else { tmin = (maxx - ox) * invdirx; tmax = (minx - ox) * invdirx; } if (invdiry >= 0) { tymin = (miny - oy) * invdiry; tymax = (maxy - oy) * invdiry; } else { tymin = (maxy - oy) * invdiry; tymax = (miny - oy) * invdiry; } if (tmin > tymax || tymin > tmax) return false; if (tymin > tmin || isNaN(tmin)) tmin = tymin; if (tymax < tmax || isNaN(tmax)) tmax = tymax; if (invdirz >= 0) { tzmin = (minz - oz) * invdirz; tzmax = (maxz - oz) * invdirz; } else { tzmin = (maxz - oz) * invdirz; tzmax = (minz - oz) * invdirz; } if (tmin > tzmax || tzmin > tmax) return false; if (tzmin > tmin || tmin !== tmin) tmin = tzmin; if (tzmax < tmax || tmax !== tmax) tmax = tzmax; return tmin <= far && tmax >= near; } // node_modules/three-mesh-bvh/src/core/utils/iterationUtils_indirect.generated.js function intersectTris_indirect(bvh, side, ray4, offset, count, intersections, near, far) { const { geometry: geometry3, _indirectBuffer } = bvh; for (let i4 = offset, end = offset + count; i4 < end; i4++) { let vi = _indirectBuffer ? _indirectBuffer[i4] : i4; intersectTri(geometry3, side, ray4, vi, intersections, near, far); } } function intersectClosestTri_indirect(bvh, side, ray4, offset, count, near, far) { const { geometry: geometry3, _indirectBuffer } = bvh; let dist = Infinity; let res = null; for (let i4 = offset, end = offset + count; i4 < end; i4++) { let intersection3; intersection3 = intersectTri(geometry3, side, ray4, _indirectBuffer ? _indirectBuffer[i4] : i4, null, near, far); if (intersection3 && intersection3.distance < dist) { res = intersection3; dist = intersection3.distance; } } return res; } function iterateOverTriangles_indirect(offset, count, bvh, intersectsTriangleFunc, contained, depth, triangle4) { const { geometry: geometry3 } = bvh; const { index: index2 } = geometry3; const pos = geometry3.attributes.position; for (let i4 = offset, l2 = count + offset; i4 < l2; i4++) { let tri; tri = bvh.resolveTriangleIndex(i4); setTriangle(triangle4, tri * 3, index2, pos); triangle4.needsUpdate = true; if (intersectsTriangleFunc(triangle4, tri, contained, depth)) { return true; } } return false; } // node_modules/three-mesh-bvh/src/core/cast/raycast.generated.js function raycast(bvh, root, side, ray4, intersects, near, far) { BufferStack.setBuffer(bvh._roots[root]); _raycast(0, bvh, side, ray4, intersects, near, far); BufferStack.clearBuffer(); } function _raycast(nodeIndex32, bvh, side, ray4, intersects, near, far) { const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack; const nodeIndex16 = nodeIndex32 * 2; const isLeaf = IS_LEAF(nodeIndex16, uint16Array2); if (isLeaf) { const offset = OFFSET(nodeIndex32, uint32Array2); const count = COUNT(nodeIndex16, uint16Array2); intersectTris(bvh, side, ray4, offset, count, intersects, near, far); } else { const leftIndex = LEFT_NODE(nodeIndex32); if (intersectRay(leftIndex, float32Array2, ray4, near, far)) { _raycast(leftIndex, bvh, side, ray4, intersects, near, far); } const rightIndex = RIGHT_NODE(nodeIndex32, uint32Array2); if (intersectRay(rightIndex, float32Array2, ray4, near, far)) { _raycast(rightIndex, bvh, side, ray4, intersects, near, far); } } } // node_modules/three-mesh-bvh/src/core/cast/raycastFirst.generated.js var _xyzFields = ["x", "y", "z"]; function raycastFirst(bvh, root, side, ray4, near, far) { BufferStack.setBuffer(bvh._roots[root]); const result = _raycastFirst(0, bvh, side, ray4, near, far); BufferStack.clearBuffer(); return result; } function _raycastFirst(nodeIndex32, bvh, side, ray4, near, far) { const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack; let nodeIndex16 = nodeIndex32 * 2; const isLeaf = IS_LEAF(nodeIndex16, uint16Array2); if (isLeaf) { const offset = OFFSET(nodeIndex32, uint32Array2); const count = COUNT(nodeIndex16, uint16Array2); return intersectClosestTri(bvh, side, ray4, offset, count, near, far); } else { const splitAxis = SPLIT_AXIS(nodeIndex32, uint32Array2); const xyzAxis = _xyzFields[splitAxis]; const rayDir = ray4.direction[xyzAxis]; const leftToRight = rayDir >= 0; let c1, c2; if (leftToRight) { c1 = LEFT_NODE(nodeIndex32); c2 = RIGHT_NODE(nodeIndex32, uint32Array2); } else { c1 = RIGHT_NODE(nodeIndex32, uint32Array2); c2 = LEFT_NODE(nodeIndex32); } const c1Intersection = intersectRay(c1, float32Array2, ray4, near, far); const c1Result = c1Intersection ? _raycastFirst(c1, bvh, side, ray4, near, far) : null; if (c1Result) { const point = c1Result.point[xyzAxis]; const isOutside = leftToRight ? point <= float32Array2[c2 + splitAxis] : ( // min bounding data point >= float32Array2[c2 + splitAxis + 3] ); if (isOutside) { return c1Result; } } const c2Intersection = intersectRay(c2, float32Array2, ray4, near, far); const c2Result = c2Intersection ? _raycastFirst(c2, bvh, side, ray4, near, far) : null; if (c1Result && c2Result) { return c1Result.distance <= c2Result.distance ? c1Result : c2Result; } else { return c1Result || c2Result || null; } } } // node_modules/three-mesh-bvh/src/core/cast/intersectsGeometry.generated.js var boundingBox = new Box3(); var triangle2 = new ExtendedTriangle(); var triangle22 = new ExtendedTriangle(); var invertedMat = new Matrix4(); var obb2 = new OrientedBox(); var obb22 = new OrientedBox(); function intersectsGeometry(bvh, root, otherGeometry, geometryToBvh) { BufferStack.setBuffer(bvh._roots[root]); const result = _intersectsGeometry(0, bvh, otherGeometry, geometryToBvh); BufferStack.clearBuffer(); return result; } function _intersectsGeometry(nodeIndex32, bvh, otherGeometry, geometryToBvh, cachedObb = null) { const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack; let nodeIndex16 = nodeIndex32 * 2; if (cachedObb === null) { if (!otherGeometry.boundingBox) { otherGeometry.computeBoundingBox(); } obb2.set(otherGeometry.boundingBox.min, otherGeometry.boundingBox.max, geometryToBvh); cachedObb = obb2; } const isLeaf = IS_LEAF(nodeIndex16, uint16Array2); if (isLeaf) { const thisGeometry = bvh.geometry; const thisIndex = thisGeometry.index; const thisPos = thisGeometry.attributes.position; const index2 = otherGeometry.index; const pos = otherGeometry.attributes.position; const offset = OFFSET(nodeIndex32, uint32Array2); const count = COUNT(nodeIndex16, uint16Array2); invertedMat.copy(geometryToBvh).invert(); if (otherGeometry.boundsTree) { arrayToBox(BOUNDING_DATA_INDEX(nodeIndex32), float32Array2, obb22); obb22.matrix.copy(invertedMat); obb22.needsUpdate = true; const res = otherGeometry.boundsTree.shapecast({ intersectsBounds: (box) => obb22.intersectsBox(box), intersectsTriangle: (tri) => { tri.a.applyMatrix4(geometryToBvh); tri.b.applyMatrix4(geometryToBvh); tri.c.applyMatrix4(geometryToBvh); tri.needsUpdate = true; for (let i4 = offset * 3, l2 = (count + offset) * 3; i4 < l2; i4 += 3) { setTriangle(triangle22, i4, thisIndex, thisPos); triangle22.needsUpdate = true; if (tri.intersectsTriangle(triangle22)) { return true; } } return false; } }); return res; } else { for (let i4 = offset * 3, l2 = (count + offset) * 3; i4 < l2; i4 += 3) { setTriangle(triangle2, i4, thisIndex, thisPos); triangle2.a.applyMatrix4(invertedMat); triangle2.b.applyMatrix4(invertedMat); triangle2.c.applyMatrix4(invertedMat); triangle2.needsUpdate = true; for (let i22 = 0, l22 = index2.count; i22 < l22; i22 += 3) { setTriangle(triangle22, i22, index2, pos); triangle22.needsUpdate = true; if (triangle2.intersectsTriangle(triangle22)) { return true; } } } } } else { const left = nodeIndex32 + 8; const right = uint32Array2[nodeIndex32 + 6]; arrayToBox(BOUNDING_DATA_INDEX(left), float32Array2, boundingBox); const leftIntersection = cachedObb.intersectsBox(boundingBox) && _intersectsGeometry(left, bvh, otherGeometry, geometryToBvh, cachedObb); if (leftIntersection) return true; arrayToBox(BOUNDING_DATA_INDEX(right), float32Array2, boundingBox); const rightIntersection = cachedObb.intersectsBox(boundingBox) && _intersectsGeometry(right, bvh, otherGeometry, geometryToBvh, cachedObb); if (rightIntersection) return true; return false; } } // node_modules/three-mesh-bvh/src/core/cast/closestPointToGeometry.generated.js var tempMatrix = new Matrix4(); var obb3 = new OrientedBox(); var obb23 = new OrientedBox(); var temp12 = new Vector3(); var temp2 = new Vector3(); var temp3 = new Vector3(); var temp4 = new Vector3(); function closestPointToGeometry(bvh, otherGeometry, geometryToBvh, target1 = {}, target2 = {}, minThreshold = 0, maxThreshold = Infinity) { if (!otherGeometry.boundingBox) { otherGeometry.computeBoundingBox(); } obb3.set(otherGeometry.boundingBox.min, otherGeometry.boundingBox.max, geometryToBvh); obb3.needsUpdate = true; const geometry3 = bvh.geometry; const pos = geometry3.attributes.position; const index2 = geometry3.index; const otherPos = otherGeometry.attributes.position; const otherIndex = otherGeometry.index; const triangle4 = ExtendedTrianglePool.getPrimitive(); const triangle24 = ExtendedTrianglePool.getPrimitive(); let tempTarget1 = temp12; let tempTargetDest1 = temp2; let tempTarget2 = null; let tempTargetDest2 = null; if (target2) { tempTarget2 = temp3; tempTargetDest2 = temp4; } let closestDistance = Infinity; let closestDistanceTriIndex = null; let closestDistanceOtherTriIndex = null; tempMatrix.copy(geometryToBvh).invert(); obb23.matrix.copy(tempMatrix); bvh.shapecast( { boundsTraverseOrder: (box) => { return obb3.distanceToBox(box); }, intersectsBounds: (box, isLeaf, score) => { if (score < closestDistance && score < maxThreshold) { if (isLeaf) { obb23.min.copy(box.min); obb23.max.copy(box.max); obb23.needsUpdate = true; } return true; } return false; }, intersectsRange: (offset, count) => { if (otherGeometry.boundsTree) { const otherBvh = otherGeometry.boundsTree; return otherBvh.shapecast({ boundsTraverseOrder: (box) => { return obb23.distanceToBox(box); }, intersectsBounds: (box, isLeaf, score) => { return score < closestDistance && score < maxThreshold; }, intersectsRange: (otherOffset, otherCount) => { for (let i22 = otherOffset, l2 = otherOffset + otherCount; i22 < l2; i22++) { setTriangle(triangle24, 3 * i22, otherIndex, otherPos); triangle24.a.applyMatrix4(geometryToBvh); triangle24.b.applyMatrix4(geometryToBvh); triangle24.c.applyMatrix4(geometryToBvh); triangle24.needsUpdate = true; for (let i4 = offset, l3 = offset + count; i4 < l3; i4++) { setTriangle(triangle4, 3 * i4, index2, pos); triangle4.needsUpdate = true; const dist = triangle4.distanceToTriangle(triangle24, tempTarget1, tempTarget2); if (dist < closestDistance) { tempTargetDest1.copy(tempTarget1); if (tempTargetDest2) { tempTargetDest2.copy(tempTarget2); } closestDistance = dist; closestDistanceTriIndex = i4; closestDistanceOtherTriIndex = i22; } if (dist < minThreshold) { return true; } } } } }); } else { const triCount = getTriCount(otherGeometry); for (let i22 = 0, l2 = triCount; i22 < l2; i22++) { setTriangle(triangle24, 3 * i22, otherIndex, otherPos); triangle24.a.applyMatrix4(geometryToBvh); triangle24.b.applyMatrix4(geometryToBvh); triangle24.c.applyMatrix4(geometryToBvh); triangle24.needsUpdate = true; for (let i4 = offset, l3 = offset + count; i4 < l3; i4++) { setTriangle(triangle4, 3 * i4, index2, pos); triangle4.needsUpdate = true; const dist = triangle4.distanceToTriangle(triangle24, tempTarget1, tempTarget2); if (dist < closestDistance) { tempTargetDest1.copy(tempTarget1); if (tempTargetDest2) { tempTargetDest2.copy(tempTarget2); } closestDistance = dist; closestDistanceTriIndex = i4; closestDistanceOtherTriIndex = i22; } if (dist < minThreshold) { return true; } } } } } } ); ExtendedTrianglePool.releasePrimitive(triangle4); ExtendedTrianglePool.releasePrimitive(triangle24); if (closestDistance === Infinity) { return null; } if (!target1.point) { target1.point = tempTargetDest1.clone(); } else { target1.point.copy(tempTargetDest1); } target1.distance = closestDistance, target1.faceIndex = closestDistanceTriIndex; if (target2) { if (!target2.point) target2.point = tempTargetDest2.clone(); else target2.point.copy(tempTargetDest2); target2.point.applyMatrix4(tempMatrix); tempTargetDest1.applyMatrix4(tempMatrix); target2.distance = tempTargetDest1.sub(target2.point).length(); target2.faceIndex = closestDistanceOtherTriIndex; } return target1; } // node_modules/three-mesh-bvh/src/core/cast/refit_indirect.generated.js function refit_indirect(bvh, nodeIndices = null) { if (nodeIndices && Array.isArray(nodeIndices)) { nodeIndices = new Set(nodeIndices); } const geometry3 = bvh.geometry; const indexArr = geometry3.index ? geometry3.index.array : null; const posAttr = geometry3.attributes.position; let buffer2, uint32Array2, uint16Array2, float32Array2; let byteOffset = 0; const roots = bvh._roots; for (let i4 = 0, l2 = roots.length; i4 < l2; i4++) { buffer2 = roots[i4]; uint32Array2 = new Uint32Array(buffer2); uint16Array2 = new Uint16Array(buffer2); float32Array2 = new Float32Array(buffer2); _traverse2(0, byteOffset); byteOffset += buffer2.byteLength; } function _traverse2(node32Index, byteOffset2, force = false) { const node16Index = node32Index * 2; const isLeaf = uint16Array2[node16Index + 15] === IS_LEAFNODE_FLAG; if (isLeaf) { const offset = uint32Array2[node32Index + 6]; const count = uint16Array2[node16Index + 14]; let minx = Infinity; let miny = Infinity; let minz = Infinity; let maxx = -Infinity; let maxy = -Infinity; let maxz = -Infinity; for (let i4 = offset, l2 = offset + count; i4 < l2; i4++) { const t3 = 3 * bvh.resolveTriangleIndex(i4); for (let j = 0; j < 3; j++) { let index2 = t3 + j; index2 = indexArr ? indexArr[index2] : index2; const x = posAttr.getX(index2); const y = posAttr.getY(index2); const z = posAttr.getZ(index2); if (x < minx) minx = x; if (x > maxx) maxx = x; if (y < miny) miny = y; if (y > maxy) maxy = y; if (z < minz) minz = z; if (z > maxz) maxz = z; } } if (float32Array2[node32Index + 0] !== minx || float32Array2[node32Index + 1] !== miny || float32Array2[node32Index + 2] !== minz || float32Array2[node32Index + 3] !== maxx || float32Array2[node32Index + 4] !== maxy || float32Array2[node32Index + 5] !== maxz) { float32Array2[node32Index + 0] = minx; float32Array2[node32Index + 1] = miny; float32Array2[node32Index + 2] = minz; float32Array2[node32Index + 3] = maxx; float32Array2[node32Index + 4] = maxy; float32Array2[node32Index + 5] = maxz; return true; } else { return false; } } else { const left = node32Index + 8; const right = uint32Array2[node32Index + 6]; const offsetLeft = left + byteOffset2; const offsetRight = right + byteOffset2; let forceChildren = force; let includesLeft = false; let includesRight = false; if (nodeIndices) { if (!forceChildren) { includesLeft = nodeIndices.has(offsetLeft); includesRight = nodeIndices.has(offsetRight); forceChildren = !includesLeft && !includesRight; } } else { includesLeft = true; includesRight = true; } const traverseLeft = forceChildren || includesLeft; const traverseRight = forceChildren || includesRight; let leftChange = false; if (traverseLeft) { leftChange = _traverse2(left, byteOffset2, forceChildren); } let rightChange = false; if (traverseRight) { rightChange = _traverse2(right, byteOffset2, forceChildren); } const didChange = leftChange || rightChange; if (didChange) { for (let i4 = 0; i4 < 3; i4++) { const lefti = left + i4; const righti = right + i4; const minLeftValue = float32Array2[lefti]; const maxLeftValue = float32Array2[lefti + 3]; const minRightValue = float32Array2[righti]; const maxRightValue = float32Array2[righti + 3]; float32Array2[node32Index + i4] = minLeftValue < minRightValue ? minLeftValue : minRightValue; float32Array2[node32Index + i4 + 3] = maxLeftValue > maxRightValue ? maxLeftValue : maxRightValue; } } return didChange; } } } // node_modules/three-mesh-bvh/src/core/cast/raycast_indirect.generated.js function raycast_indirect(bvh, root, side, ray4, intersects, near, far) { BufferStack.setBuffer(bvh._roots[root]); _raycast2(0, bvh, side, ray4, intersects, near, far); BufferStack.clearBuffer(); } function _raycast2(nodeIndex32, bvh, side, ray4, intersects, near, far) { const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack; const nodeIndex16 = nodeIndex32 * 2; const isLeaf = IS_LEAF(nodeIndex16, uint16Array2); if (isLeaf) { const offset = OFFSET(nodeIndex32, uint32Array2); const count = COUNT(nodeIndex16, uint16Array2); intersectTris_indirect(bvh, side, ray4, offset, count, intersects, near, far); } else { const leftIndex = LEFT_NODE(nodeIndex32); if (intersectRay(leftIndex, float32Array2, ray4, near, far)) { _raycast2(leftIndex, bvh, side, ray4, intersects, near, far); } const rightIndex = RIGHT_NODE(nodeIndex32, uint32Array2); if (intersectRay(rightIndex, float32Array2, ray4, near, far)) { _raycast2(rightIndex, bvh, side, ray4, intersects, near, far); } } } // node_modules/three-mesh-bvh/src/core/cast/raycastFirst_indirect.generated.js var _xyzFields2 = ["x", "y", "z"]; function raycastFirst_indirect(bvh, root, side, ray4, near, far) { BufferStack.setBuffer(bvh._roots[root]); const result = _raycastFirst2(0, bvh, side, ray4, near, far); BufferStack.clearBuffer(); return result; } function _raycastFirst2(nodeIndex32, bvh, side, ray4, near, far) { const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack; let nodeIndex16 = nodeIndex32 * 2; const isLeaf = IS_LEAF(nodeIndex16, uint16Array2); if (isLeaf) { const offset = OFFSET(nodeIndex32, uint32Array2); const count = COUNT(nodeIndex16, uint16Array2); return intersectClosestTri_indirect(bvh, side, ray4, offset, count, near, far); } else { const splitAxis = SPLIT_AXIS(nodeIndex32, uint32Array2); const xyzAxis = _xyzFields2[splitAxis]; const rayDir = ray4.direction[xyzAxis]; const leftToRight = rayDir >= 0; let c1, c2; if (leftToRight) { c1 = LEFT_NODE(nodeIndex32); c2 = RIGHT_NODE(nodeIndex32, uint32Array2); } else { c1 = RIGHT_NODE(nodeIndex32, uint32Array2); c2 = LEFT_NODE(nodeIndex32); } const c1Intersection = intersectRay(c1, float32Array2, ray4, near, far); const c1Result = c1Intersection ? _raycastFirst2(c1, bvh, side, ray4, near, far) : null; if (c1Result) { const point = c1Result.point[xyzAxis]; const isOutside = leftToRight ? point <= float32Array2[c2 + splitAxis] : ( // min bounding data point >= float32Array2[c2 + splitAxis + 3] ); if (isOutside) { return c1Result; } } const c2Intersection = intersectRay(c2, float32Array2, ray4, near, far); const c2Result = c2Intersection ? _raycastFirst2(c2, bvh, side, ray4, near, far) : null; if (c1Result && c2Result) { return c1Result.distance <= c2Result.distance ? c1Result : c2Result; } else { return c1Result || c2Result || null; } } } // node_modules/three-mesh-bvh/src/core/cast/intersectsGeometry_indirect.generated.js var boundingBox2 = new Box3(); var triangle3 = new ExtendedTriangle(); var triangle23 = new ExtendedTriangle(); var invertedMat2 = new Matrix4(); var obb4 = new OrientedBox(); var obb24 = new OrientedBox(); function intersectsGeometry_indirect(bvh, root, otherGeometry, geometryToBvh) { BufferStack.setBuffer(bvh._roots[root]); const result = _intersectsGeometry2(0, bvh, otherGeometry, geometryToBvh); BufferStack.clearBuffer(); return result; } function _intersectsGeometry2(nodeIndex32, bvh, otherGeometry, geometryToBvh, cachedObb = null) { const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack; let nodeIndex16 = nodeIndex32 * 2; if (cachedObb === null) { if (!otherGeometry.boundingBox) { otherGeometry.computeBoundingBox(); } obb4.set(otherGeometry.boundingBox.min, otherGeometry.boundingBox.max, geometryToBvh); cachedObb = obb4; } const isLeaf = IS_LEAF(nodeIndex16, uint16Array2); if (isLeaf) { const thisGeometry = bvh.geometry; const thisIndex = thisGeometry.index; const thisPos = thisGeometry.attributes.position; const index2 = otherGeometry.index; const pos = otherGeometry.attributes.position; const offset = OFFSET(nodeIndex32, uint32Array2); const count = COUNT(nodeIndex16, uint16Array2); invertedMat2.copy(geometryToBvh).invert(); if (otherGeometry.boundsTree) { arrayToBox(BOUNDING_DATA_INDEX(nodeIndex32), float32Array2, obb24); obb24.matrix.copy(invertedMat2); obb24.needsUpdate = true; const res = otherGeometry.boundsTree.shapecast({ intersectsBounds: (box) => obb24.intersectsBox(box), intersectsTriangle: (tri) => { tri.a.applyMatrix4(geometryToBvh); tri.b.applyMatrix4(geometryToBvh); tri.c.applyMatrix4(geometryToBvh); tri.needsUpdate = true; for (let i4 = offset, l2 = count + offset; i4 < l2; i4++) { setTriangle(triangle23, 3 * bvh.resolveTriangleIndex(i4), thisIndex, thisPos); triangle23.needsUpdate = true; if (tri.intersectsTriangle(triangle23)) { return true; } } return false; } }); return res; } else { for (let i4 = offset, l2 = count + offset; i4 < l2; i4++) { const ti = bvh.resolveTriangleIndex(i4); setTriangle(triangle3, 3 * ti, thisIndex, thisPos); triangle3.a.applyMatrix4(invertedMat2); triangle3.b.applyMatrix4(invertedMat2); triangle3.c.applyMatrix4(invertedMat2); triangle3.needsUpdate = true; for (let i22 = 0, l22 = index2.count; i22 < l22; i22 += 3) { setTriangle(triangle23, i22, index2, pos); triangle23.needsUpdate = true; if (triangle3.intersectsTriangle(triangle23)) { return true; } } } } } else { const left = nodeIndex32 + 8; const right = uint32Array2[nodeIndex32 + 6]; arrayToBox(BOUNDING_DATA_INDEX(left), float32Array2, boundingBox2); const leftIntersection = cachedObb.intersectsBox(boundingBox2) && _intersectsGeometry2(left, bvh, otherGeometry, geometryToBvh, cachedObb); if (leftIntersection) return true; arrayToBox(BOUNDING_DATA_INDEX(right), float32Array2, boundingBox2); const rightIntersection = cachedObb.intersectsBox(boundingBox2) && _intersectsGeometry2(right, bvh, otherGeometry, geometryToBvh, cachedObb); if (rightIntersection) return true; return false; } } // node_modules/three-mesh-bvh/src/core/cast/closestPointToGeometry_indirect.generated.js var tempMatrix2 = new Matrix4(); var obb5 = new OrientedBox(); var obb25 = new OrientedBox(); var temp13 = new Vector3(); var temp22 = new Vector3(); var temp32 = new Vector3(); var temp42 = new Vector3(); function closestPointToGeometry_indirect(bvh, otherGeometry, geometryToBvh, target1 = {}, target2 = {}, minThreshold = 0, maxThreshold = Infinity) { if (!otherGeometry.boundingBox) { otherGeometry.computeBoundingBox(); } obb5.set(otherGeometry.boundingBox.min, otherGeometry.boundingBox.max, geometryToBvh); obb5.needsUpdate = true; const geometry3 = bvh.geometry; const pos = geometry3.attributes.position; const index2 = geometry3.index; const otherPos = otherGeometry.attributes.position; const otherIndex = otherGeometry.index; const triangle4 = ExtendedTrianglePool.getPrimitive(); const triangle24 = ExtendedTrianglePool.getPrimitive(); let tempTarget1 = temp13; let tempTargetDest1 = temp22; let tempTarget2 = null; let tempTargetDest2 = null; if (target2) { tempTarget2 = temp32; tempTargetDest2 = temp42; } let closestDistance = Infinity; let closestDistanceTriIndex = null; let closestDistanceOtherTriIndex = null; tempMatrix2.copy(geometryToBvh).invert(); obb25.matrix.copy(tempMatrix2); bvh.shapecast( { boundsTraverseOrder: (box) => { return obb5.distanceToBox(box); }, intersectsBounds: (box, isLeaf, score) => { if (score < closestDistance && score < maxThreshold) { if (isLeaf) { obb25.min.copy(box.min); obb25.max.copy(box.max); obb25.needsUpdate = true; } return true; } return false; }, intersectsRange: (offset, count) => { if (otherGeometry.boundsTree) { const otherBvh = otherGeometry.boundsTree; return otherBvh.shapecast({ boundsTraverseOrder: (box) => { return obb25.distanceToBox(box); }, intersectsBounds: (box, isLeaf, score) => { return score < closestDistance && score < maxThreshold; }, intersectsRange: (otherOffset, otherCount) => { for (let i22 = otherOffset, l2 = otherOffset + otherCount; i22 < l2; i22++) { const ti2 = otherBvh.resolveTriangleIndex(i22); setTriangle(triangle24, 3 * ti2, otherIndex, otherPos); triangle24.a.applyMatrix4(geometryToBvh); triangle24.b.applyMatrix4(geometryToBvh); triangle24.c.applyMatrix4(geometryToBvh); triangle24.needsUpdate = true; for (let i4 = offset, l3 = offset + count; i4 < l3; i4++) { const ti = bvh.resolveTriangleIndex(i4); setTriangle(triangle4, 3 * ti, index2, pos); triangle4.needsUpdate = true; const dist = triangle4.distanceToTriangle(triangle24, tempTarget1, tempTarget2); if (dist < closestDistance) { tempTargetDest1.copy(tempTarget1); if (tempTargetDest2) { tempTargetDest2.copy(tempTarget2); } closestDistance = dist; closestDistanceTriIndex = i4; closestDistanceOtherTriIndex = i22; } if (dist < minThreshold) { return true; } } } } }); } else { const triCount = getTriCount(otherGeometry); for (let i22 = 0, l2 = triCount; i22 < l2; i22++) { setTriangle(triangle24, 3 * i22, otherIndex, otherPos); triangle24.a.applyMatrix4(geometryToBvh); triangle24.b.applyMatrix4(geometryToBvh); triangle24.c.applyMatrix4(geometryToBvh); triangle24.needsUpdate = true; for (let i4 = offset, l3 = offset + count; i4 < l3; i4++) { const ti = bvh.resolveTriangleIndex(i4); setTriangle(triangle4, 3 * ti, index2, pos); triangle4.needsUpdate = true; const dist = triangle4.distanceToTriangle(triangle24, tempTarget1, tempTarget2); if (dist < closestDistance) { tempTargetDest1.copy(tempTarget1); if (tempTargetDest2) { tempTargetDest2.copy(tempTarget2); } closestDistance = dist; closestDistanceTriIndex = i4; closestDistanceOtherTriIndex = i22; } if (dist < minThreshold) { return true; } } } } } } ); ExtendedTrianglePool.releasePrimitive(triangle4); ExtendedTrianglePool.releasePrimitive(triangle24); if (closestDistance === Infinity) { return null; } if (!target1.point) { target1.point = tempTargetDest1.clone(); } else { target1.point.copy(tempTargetDest1); } target1.distance = closestDistance, target1.faceIndex = closestDistanceTriIndex; if (target2) { if (!target2.point) target2.point = tempTargetDest2.clone(); else target2.point.copy(tempTargetDest2); target2.point.applyMatrix4(tempMatrix2); tempTargetDest1.applyMatrix4(tempMatrix2); target2.distance = tempTargetDest1.sub(target2.point).length(); target2.faceIndex = closestDistanceOtherTriIndex; } return target1; } // node_modules/three-mesh-bvh/src/utils/BufferUtils.js function isSharedArrayBufferSupported() { return typeof SharedArrayBuffer !== "undefined"; } // node_modules/three-mesh-bvh/src/core/cast/bvhcast.js var _bufferStack1 = new BufferStack.constructor(); var _bufferStack2 = new BufferStack.constructor(); var _boxPool = new PrimitivePool(() => new Box3()); var _leftBox1 = new Box3(); var _rightBox1 = new Box3(); var _leftBox2 = new Box3(); var _rightBox2 = new Box3(); var _active = false; function bvhcast(bvh, otherBvh, matrixToLocal, intersectsRanges) { if (_active) { throw new Error("MeshBVH: Recursive calls to bvhcast not supported."); } _active = true; const roots = bvh._roots; const otherRoots = otherBvh._roots; let result; let offset1 = 0; let offset2 = 0; const invMat = new Matrix4().copy(matrixToLocal).invert(); for (let i4 = 0, il = roots.length; i4 < il; i4++) { _bufferStack1.setBuffer(roots[i4]); offset2 = 0; const localBox = _boxPool.getPrimitive(); arrayToBox(BOUNDING_DATA_INDEX(0), _bufferStack1.float32Array, localBox); localBox.applyMatrix4(invMat); for (let j = 0, jl = otherRoots.length; j < jl; j++) { _bufferStack2.setBuffer(otherRoots[j]); result = _traverse( 0, 0, matrixToLocal, invMat, intersectsRanges, offset1, offset2, 0, 0, localBox ); _bufferStack2.clearBuffer(); offset2 += otherRoots[j].length; if (result) { break; } } _boxPool.releasePrimitive(localBox); _bufferStack1.clearBuffer(); offset1 += roots[i4].length; if (result) { break; } } _active = false; return result; } function _traverse(node1Index32, node2Index32, matrix2to1, matrix1to2, intersectsRangesFunc, node1IndexByteOffset = 0, node2IndexByteOffset = 0, depth1 = 0, depth2 = 0, currBox = null, reversed = false) { let bufferStack1, bufferStack2; if (reversed) { bufferStack1 = _bufferStack2; bufferStack2 = _bufferStack1; } else { bufferStack1 = _bufferStack1; bufferStack2 = _bufferStack2; } const float32Array1 = bufferStack1.float32Array, uint32Array1 = bufferStack1.uint32Array, uint16Array1 = bufferStack1.uint16Array, float32Array2 = bufferStack2.float32Array, uint32Array2 = bufferStack2.uint32Array, uint16Array2 = bufferStack2.uint16Array; const node1Index16 = node1Index32 * 2; const node2Index16 = node2Index32 * 2; const isLeaf1 = IS_LEAF(node1Index16, uint16Array1); const isLeaf2 = IS_LEAF(node2Index16, uint16Array2); let result = false; if (isLeaf2 && isLeaf1) { if (reversed) { result = intersectsRangesFunc( OFFSET(node2Index32, uint32Array2), COUNT(node2Index32 * 2, uint16Array2), OFFSET(node1Index32, uint32Array1), COUNT(node1Index32 * 2, uint16Array1), depth2, node2IndexByteOffset + node2Index32, depth1, node1IndexByteOffset + node1Index32 ); } else { result = intersectsRangesFunc( OFFSET(node1Index32, uint32Array1), COUNT(node1Index32 * 2, uint16Array1), OFFSET(node2Index32, uint32Array2), COUNT(node2Index32 * 2, uint16Array2), depth1, node1IndexByteOffset + node1Index32, depth2, node2IndexByteOffset + node2Index32 ); } } else if (isLeaf2) { const newBox = _boxPool.getPrimitive(); arrayToBox(BOUNDING_DATA_INDEX(node2Index32), float32Array2, newBox); newBox.applyMatrix4(matrix2to1); const cl1 = LEFT_NODE(node1Index32); const cr1 = RIGHT_NODE(node1Index32, uint32Array1); arrayToBox(BOUNDING_DATA_INDEX(cl1), float32Array1, _leftBox1); arrayToBox(BOUNDING_DATA_INDEX(cr1), float32Array1, _rightBox1); const intersectCl1 = newBox.intersectsBox(_leftBox1); const intersectCr1 = newBox.intersectsBox(_rightBox1); result = intersectCl1 && _traverse( node2Index32, cl1, matrix1to2, matrix2to1, intersectsRangesFunc, node2IndexByteOffset, node1IndexByteOffset, depth2, depth1 + 1, newBox, !reversed ) || intersectCr1 && _traverse( node2Index32, cr1, matrix1to2, matrix2to1, intersectsRangesFunc, node2IndexByteOffset, node1IndexByteOffset, depth2, depth1 + 1, newBox, !reversed ); _boxPool.releasePrimitive(newBox); } else { const cl2 = LEFT_NODE(node2Index32); const cr2 = RIGHT_NODE(node2Index32, uint32Array2); arrayToBox(BOUNDING_DATA_INDEX(cl2), float32Array2, _leftBox2); arrayToBox(BOUNDING_DATA_INDEX(cr2), float32Array2, _rightBox2); const leftIntersects = currBox.intersectsBox(_leftBox2); const rightIntersects = currBox.intersectsBox(_rightBox2); if (leftIntersects && rightIntersects) { result = _traverse( node1Index32, cl2, matrix2to1, matrix1to2, intersectsRangesFunc, node1IndexByteOffset, node2IndexByteOffset, depth1, depth2 + 1, currBox, reversed ) || _traverse( node1Index32, cr2, matrix2to1, matrix1to2, intersectsRangesFunc, node1IndexByteOffset, node2IndexByteOffset, depth1, depth2 + 1, currBox, reversed ); } else if (leftIntersects) { if (isLeaf1) { result = _traverse( node1Index32, cl2, matrix2to1, matrix1to2, intersectsRangesFunc, node1IndexByteOffset, node2IndexByteOffset, depth1, depth2 + 1, currBox, reversed ); } else { const newBox = _boxPool.getPrimitive(); newBox.copy(_leftBox2).applyMatrix4(matrix2to1); const cl1 = LEFT_NODE(node1Index32); const cr1 = RIGHT_NODE(node1Index32, uint32Array1); arrayToBox(BOUNDING_DATA_INDEX(cl1), float32Array1, _leftBox1); arrayToBox(BOUNDING_DATA_INDEX(cr1), float32Array1, _rightBox1); const intersectCl1 = newBox.intersectsBox(_leftBox1); const intersectCr1 = newBox.intersectsBox(_rightBox1); result = intersectCl1 && _traverse( cl2, cl1, matrix1to2, matrix2to1, intersectsRangesFunc, node2IndexByteOffset, node1IndexByteOffset, depth2, depth1 + 1, newBox, !reversed ) || intersectCr1 && _traverse( cl2, cr1, matrix1to2, matrix2to1, intersectsRangesFunc, node2IndexByteOffset, node1IndexByteOffset, depth2, depth1 + 1, newBox, !reversed ); _boxPool.releasePrimitive(newBox); } } else if (rightIntersects) { if (isLeaf1) { result = _traverse( node1Index32, cr2, matrix2to1, matrix1to2, intersectsRangesFunc, node1IndexByteOffset, node2IndexByteOffset, depth1, depth2 + 1, currBox, reversed ); } else { const newBox = _boxPool.getPrimitive(); newBox.copy(_rightBox2).applyMatrix4(matrix2to1); const cl1 = LEFT_NODE(node1Index32); const cr1 = RIGHT_NODE(node1Index32, uint32Array1); arrayToBox(BOUNDING_DATA_INDEX(cl1), float32Array1, _leftBox1); arrayToBox(BOUNDING_DATA_INDEX(cr1), float32Array1, _rightBox1); const intersectCl1 = newBox.intersectsBox(_leftBox1); const intersectCr1 = newBox.intersectsBox(_rightBox1); result = intersectCl1 && _traverse( cr2, cl1, matrix1to2, matrix2to1, intersectsRangesFunc, node2IndexByteOffset, node1IndexByteOffset, depth2, depth1 + 1, newBox, !reversed ) || intersectCr1 && _traverse( cr2, cr1, matrix1to2, matrix2to1, intersectsRangesFunc, node2IndexByteOffset, node1IndexByteOffset, depth2, depth1 + 1, newBox, !reversed ); _boxPool.releasePrimitive(newBox); } } } return result; } // node_modules/three-mesh-bvh/src/core/MeshBVH.js var obb6 = new OrientedBox(); var tempBox = new Box3(); var DEFAULT_OPTIONS = { strategy: CENTER, maxDepth: 40, maxLeafTris: 10, useSharedArrayBuffer: false, setBoundingBox: true, onProgress: null, indirect: false, verbose: true, range: null }; var MeshBVH = class _MeshBVH { static serialize(bvh, options = {}) { options = { cloneBuffers: true, ...options }; const geometry3 = bvh.geometry; const rootData = bvh._roots; const indirectBuffer = bvh._indirectBuffer; const indexAttribute = geometry3.getIndex(); let result; if (options.cloneBuffers) { result = { roots: rootData.map((root) => root.slice()), index: indexAttribute ? indexAttribute.array.slice() : null, indirectBuffer: indirectBuffer ? indirectBuffer.slice() : null }; } else { result = { roots: rootData, index: indexAttribute ? indexAttribute.array : null, indirectBuffer }; } return result; } static deserialize(data, geometry3, options = {}) { options = { setIndex: true, indirect: Boolean(data.indirectBuffer), ...options }; const { index: index2, roots, indirectBuffer } = data; const bvh = new _MeshBVH(geometry3, { ...options, [SKIP_GENERATION]: true }); bvh._roots = roots; bvh._indirectBuffer = indirectBuffer || null; if (options.setIndex) { const indexAttribute = geometry3.getIndex(); if (indexAttribute === null) { const newIndex = new BufferAttribute(data.index, 1, false); geometry3.setIndex(newIndex); } else if (indexAttribute.array !== index2) { indexAttribute.array.set(index2); indexAttribute.needsUpdate = true; } } return bvh; } get indirect() { return !!this._indirectBuffer; } constructor(geometry3, options = {}) { if (!geometry3.isBufferGeometry) { throw new Error("MeshBVH: Only BufferGeometries are supported."); } else if (geometry3.index && geometry3.index.isInterleavedBufferAttribute) { throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute."); } options = Object.assign({ ...DEFAULT_OPTIONS, // undocumented options // Whether to skip generating the tree. Used for deserialization. [SKIP_GENERATION]: false }, options); if (options.useSharedArrayBuffer && !isSharedArrayBufferSupported()) { throw new Error("MeshBVH: SharedArrayBuffer is not available."); } this.geometry = geometry3; this._roots = null; this._indirectBuffer = null; if (!options[SKIP_GENERATION]) { buildPackedTree(this, options); if (!geometry3.boundingBox && options.setBoundingBox) { geometry3.boundingBox = this.getBoundingBox(new Box3()); } } this.resolveTriangleIndex = options.indirect ? (i4) => this._indirectBuffer[i4] : (i4) => i4; } refit(nodeIndices = null) { const refitFunc = this.indirect ? refit_indirect : refit; return refitFunc(this, nodeIndices); } traverse(callback, rootIndex = 0) { const buffer2 = this._roots[rootIndex]; const uint32Array2 = new Uint32Array(buffer2); const uint16Array2 = new Uint16Array(buffer2); _traverse2(0); function _traverse2(node32Index, depth = 0) { const node16Index = node32Index * 2; const isLeaf = uint16Array2[node16Index + 15] === IS_LEAFNODE_FLAG; if (isLeaf) { const offset = uint32Array2[node32Index + 6]; const count = uint16Array2[node16Index + 14]; callback(depth, isLeaf, new Float32Array(buffer2, node32Index * 4, 6), offset, count); } else { const left = node32Index + BYTES_PER_NODE / 4; const right = uint32Array2[node32Index + 6]; const splitAxis = uint32Array2[node32Index + 7]; const stopTraversal = callback(depth, isLeaf, new Float32Array(buffer2, node32Index * 4, 6), splitAxis); if (!stopTraversal) { _traverse2(left, depth + 1); _traverse2(right, depth + 1); } } } } /* Core Cast Functions */ raycast(ray4, materialOrSide = FrontSide, near = 0, far = Infinity) { const roots = this._roots; const geometry3 = this.geometry; const intersects = []; const isMaterial = materialOrSide.isMaterial; const isArrayMaterial = Array.isArray(materialOrSide); const groups = geometry3.groups; const side = isMaterial ? materialOrSide.side : materialOrSide; const raycastFunc = this.indirect ? raycast_indirect : raycast; for (let i4 = 0, l2 = roots.length; i4 < l2; i4++) { const materialSide = isArrayMaterial ? materialOrSide[groups[i4].materialIndex].side : side; const startCount = intersects.length; raycastFunc(this, i4, materialSide, ray4, intersects, near, far); if (isArrayMaterial) { const materialIndex = groups[i4].materialIndex; for (let j = startCount, jl = intersects.length; j < jl; j++) { intersects[j].face.materialIndex = materialIndex; } } } return intersects; } raycastFirst(ray4, materialOrSide = FrontSide, near = 0, far = Infinity) { const roots = this._roots; const geometry3 = this.geometry; const isMaterial = materialOrSide.isMaterial; const isArrayMaterial = Array.isArray(materialOrSide); let closestResult = null; const groups = geometry3.groups; const side = isMaterial ? materialOrSide.side : materialOrSide; const raycastFirstFunc = this.indirect ? raycastFirst_indirect : raycastFirst; for (let i4 = 0, l2 = roots.length; i4 < l2; i4++) { const materialSide = isArrayMaterial ? materialOrSide[groups[i4].materialIndex].side : side; const result = raycastFirstFunc(this, i4, materialSide, ray4, near, far); if (result != null && (closestResult == null || result.distance < closestResult.distance)) { closestResult = result; if (isArrayMaterial) { result.face.materialIndex = groups[i4].materialIndex; } } } return closestResult; } intersectsGeometry(otherGeometry, geomToMesh) { let result = false; const roots = this._roots; const intersectsGeometryFunc = this.indirect ? intersectsGeometry_indirect : intersectsGeometry; for (let i4 = 0, l2 = roots.length; i4 < l2; i4++) { result = intersectsGeometryFunc(this, i4, otherGeometry, geomToMesh); if (result) { break; } } return result; } shapecast(callbacks) { const triangle4 = ExtendedTrianglePool.getPrimitive(); const iterateFunc = this.indirect ? iterateOverTriangles_indirect : iterateOverTriangles; let { boundsTraverseOrder, intersectsBounds, intersectsRange, intersectsTriangle } = callbacks; if (intersectsRange && intersectsTriangle) { const originalIntersectsRange = intersectsRange; intersectsRange = (offset, count, contained, depth, nodeIndex) => { if (!originalIntersectsRange(offset, count, contained, depth, nodeIndex)) { return iterateFunc(offset, count, this, intersectsTriangle, contained, depth, triangle4); } return true; }; } else if (!intersectsRange) { if (intersectsTriangle) { intersectsRange = (offset, count, contained, depth) => { return iterateFunc(offset, count, this, intersectsTriangle, contained, depth, triangle4); }; } else { intersectsRange = (offset, count, contained) => { return contained; }; } } let result = false; let byteOffset = 0; const roots = this._roots; for (let i4 = 0, l2 = roots.length; i4 < l2; i4++) { const root = roots[i4]; result = shapecast(this, i4, intersectsBounds, intersectsRange, boundsTraverseOrder, byteOffset); if (result) { break; } byteOffset += root.byteLength; } ExtendedTrianglePool.releasePrimitive(triangle4); return result; } bvhcast(otherBvh, matrixToLocal, callbacks) { let { intersectsRanges, intersectsTriangles } = callbacks; const triangle1 = ExtendedTrianglePool.getPrimitive(); const indexAttr1 = this.geometry.index; const positionAttr1 = this.geometry.attributes.position; const assignTriangle1 = this.indirect ? (i1) => { const ti = this.resolveTriangleIndex(i1); setTriangle(triangle1, ti * 3, indexAttr1, positionAttr1); } : (i1) => { setTriangle(triangle1, i1 * 3, indexAttr1, positionAttr1); }; const triangle24 = ExtendedTrianglePool.getPrimitive(); const indexAttr2 = otherBvh.geometry.index; const positionAttr2 = otherBvh.geometry.attributes.position; const assignTriangle2 = otherBvh.indirect ? (i22) => { const ti2 = otherBvh.resolveTriangleIndex(i22); setTriangle(triangle24, ti2 * 3, indexAttr2, positionAttr2); } : (i22) => { setTriangle(triangle24, i22 * 3, indexAttr2, positionAttr2); }; if (intersectsTriangles) { const iterateOverDoubleTriangles = (offset1, count1, offset2, count2, depth1, index1, depth2, index2) => { for (let i22 = offset2, l2 = offset2 + count2; i22 < l2; i22++) { assignTriangle2(i22); triangle24.a.applyMatrix4(matrixToLocal); triangle24.b.applyMatrix4(matrixToLocal); triangle24.c.applyMatrix4(matrixToLocal); triangle24.needsUpdate = true; for (let i1 = offset1, l1 = offset1 + count1; i1 < l1; i1++) { assignTriangle1(i1); triangle1.needsUpdate = true; if (intersectsTriangles(triangle1, triangle24, i1, i22, depth1, index1, depth2, index2)) { return true; } } } return false; }; if (intersectsRanges) { const originalIntersectsRanges = intersectsRanges; intersectsRanges = function(offset1, count1, offset2, count2, depth1, index1, depth2, index2) { if (!originalIntersectsRanges(offset1, count1, offset2, count2, depth1, index1, depth2, index2)) { return iterateOverDoubleTriangles(offset1, count1, offset2, count2, depth1, index1, depth2, index2); } return true; }; } else { intersectsRanges = iterateOverDoubleTriangles; } } return bvhcast(this, otherBvh, matrixToLocal, intersectsRanges); } /* Derived Cast Functions */ intersectsBox(box, boxToMesh) { obb6.set(box.min, box.max, boxToMesh); obb6.needsUpdate = true; return this.shapecast( { intersectsBounds: (box2) => obb6.intersectsBox(box2), intersectsTriangle: (tri) => obb6.intersectsTriangle(tri) } ); } intersectsSphere(sphere) { return this.shapecast( { intersectsBounds: (box) => sphere.intersectsBox(box), intersectsTriangle: (tri) => tri.intersectsSphere(sphere) } ); } closestPointToGeometry(otherGeometry, geometryToBvh, target1 = {}, target2 = {}, minThreshold = 0, maxThreshold = Infinity) { const closestPointToGeometryFunc = this.indirect ? closestPointToGeometry_indirect : closestPointToGeometry; return closestPointToGeometryFunc( this, otherGeometry, geometryToBvh, target1, target2, minThreshold, maxThreshold ); } closestPointToPoint(point, target2 = {}, minThreshold = 0, maxThreshold = Infinity) { return closestPointToPoint( this, point, target2, minThreshold, maxThreshold ); } getBoundingBox(target2) { target2.makeEmpty(); const roots = this._roots; roots.forEach((buffer2) => { arrayToBox(0, new Float32Array(buffer2), tempBox); target2.union(tempBox); }); return target2; } }; // node_modules/three-mesh-bvh/src/objects/MeshBVHHelper.js var boundingBox3 = new Box3(); var matrix5 = new Matrix4(); // node_modules/three-mesh-bvh/src/debug/Debug.js var _box12 = new Box3(); var _box23 = new Box3(); var _vec = new Vector3(); // node_modules/three-mesh-bvh/src/utils/GeometryRayIntersectUtilities.js function convertRaycastIntersect(hit, object, raycaster) { if (hit === null) { return null; } hit.point.applyMatrix4(object.matrixWorld); hit.distance = hit.point.distanceTo(raycaster.ray.origin); hit.object = object; return hit; } // node_modules/three-mesh-bvh/src/utils/ExtensionUtilities.js var IS_REVISION_166 = parseInt(REVISION) >= 166; var ray = new Ray(); var direction = new Vector3(); var tmpInverseMatrix = new Matrix4(); var origMeshRaycastFunc = Mesh.prototype.raycast; var origBatchedRaycastFunc = BatchedMesh.prototype.raycast; var _worldScale = new Vector3(); var _mesh2 = new Mesh(); var _batchIntersects = []; function acceleratedRaycast(raycaster, intersects) { if (this.isBatchedMesh) { acceleratedBatchedMeshRaycast.call(this, raycaster, intersects); } else { acceleratedMeshRaycast.call(this, raycaster, intersects); } } function acceleratedBatchedMeshRaycast(raycaster, intersects) { if (this.boundsTrees) { const boundsTrees = this.boundsTrees; const drawInfo = this._drawInfo || this._instanceInfo; const drawRanges = this._drawRanges || this._geometryInfo; const matrixWorld = this.matrixWorld; _mesh2.material = this.material; _mesh2.geometry = this.geometry; const oldBoundsTree = _mesh2.geometry.boundsTree; const oldDrawRange = _mesh2.geometry.drawRange; if (_mesh2.geometry.boundingSphere === null) { _mesh2.geometry.boundingSphere = new Sphere(); } for (let i4 = 0, l2 = drawInfo.length; i4 < l2; i4++) { if (!this.getVisibleAt(i4)) { continue; } const geometryId = drawInfo[i4].geometryIndex; _mesh2.geometry.boundsTree = boundsTrees[geometryId]; this.getMatrixAt(i4, _mesh2.matrixWorld).premultiply(matrixWorld); if (!_mesh2.geometry.boundsTree) { this.getBoundingBoxAt(geometryId, _mesh2.geometry.boundingBox); this.getBoundingSphereAt(geometryId, _mesh2.geometry.boundingSphere); const drawRange = drawRanges[geometryId]; _mesh2.geometry.setDrawRange(drawRange.start, drawRange.count); } _mesh2.raycast(raycaster, _batchIntersects); for (let j = 0, l3 = _batchIntersects.length; j < l3; j++) { const intersect = _batchIntersects[j]; intersect.object = this; intersect.batchId = i4; intersects.push(intersect); } _batchIntersects.length = 0; } _mesh2.geometry.boundsTree = oldBoundsTree; _mesh2.geometry.drawRange = oldDrawRange; _mesh2.material = null; _mesh2.geometry = null; } else { origBatchedRaycastFunc.call(this, raycaster, intersects); } } function acceleratedMeshRaycast(raycaster, intersects) { if (this.geometry.boundsTree) { if (this.material === void 0) return; tmpInverseMatrix.copy(this.matrixWorld).invert(); ray.copy(raycaster.ray).applyMatrix4(tmpInverseMatrix); _worldScale.setFromMatrixScale(this.matrixWorld); direction.copy(ray.direction).multiply(_worldScale); const scaleFactor = direction.length(); const near = raycaster.near / scaleFactor; const far = raycaster.far / scaleFactor; const bvh = this.geometry.boundsTree; if (raycaster.firstHitOnly === true) { const hit = convertRaycastIntersect(bvh.raycastFirst(ray, this.material, near, far), this, raycaster); if (hit) { intersects.push(hit); } } else { const hits = bvh.raycast(ray, this.material, near, far); for (let i4 = 0, l2 = hits.length; i4 < l2; i4++) { const hit = convertRaycastIntersect(hits[i4], this, raycaster); if (hit) { intersects.push(hit); } } } } else { origMeshRaycastFunc.call(this, raycaster, intersects); } } function computeBoundsTree(options = {}) { this.boundsTree = new MeshBVH(this, options); return this.boundsTree; } function disposeBoundsTree() { this.boundsTree = null; } // node_modules/three-mesh-bvh/src/gpu/VertexAttributeTexture.js function countToStringFormat(count) { switch (count) { case 1: return "R"; case 2: return "RG"; case 3: return "RGBA"; case 4: return "RGBA"; } throw new Error(); } function countToFormat(count) { switch (count) { case 1: return RedFormat; case 2: return RGFormat; case 3: return RGBAFormat; case 4: return RGBAFormat; } } function countToIntFormat(count) { switch (count) { case 1: return RedIntegerFormat; case 2: return RGIntegerFormat; case 3: return RGBAIntegerFormat; case 4: return RGBAIntegerFormat; } } var VertexAttributeTexture = class extends DataTexture { constructor() { super(); this.minFilter = NearestFilter; this.magFilter = NearestFilter; this.generateMipmaps = false; this.overrideItemSize = null; this._forcedType = null; } updateFrom(attr) { const overrideItemSize = this.overrideItemSize; const originalItemSize = attr.itemSize; const originalCount = attr.count; if (overrideItemSize !== null) { if (originalItemSize * originalCount % overrideItemSize !== 0) { throw new Error("VertexAttributeTexture: overrideItemSize must divide evenly into buffer length."); } attr.itemSize = overrideItemSize; attr.count = originalCount * originalItemSize / overrideItemSize; } const itemSize = attr.itemSize; const count = attr.count; const normalized = attr.normalized; const originalBufferCons = attr.array.constructor; const byteCount = originalBufferCons.BYTES_PER_ELEMENT; let targetType = this._forcedType; let finalStride = itemSize; if (targetType === null) { switch (originalBufferCons) { case Float32Array: targetType = FloatType; break; case Uint8Array: case Uint16Array: case Uint32Array: targetType = UnsignedIntType; break; case Int8Array: case Int16Array: case Int32Array: targetType = IntType; break; } } let type, format, normalizeValue, targetBufferCons; let internalFormat = countToStringFormat(itemSize); switch (targetType) { case FloatType: normalizeValue = 1; format = countToFormat(itemSize); if (normalized && byteCount === 1) { targetBufferCons = originalBufferCons; internalFormat += "8"; if (originalBufferCons === Uint8Array) { type = UnsignedByteType; } else { type = ByteType; internalFormat += "_SNORM"; } } else { targetBufferCons = Float32Array; internalFormat += "32F"; type = FloatType; } break; case IntType: internalFormat += byteCount * 8 + "I"; normalizeValue = normalized ? Math.pow(2, originalBufferCons.BYTES_PER_ELEMENT * 8 - 1) : 1; format = countToIntFormat(itemSize); if (byteCount === 1) { targetBufferCons = Int8Array; type = ByteType; } else if (byteCount === 2) { targetBufferCons = Int16Array; type = ShortType; } else { targetBufferCons = Int32Array; type = IntType; } break; case UnsignedIntType: internalFormat += byteCount * 8 + "UI"; normalizeValue = normalized ? Math.pow(2, originalBufferCons.BYTES_PER_ELEMENT * 8 - 1) : 1; format = countToIntFormat(itemSize); if (byteCount === 1) { targetBufferCons = Uint8Array; type = UnsignedByteType; } else if (byteCount === 2) { targetBufferCons = Uint16Array; type = UnsignedShortType; } else { targetBufferCons = Uint32Array; type = UnsignedIntType; } break; } if (finalStride === 3 && (format === RGBAFormat || format === RGBAIntegerFormat)) { finalStride = 4; } const dimension = Math.ceil(Math.sqrt(count)) || 1; const length3 = finalStride * dimension * dimension; const dataArray2 = new targetBufferCons(length3); const originalNormalized = attr.normalized; attr.normalized = false; for (let i4 = 0; i4 < count; i4++) { const ii = finalStride * i4; dataArray2[ii] = attr.getX(i4) / normalizeValue; if (itemSize >= 2) { dataArray2[ii + 1] = attr.getY(i4) / normalizeValue; } if (itemSize >= 3) { dataArray2[ii + 2] = attr.getZ(i4) / normalizeValue; if (finalStride === 4) { dataArray2[ii + 3] = 1; } } if (itemSize >= 4) { dataArray2[ii + 3] = attr.getW(i4) / normalizeValue; } } attr.normalized = originalNormalized; this.internalFormat = internalFormat; this.format = format; this.type = type; this.image.width = dimension; this.image.height = dimension; this.image.data = dataArray2; this.needsUpdate = true; this.dispose(); attr.itemSize = originalItemSize; attr.count = originalCount; } }; var UIntVertexAttributeTexture = class extends VertexAttributeTexture { constructor() { super(); this._forcedType = UnsignedIntType; } }; var FloatVertexAttributeTexture = class extends VertexAttributeTexture { constructor() { super(); this._forcedType = FloatType; } }; // node_modules/three-mesh-bvh/src/gpu/MeshBVHUniformStruct.js var MeshBVHUniformStruct = class { constructor() { this.index = new UIntVertexAttributeTexture(); this.position = new FloatVertexAttributeTexture(); this.bvhBounds = new DataTexture(); this.bvhContents = new DataTexture(); this._cachedIndexAttr = null; this.index.overrideItemSize = 3; } updateFrom(bvh) { const { geometry: geometry3 } = bvh; bvhToTextures(bvh, this.bvhBounds, this.bvhContents); this.position.updateFrom(geometry3.attributes.position); if (bvh.indirect) { const indirectBuffer = bvh._indirectBuffer; if (this._cachedIndexAttr === null || this._cachedIndexAttr.count !== indirectBuffer.length) { if (geometry3.index) { this._cachedIndexAttr = geometry3.index.clone(); } else { const array = getIndexArray(getVertexCount(geometry3)); this._cachedIndexAttr = new BufferAttribute(array, 1, false); } } dereferenceIndex(geometry3, indirectBuffer, this._cachedIndexAttr); this.index.updateFrom(this._cachedIndexAttr); } else { this.index.updateFrom(geometry3.index); } } dispose() { const { index: index2, position: position2, bvhBounds, bvhContents } = this; if (index2) index2.dispose(); if (position2) position2.dispose(); if (bvhBounds) bvhBounds.dispose(); if (bvhContents) bvhContents.dispose(); } }; function dereferenceIndex(geometry3, indirectBuffer, target2) { const unpacked = target2.array; const indexArray = geometry3.index ? geometry3.index.array : null; for (let i4 = 0, l2 = indirectBuffer.length; i4 < l2; i4++) { const i32 = 3 * i4; const v32 = 3 * indirectBuffer[i4]; for (let c2 = 0; c2 < 3; c2++) { unpacked[i32 + c2] = indexArray ? indexArray[v32 + c2] : v32 + c2; } } } function bvhToTextures(bvh, boundsTexture, contentsTexture) { const roots = bvh._roots; if (roots.length !== 1) { throw new Error("MeshBVHUniformStruct: Multi-root BVHs not supported."); } const root = roots[0]; const uint16Array2 = new Uint16Array(root); const uint32Array2 = new Uint32Array(root); const float32Array2 = new Float32Array(root); const nodeCount = root.byteLength / BYTES_PER_NODE; const boundsDimension = 2 * Math.ceil(Math.sqrt(nodeCount / 2)); const boundsArray = new Float32Array(4 * boundsDimension * boundsDimension); const contentsDimension = Math.ceil(Math.sqrt(nodeCount)); const contentsArray = new Uint32Array(2 * contentsDimension * contentsDimension); for (let i4 = 0; i4 < nodeCount; i4++) { const nodeIndex32 = i4 * BYTES_PER_NODE / 4; const nodeIndex16 = nodeIndex32 * 2; const boundsIndex = BOUNDING_DATA_INDEX(nodeIndex32); for (let b5 = 0; b5 < 3; b5++) { boundsArray[8 * i4 + 0 + b5] = float32Array2[boundsIndex + 0 + b5]; boundsArray[8 * i4 + 4 + b5] = float32Array2[boundsIndex + 3 + b5]; } if (IS_LEAF(nodeIndex16, uint16Array2)) { const count = COUNT(nodeIndex16, uint16Array2); const offset = OFFSET(nodeIndex32, uint32Array2); const mergedLeafCount = 4294901760 | count; contentsArray[i4 * 2 + 0] = mergedLeafCount; contentsArray[i4 * 2 + 1] = offset; } else { const rightIndex = 4 * RIGHT_NODE(nodeIndex32, uint32Array2) / BYTES_PER_NODE; const splitAxis = SPLIT_AXIS(nodeIndex32, uint32Array2); contentsArray[i4 * 2 + 0] = splitAxis; contentsArray[i4 * 2 + 1] = rightIndex; } } boundsTexture.image.data = boundsArray; boundsTexture.image.width = boundsDimension; boundsTexture.image.height = boundsDimension; boundsTexture.format = RGBAFormat; boundsTexture.type = FloatType; boundsTexture.internalFormat = "RGBA32F"; boundsTexture.minFilter = NearestFilter; boundsTexture.magFilter = NearestFilter; boundsTexture.generateMipmaps = false; boundsTexture.needsUpdate = true; boundsTexture.dispose(); contentsTexture.image.data = contentsArray; contentsTexture.image.width = contentsDimension; contentsTexture.image.height = contentsDimension; contentsTexture.format = RGIntegerFormat; contentsTexture.type = UnsignedIntType; contentsTexture.internalFormat = "RG32UI"; contentsTexture.minFilter = NearestFilter; contentsTexture.magFilter = NearestFilter; contentsTexture.generateMipmaps = false; contentsTexture.needsUpdate = true; contentsTexture.dispose(); } // node_modules/three-mesh-bvh/src/utils/StaticGeometryGenerator.js var _positionVector = new Vector3(); var _normalVector = new Vector3(); var _tangentVector = new Vector3(); var _tangentVector4 = new Vector4(); var _morphVector = new Vector3(); var _temp = new Vector3(); var _skinIndex = new Vector4(); var _skinWeight = new Vector4(); var _matrix5 = new Matrix4(); var _boneMatrix = new Matrix4(); // node_modules/three-mesh-bvh/src/gpu/glsl/common_functions.glsl.js var common_functions = ( /* glsl */ ` // A stack of uint32 indices can can store the indices for // a perfectly balanced tree with a depth up to 31. Lower stack // depth gets higher performance. // // However not all trees are balanced. Best value to set this to // is the trees max depth. #ifndef BVH_STACK_DEPTH #define BVH_STACK_DEPTH 60 #endif #ifndef INFINITY #define INFINITY 1e20 #endif // Utilities uvec4 uTexelFetch1D( usampler2D tex, uint index ) { uint width = uint( textureSize( tex, 0 ).x ); uvec2 uv; uv.x = index % width; uv.y = index / width; return texelFetch( tex, ivec2( uv ), 0 ); } ivec4 iTexelFetch1D( isampler2D tex, uint index ) { uint width = uint( textureSize( tex, 0 ).x ); uvec2 uv; uv.x = index % width; uv.y = index / width; return texelFetch( tex, ivec2( uv ), 0 ); } vec4 texelFetch1D( sampler2D tex, uint index ) { uint width = uint( textureSize( tex, 0 ).x ); uvec2 uv; uv.x = index % width; uv.y = index / width; return texelFetch( tex, ivec2( uv ), 0 ); } vec4 textureSampleBarycoord( sampler2D tex, vec3 barycoord, uvec3 faceIndices ) { return barycoord.x * texelFetch1D( tex, faceIndices.x ) + barycoord.y * texelFetch1D( tex, faceIndices.y ) + barycoord.z * texelFetch1D( tex, faceIndices.z ); } void ndcToCameraRay( vec2 coord, mat4 cameraWorld, mat4 invProjectionMatrix, out vec3 rayOrigin, out vec3 rayDirection ) { // get camera look direction and near plane for camera clipping vec4 lookDirection = cameraWorld * vec4( 0.0, 0.0, - 1.0, 0.0 ); vec4 nearVector = invProjectionMatrix * vec4( 0.0, 0.0, - 1.0, 1.0 ); float near = abs( nearVector.z / nearVector.w ); // get the camera direction and position from camera matrices vec4 origin = cameraWorld * vec4( 0.0, 0.0, 0.0, 1.0 ); vec4 direction = invProjectionMatrix * vec4( coord, 0.5, 1.0 ); direction /= direction.w; direction = cameraWorld * direction - origin; // slide the origin along the ray until it sits at the near clip plane position origin.xyz += direction.xyz * near / dot( direction, lookDirection ); rayOrigin = origin.xyz; rayDirection = direction.xyz; } ` ); // node_modules/three-mesh-bvh/src/gpu/glsl/bvh_ray_functions.glsl.js var bvh_ray_functions = ( /* glsl */ ` #ifndef TRI_INTERSECT_EPSILON #define TRI_INTERSECT_EPSILON 1e-5 #endif // Raycasting bool intersectsBounds( vec3 rayOrigin, vec3 rayDirection, vec3 boundsMin, vec3 boundsMax, out float dist ) { // https://www.reddit.com/r/opengl/comments/8ntzz5/fast_glsl_ray_box_intersection/ // https://tavianator.com/2011/ray_box.html vec3 invDir = 1.0 / rayDirection; // find intersection distances for each plane vec3 tMinPlane = invDir * ( boundsMin - rayOrigin ); vec3 tMaxPlane = invDir * ( boundsMax - rayOrigin ); // get the min and max distances from each intersection vec3 tMinHit = min( tMaxPlane, tMinPlane ); vec3 tMaxHit = max( tMaxPlane, tMinPlane ); // get the furthest hit distance vec2 t = max( tMinHit.xx, tMinHit.yz ); float t0 = max( t.x, t.y ); // get the minimum hit distance t = min( tMaxHit.xx, tMaxHit.yz ); float t1 = min( t.x, t.y ); // set distance to 0.0 if the ray starts inside the box dist = max( t0, 0.0 ); return t1 >= dist; } bool intersectsTriangle( vec3 rayOrigin, vec3 rayDirection, vec3 a, vec3 b, vec3 c, out vec3 barycoord, out vec3 norm, out float dist, out float side ) { // https://stackoverflow.com/questions/42740765/intersection-between-line-and-triangle-in-3d vec3 edge1 = b - a; vec3 edge2 = c - a; norm = cross( edge1, edge2 ); float det = - dot( rayDirection, norm ); float invdet = 1.0 / det; vec3 AO = rayOrigin - a; vec3 DAO = cross( AO, rayDirection ); vec4 uvt; uvt.x = dot( edge2, DAO ) * invdet; uvt.y = - dot( edge1, DAO ) * invdet; uvt.z = dot( AO, norm ) * invdet; uvt.w = 1.0 - uvt.x - uvt.y; // set the hit information barycoord = uvt.wxy; // arranged in A, B, C order dist = uvt.z; side = sign( det ); norm = side * normalize( norm ); // add an epsilon to avoid misses between triangles uvt += vec4( TRI_INTERSECT_EPSILON ); return all( greaterThanEqual( uvt, vec4( 0.0 ) ) ); } bool intersectTriangles( // geometry info and triangle range sampler2D positionAttr, usampler2D indexAttr, uint offset, uint count, // ray vec3 rayOrigin, vec3 rayDirection, // outputs inout float minDistance, inout uvec4 faceIndices, inout vec3 faceNormal, inout vec3 barycoord, inout float side, inout float dist ) { bool found = false; vec3 localBarycoord, localNormal; float localDist, localSide; for ( uint i = offset, l = offset + count; i < l; i ++ ) { uvec3 indices = uTexelFetch1D( indexAttr, i ).xyz; vec3 a = texelFetch1D( positionAttr, indices.x ).rgb; vec3 b = texelFetch1D( positionAttr, indices.y ).rgb; vec3 c = texelFetch1D( positionAttr, indices.z ).rgb; if ( intersectsTriangle( rayOrigin, rayDirection, a, b, c, localBarycoord, localNormal, localDist, localSide ) && localDist < minDistance ) { found = true; minDistance = localDist; faceIndices = uvec4( indices.xyz, i ); faceNormal = localNormal; side = localSide; barycoord = localBarycoord; dist = localDist; } } return found; } bool intersectsBVHNodeBounds( vec3 rayOrigin, vec3 rayDirection, sampler2D bvhBounds, uint currNodeIndex, out float dist ) { uint cni2 = currNodeIndex * 2u; vec3 boundsMin = texelFetch1D( bvhBounds, cni2 ).xyz; vec3 boundsMax = texelFetch1D( bvhBounds, cni2 + 1u ).xyz; return intersectsBounds( rayOrigin, rayDirection, boundsMin, boundsMax, dist ); } // use a macro to hide the fact that we need to expand the struct into separate fields #define bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) _bvhIntersectFirstHit( bvh.position, bvh.index, bvh.bvhBounds, bvh.bvhContents, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) bool _bvhIntersectFirstHit( // bvh info sampler2D bvh_position, usampler2D bvh_index, sampler2D bvh_bvhBounds, usampler2D bvh_bvhContents, // ray vec3 rayOrigin, vec3 rayDirection, // output variables split into separate variables due to output precision inout uvec4 faceIndices, inout vec3 faceNormal, inout vec3 barycoord, inout float side, inout float dist ) { // stack needs to be twice as long as the deepest tree we expect because // we push both the left and right child onto the stack every traversal int ptr = 0; uint stack[ BVH_STACK_DEPTH ]; stack[ 0 ] = 0u; float triangleDistance = INFINITY; bool found = false; while ( ptr > - 1 && ptr < BVH_STACK_DEPTH ) { uint currNodeIndex = stack[ ptr ]; ptr --; // check if we intersect the current bounds float boundsHitDistance; if ( ! intersectsBVHNodeBounds( rayOrigin, rayDirection, bvh_bvhBounds, currNodeIndex, boundsHitDistance ) || boundsHitDistance > triangleDistance ) { continue; } uvec2 boundsInfo = uTexelFetch1D( bvh_bvhContents, currNodeIndex ).xy; bool isLeaf = bool( boundsInfo.x & 0xffff0000u ); if ( isLeaf ) { uint count = boundsInfo.x & 0x0000ffffu; uint offset = boundsInfo.y; found = intersectTriangles( bvh_position, bvh_index, offset, count, rayOrigin, rayDirection, triangleDistance, faceIndices, faceNormal, barycoord, side, dist ) || found; } else { uint leftIndex = currNodeIndex + 1u; uint splitAxis = boundsInfo.x & 0x0000ffffu; uint rightIndex = boundsInfo.y; bool leftToRight = rayDirection[ splitAxis ] >= 0.0; uint c1 = leftToRight ? leftIndex : rightIndex; uint c2 = leftToRight ? rightIndex : leftIndex; // set c2 in the stack so we traverse it later. We need to keep track of a pointer in // the stack while we traverse. The second pointer added is the one that will be // traversed first ptr ++; stack[ ptr ] = c2; ptr ++; stack[ ptr ] = c1; } } return found; } ` ); // node_modules/three-mesh-bvh/src/gpu/glsl/bvh_struct_definitions.glsl.js var bvh_struct_definitions = ( /* glsl */ ` struct BVH { usampler2D index; sampler2D position; sampler2D bvhBounds; usampler2D bvhContents; }; ` ); // node_modules/three-mesh-bvh/src/index.js var shaderStructs = bvh_struct_definitions; var shaderIntersectFunction = ` ${common_functions} ${bvh_ray_functions} `; // node_modules/@react-three/drei/core/Bvh.js var isMesh = (child) => child.isMesh; function useBVH(mesh, options) { options = { strategy: SAH, verbose: false, setBoundingBox: true, maxDepth: 40, maxLeafTris: 10, indirect: false, ...options }; React71.useEffect(() => { if (mesh.current) { mesh.current.raycast = acceleratedRaycast; const geometry3 = mesh.current.geometry; geometry3.computeBoundsTree = computeBoundsTree; geometry3.disposeBoundsTree = disposeBoundsTree; geometry3.computeBoundsTree(options); return () => { if (geometry3.boundsTree) { geometry3.disposeBoundsTree(); } }; } }, [mesh, JSON.stringify(options)]); } var Bvh = React71.forwardRef(({ enabled = true, firstHitOnly = false, children, strategy = SAH, verbose = false, setBoundingBox = true, maxDepth = 40, maxLeafTris = 10, indirect = false, ...props }, fref) => { const ref = React71.useRef(null); const raycaster = useThree((state) => state.raycaster); React71.useImperativeHandle(fref, () => ref.current, []); React71.useEffect(() => { if (enabled) { const options = { strategy, verbose, setBoundingBox, maxDepth, maxLeafTris, indirect }; const group = ref.current; raycaster.firstHitOnly = firstHitOnly; group.traverse((child) => { if (isMesh(child) && !child.geometry.boundsTree && child.raycast === Mesh.prototype.raycast) { child.raycast = acceleratedRaycast; child.geometry.computeBoundsTree = computeBoundsTree; child.geometry.disposeBoundsTree = disposeBoundsTree; child.geometry.computeBoundsTree(options); } }); return () => { delete raycaster.firstHitOnly; group.traverse((child) => { if (isMesh(child) && child.geometry.boundsTree) { child.geometry.disposeBoundsTree(); child.raycast = Mesh.prototype.raycast; } }); }; } }, []); return React71.createElement("group", _extends({ ref }, props), children); }); // node_modules/@react-three/drei/core/useContextBridge.js var React72 = __toESM(require_react()); function useContextBridge(...contexts) { const cRef = React72.useRef([]); cRef.current = contexts.map((context12) => React72.useContext(context12)); return React72.useMemo(() => ({ children }) => contexts.reduceRight( (acc, Context2, i4) => React72.createElement(Context2.Provider, { value: cRef.current[i4], children: acc }), children /* * done this way in reference to: * https://github.com/DefinitelyTyped/DefinitelyTyped/issues/44572#issuecomment-625878049 * https://github.com/microsoft/TypeScript/issues/14729 */ ), []); } // node_modules/@react-three/drei/core/useAnimations.js var React73 = __toESM(require_react()); function useAnimations(clips, root) { const ref = React73.useRef(null); const [actualRef] = React73.useState(() => root ? root instanceof Object3D ? { current: root } : root : ref); const [mixer] = React73.useState(() => new AnimationMixer(void 0)); React73.useLayoutEffect(() => { if (root) actualRef.current = root instanceof Object3D ? root : root.current; mixer._root = actualRef.current; }); const lazyActions = React73.useRef({}); const api = React73.useMemo(() => { const actions = {}; clips.forEach((clip) => Object.defineProperty(actions, clip.name, { enumerable: true, get() { if (actualRef.current) { return lazyActions.current[clip.name] || (lazyActions.current[clip.name] = mixer.clipAction(clip, actualRef.current)); } }, configurable: true })); return { ref: actualRef, clips, actions, names: clips.map((c2) => c2.name), mixer }; }, [clips]); useFrame((state, delta) => mixer.update(delta)); React73.useEffect(() => { const currentRoot = actualRef.current; return () => { lazyActions.current = {}; mixer.stopAllAction(); Object.values(api.actions).forEach((action) => { if (currentRoot) { mixer.uncacheAction(action, currentRoot); } }); }; }, [clips]); return api; } // node_modules/@react-three/drei/core/useIntersect.js var React74 = __toESM(require_react()); function useIntersect(onChange) { const ref = React74.useRef(null); const check = React74.useRef(false); const temp5 = React74.useRef(false); const callback = React74.useRef(onChange); React74.useLayoutEffect(() => void (callback.current = onChange), [onChange]); React74.useEffect(() => { const obj = ref.current; if (obj) { const unsub1 = addEffect(() => { check.current = false; return true; }); const oldOnRender = obj.onBeforeRender; obj.onBeforeRender = () => check.current = true; const unsub2 = addAfterEffect(() => { if (check.current !== temp5.current) callback.current == null || callback.current(temp5.current = check.current); return true; }); return () => { obj.onBeforeRender = oldOnRender; unsub1(); unsub2(); }; } }, []); return ref; } // node_modules/@react-three/drei/core/useBoxProjectedEnv.js var React75 = __toESM(require_react()); var worldposReplace = ( /* glsl */ ` #if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 ); #ifdef BOX_PROJECTED_ENV_MAP vWorldPosition = worldPosition.xyz; #endif #endif ` ); var boxProjectDefinitions = ( /*glsl */ ` #ifdef BOX_PROJECTED_ENV_MAP uniform vec3 envMapSize; uniform vec3 envMapPosition; varying vec3 vWorldPosition; vec3 parallaxCorrectNormal( vec3 v, vec3 cubeSize, vec3 cubePos ) { vec3 nDir = normalize( v ); vec3 rbmax = ( .5 * cubeSize + cubePos - vWorldPosition ) / nDir; vec3 rbmin = ( -.5 * cubeSize + cubePos - vWorldPosition ) / nDir; vec3 rbminmax; rbminmax.x = ( nDir.x > 0. ) ? rbmax.x : rbmin.x; rbminmax.y = ( nDir.y > 0. ) ? rbmax.y : rbmin.y; rbminmax.z = ( nDir.z > 0. ) ? rbmax.z : rbmin.z; float correction = min( min( rbminmax.x, rbminmax.y ), rbminmax.z ); vec3 boxIntersection = vWorldPosition + nDir * correction; return boxIntersection - cubePos; } #endif ` ); var getIBLIrradiance_patch = ( /* glsl */ ` #ifdef BOX_PROJECTED_ENV_MAP worldNormal = parallaxCorrectNormal( worldNormal, envMapSize, envMapPosition ); #endif ` ); var getIBLRadiance_patch = ( /* glsl */ ` #ifdef BOX_PROJECTED_ENV_MAP reflectVec = parallaxCorrectNormal( reflectVec, envMapSize, envMapPosition ); #endif ` ); function boxProjectedEnvMap(shader, envMapPosition, envMapSize) { shader.defines.BOX_PROJECTED_ENV_MAP = true; shader.uniforms.envMapPosition = { value: envMapPosition }; shader.uniforms.envMapSize = { value: envMapSize }; shader.vertexShader = ` varying vec3 vWorldPosition; ${shader.vertexShader.replace("#include ", worldposReplace)}`; shader.fragmentShader = ` ${boxProjectDefinitions} ${shader.fragmentShader.replace("#include ", ShaderChunk.envmap_physical_pars_fragment).replace("vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );", `vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); ${getIBLIrradiance_patch} `).replace("reflectVec = inverseTransformDirection( reflectVec, viewMatrix );", `reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); ${getIBLRadiance_patch} `)}`; } function useBoxProjectedEnv(position2 = new Vector3(), size2 = new Vector3()) { const [config] = React75.useState(() => ({ position: new Vector3(), size: new Vector3() })); applyProps(config, { position: position2, size: size2 }); const ref = React75.useRef(null); const spread = React75.useMemo(() => ({ ref, onBeforeCompile: (shader) => boxProjectedEnvMap(shader, config.position, config.size), customProgramCacheKey: () => JSON.stringify(config.position.toArray()) + JSON.stringify(config.size.toArray()) }), [...config.position.toArray(), ...config.size.toArray()]); React75.useLayoutEffect(() => void (ref.current.needsUpdate = true), [config]); return spread; } // node_modules/@react-three/drei/core/BBAnchor.js var React76 = __toESM(require_react()); var boundingBox4 = new Box3(); var boundingBoxSize = new Vector3(); var BBAnchor = ({ anchor, ...props }) => { const ref = React76.useRef(null); const parentRef = React76.useRef(null); React76.useEffect(() => { var _ref$current; if ((_ref$current = ref.current) != null && (_ref$current = _ref$current.parent) != null && _ref$current.parent) { parentRef.current = ref.current.parent; ref.current.parent.parent.add(ref.current); } }, []); useFrame(() => { if (parentRef.current) { boundingBox4.setFromObject(parentRef.current); boundingBox4.getSize(boundingBoxSize); ref.current.position.set(parentRef.current.position.x + boundingBoxSize.x * (Array.isArray(anchor) ? anchor[0] : anchor.x) / 2, parentRef.current.position.y + boundingBoxSize.y * (Array.isArray(anchor) ? anchor[1] : anchor.y) / 2, parentRef.current.position.z + boundingBoxSize.z * (Array.isArray(anchor) ? anchor[2] : anchor.z) / 2); } }); return React76.createElement("group", _extends({ ref }, props)); }; // node_modules/@react-three/drei/core/TrailTexture.js var React77 = __toESM(require_react()); var import_react16 = __toESM(require_react()); function smoothAverage(current, measurement, smoothing = 0.9) { return measurement * smoothing + current * (1 - smoothing); } var easeCircleOut = (x) => Math.sqrt(1 - Math.pow(x - 1, 2)); var TrailTextureImpl = class { constructor({ size: size2 = 256, maxAge = 750, radius = 0.3, intensity = 0.2, interpolate = 0, smoothing = 0, minForce = 0.3, blend = "screen", // source-over is canvas default. Others are slower ease = easeCircleOut } = {}) { this.size = size2; this.maxAge = maxAge; this.radius = radius; this.intensity = intensity; this.ease = ease; this.interpolate = interpolate; this.smoothing = smoothing; this.minForce = minForce; this.blend = blend; this.trail = []; this.force = 0; this.initTexture(); } initTexture() { this.canvas = document.createElement("canvas"); this.canvas.width = this.canvas.height = this.size; const ctx = this.canvas.getContext("2d"); if (ctx === null) { throw new Error("2D not available"); } this.ctx = ctx; this.ctx.fillStyle = "black"; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); this.texture = new Texture(this.canvas); this.canvas.id = "touchTexture"; this.canvas.style.width = this.canvas.style.height = `${this.canvas.width}px`; } update(delta) { this.clear(); this.trail.forEach((point, i4) => { point.age += delta * 1e3; if (point.age > this.maxAge) { this.trail.splice(i4, 1); } }); if (!this.trail.length) this.force = 0; this.trail.forEach((point) => { this.drawTouch(point); }); this.texture.needsUpdate = true; } clear() { this.ctx.globalCompositeOperation = "source-over"; this.ctx.fillStyle = "black"; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); } addTouch(point) { const last = this.trail[this.trail.length - 1]; if (last) { const dx = last.x - point.x; const dy = last.y - point.y; const dd = dx * dx + dy * dy; const force = Math.max(this.minForce, Math.min(dd * 1e4, 1)); this.force = smoothAverage(force, this.force, this.smoothing); if (!!this.interpolate) { const lines = Math.ceil(dd / Math.pow(this.radius * 0.5 / this.interpolate, 2)); if (lines > 1) { for (let i4 = 1; i4 < lines; i4++) { this.trail.push({ x: last.x - dx / lines * i4, y: last.y - dy / lines * i4, age: 0, force }); } } } } this.trail.push({ x: point.x, y: point.y, age: 0, force: this.force }); } drawTouch(point) { const pos = { x: point.x * this.size, y: (1 - point.y) * this.size }; let intensity = 1; if (point.age < this.maxAge * 0.3) { intensity = this.ease(point.age / (this.maxAge * 0.3)); } else { intensity = this.ease(1 - (point.age - this.maxAge * 0.3) / (this.maxAge * 0.7)); } intensity *= point.force; this.ctx.globalCompositeOperation = this.blend; const radius = this.size * this.radius * intensity; const grd = this.ctx.createRadialGradient(pos.x, pos.y, Math.max(0, radius * 0.25), pos.x, pos.y, Math.max(0, radius)); grd.addColorStop(0, `rgba(255, 255, 255, ${this.intensity})`); grd.addColorStop(1, `rgba(0, 0, 0, 0.0)`); this.ctx.beginPath(); this.ctx.fillStyle = grd; this.ctx.arc(pos.x, pos.y, Math.max(0, radius), 0, Math.PI * 2); this.ctx.fill(); } }; function useTrailTexture(config = {}) { const { size: size2, maxAge, radius, intensity, interpolate, smoothing, minForce, blend, ease } = config; const trail = (0, import_react16.useMemo)(() => new TrailTextureImpl(config), [size2, maxAge, radius, intensity, interpolate, smoothing, minForce, blend, ease]); useFrame((_, delta) => void trail.update(delta)); const onMove = (0, import_react16.useCallback)((e2) => trail.addTouch(e2.uv), [trail]); return [trail.texture, onMove]; } var TrailTexture = ({ children, ...config }) => { const ret = useTrailTexture(config); return React77.createElement(React77.Fragment, null, children == null ? void 0 : children(ret)); }; // node_modules/@react-three/drei/core/Example.js var React79 = __toESM(require_react()); // node_modules/@react-three/drei/core/Center.js var React78 = __toESM(require_react()); var Center = React78.forwardRef(function Center2({ children, object, disable, disableX, disableY, disableZ, left, right, top, bottom, front, back, onCentered, precise = true, cacheKey = 0, ...props }, fRef) { const ref = React78.useRef(null); const outer = React78.useRef(null); const inner = React78.useRef(null); const [box3] = React78.useState(() => new Box3()); const [center3] = React78.useState(() => new Vector3()); const [sphere] = React78.useState(() => new Sphere()); React78.useLayoutEffect(() => { outer.current.matrixWorld.identity(); box3.setFromObject(object !== null && object !== void 0 ? object : inner.current, precise); const width = box3.max.x - box3.min.x; const height = box3.max.y - box3.min.y; const depth = box3.max.z - box3.min.z; box3.getCenter(center3); box3.getBoundingSphere(sphere); const vAlign = top ? height / 2 : bottom ? -height / 2 : 0; const hAlign = left ? -width / 2 : right ? width / 2 : 0; const dAlign = front ? depth / 2 : back ? -depth / 2 : 0; outer.current.position.set(disable || disableX ? 0 : -center3.x + hAlign, disable || disableY ? 0 : -center3.y + vAlign, disable || disableZ ? 0 : -center3.z + dAlign); onCentered == null || onCentered({ parent: ref.current.parent, container: ref.current, width, height, depth, boundingBox: box3, boundingSphere: sphere, center: center3, verticalAlignment: vAlign, horizontalAlignment: hAlign, depthAlignment: dAlign }); }, [cacheKey, onCentered, top, left, front, disable, disableX, disableY, disableZ, object, precise, right, bottom, back, box3, center3, sphere]); React78.useImperativeHandle(fRef, () => ref.current, []); return React78.createElement("group", _extends({ ref }, props), React78.createElement("group", { ref: outer }, React78.createElement("group", { ref: inner }, children))); }); // node_modules/@react-three/drei/core/Example.js var Example = React79.forwardRef(({ font, color = "#cbcbcb", bevelSize = 0.04, debug = false, children, ...props }, fref) => { const [counter, setCounter] = React79.useState(0); const incr = React79.useCallback((x = 1) => setCounter(counter + x), [counter]); const decr = React79.useCallback((x = 1) => setCounter(counter - x), [counter]); const api = React79.useMemo(() => ({ incr, decr }), [incr, decr]); React79.useImperativeHandle(fref, () => api, [api]); return React79.createElement("group", props, React79.createElement(React79.Suspense, { fallback: null }, React79.createElement(Center, { top: true, cacheKey: JSON.stringify({ counter, font }) }, React79.createElement(Text3D, { bevelEnabled: true, bevelSize, font }, debug ? React79.createElement("meshNormalMaterial", { wireframe: true }) : React79.createElement("meshStandardMaterial", { color }), counter))), children); }); // node_modules/@react-three/drei/core/SpriteAnimator.js var React81 = __toESM(require_react()); // node_modules/@react-three/drei/core/Instances.js var React80 = __toESM(require_react()); // node_modules/@react-three/drei/helpers/deprecated.js var setUpdateRange = (attribute, updateRange) => { attribute.updateRanges[0] = updateRange; }; // node_modules/@react-three/drei/core/Instances.js function isFunctionChild(value) { return typeof value === "function"; } var _instanceLocalMatrix = new Matrix4(); var _instanceWorldMatrix = new Matrix4(); var _instanceIntersects = []; var _mesh3 = new Mesh(); var PositionMesh = class extends Group { constructor() { super(); this.color = new Color("white"); this.instance = { current: void 0 }; this.instanceKey = { current: void 0 }; } // This will allow the virtual instance have bounds get geometry() { var _this$instance$curren; return (_this$instance$curren = this.instance.current) == null ? void 0 : _this$instance$curren.geometry; } // And this will allow the virtual instance to receive events raycast(raycaster, intersects) { const parent = this.instance.current; if (!parent) return; if (!parent.geometry || !parent.material) return; _mesh3.geometry = parent.geometry; const matrixWorld = parent.matrixWorld; const instanceId = parent.userData.instances.indexOf(this.instanceKey); if (instanceId === -1 || instanceId > parent.count) return; parent.getMatrixAt(instanceId, _instanceLocalMatrix); _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); _mesh3.matrixWorld = _instanceWorldMatrix; if (parent.material instanceof Material) _mesh3.material.side = parent.material.side; else _mesh3.material.side = parent.material[0].side; _mesh3.raycast(raycaster, _instanceIntersects); for (let i4 = 0, l2 = _instanceIntersects.length; i4 < l2; i4++) { const intersect = _instanceIntersects[i4]; intersect.instanceId = instanceId; intersect.object = this; intersects.push(intersect); } _instanceIntersects.length = 0; } }; var globalContext2 = React80.createContext(null); var parentMatrix = new Matrix4(); var instanceMatrix = new Matrix4(); var tempMatrix3 = new Matrix4(); var translation = new Vector3(); var rotation = new Quaternion(); var scale3 = new Vector3(); var isInstancedBufferAttribute = (attr) => attr.isInstancedBufferAttribute; var Instance = React80.forwardRef(({ context: context12, children, ...props }, ref) => { React80.useMemo(() => extend({ PositionMesh }), []); const group = React80.useRef(null); React80.useImperativeHandle(ref, () => group.current, []); const { subscribe, getParent } = React80.useContext(context12 || globalContext2); React80.useLayoutEffect(() => subscribe(group), []); return React80.createElement("positionMesh", _extends({ instance: getParent(), instanceKey: group, ref: group }, props), children); }); var Instances = React80.forwardRef(({ context: context12, children, range, limit = 1e3, frames = Infinity, ...props }, ref) => { const [{ localContext, instance: instance2 }] = React80.useState(() => { const localContext2 = React80.createContext(null); return { localContext: localContext2, instance: React80.forwardRef((props2, ref2) => React80.createElement(Instance, _extends({ context: localContext2 }, props2, { ref: ref2 }))) }; }); const parentRef = React80.useRef(null); React80.useImperativeHandle(ref, () => parentRef.current, []); const [instances, setInstances] = React80.useState([]); const [[matrices, colors2]] = React80.useState(() => { const mArray = new Float32Array(limit * 16); for (let i4 = 0; i4 < limit; i4++) tempMatrix3.identity().toArray(mArray, i4 * 16); return [mArray, new Float32Array([...new Array(limit * 3)].map(() => 1))]; }); React80.useEffect(() => { parentRef.current.instanceMatrix.needsUpdate = true; }); let iterations = 0; let count = 0; const attributes = React80.useRef([]); React80.useLayoutEffect(() => { attributes.current = Object.entries(parentRef.current.geometry.attributes).filter(([_name, value]) => isInstancedBufferAttribute(value)); }); useFrame(() => { if (frames === Infinity || iterations < frames) { parentRef.current.updateMatrix(); parentRef.current.updateMatrixWorld(); parentMatrix.copy(parentRef.current.matrixWorld).invert(); count = Math.min(limit, range !== void 0 ? range : limit, instances.length); parentRef.current.count = count; setUpdateRange(parentRef.current.instanceMatrix, { start: 0, count: count * 16 }); setUpdateRange(parentRef.current.instanceColor, { start: 0, count: count * 3 }); for (let i4 = 0; i4 < instances.length; i4++) { const instance3 = instances[i4].current; instance3.matrixWorld.decompose(translation, rotation, scale3); instanceMatrix.compose(translation, rotation, scale3).premultiply(parentMatrix); instanceMatrix.toArray(matrices, i4 * 16); parentRef.current.instanceMatrix.needsUpdate = true; instance3.color.toArray(colors2, i4 * 3); parentRef.current.instanceColor.needsUpdate = true; } iterations++; } }); const api = React80.useMemo(() => ({ getParent: () => parentRef, subscribe: (ref2) => { setInstances((instances2) => [...instances2, ref2]); return () => setInstances((instances2) => instances2.filter((item) => item.current !== ref2.current)); } }), []); return React80.createElement("instancedMesh", _extends({ userData: { instances, limit, frames }, matrixAutoUpdate: false, ref: parentRef, args: [null, null, 0], raycast: () => null }, props), React80.createElement("instancedBufferAttribute", { attach: "instanceMatrix", args: [matrices, 16], usage: DynamicDrawUsage }), React80.createElement("instancedBufferAttribute", { attach: "instanceColor", args: [colors2, 3], usage: DynamicDrawUsage }), isFunctionChild(children) ? React80.createElement(localContext.Provider, { value: api }, children(instance2)) : context12 ? React80.createElement(context12.Provider, { value: api }, children) : React80.createElement(globalContext2.Provider, { value: api }, children)); }); var Merged = React80.forwardRef(function Merged2({ meshes, children, ...props }, ref) { const isArray3 = Array.isArray(meshes); if (!isArray3) { for (const key of Object.keys(meshes)) if (!meshes[key].isMesh) delete meshes[key]; } const render = (args) => isArray3 ? ( // @ts-expect-error children(...args) ) : children( // @ts-expect-error Object.keys(meshes).filter((key) => meshes[key].isMesh).reduce((acc, key, i4) => ({ ...acc, [key]: args[i4] }), {}) ); const components = (isArray3 ? meshes : Object.values(meshes)).map(({ geometry: geometry3, material }) => React80.createElement(Instances, _extends({ key: geometry3.uuid, geometry: geometry3, material }, props))); return React80.createElement("group", { ref }, renderRecursive(render, components)); }); function renderRecursive(render, components, results = []) { if (!components[0]) { return render(results); } function nextRender(value) { return renderRecursive(render, components.slice(1), results.concat([value])); } return typeof components[0] === "function" ? ( // When it is a function, produce an element by invoking it with "render component values". components[0]({ results, render: nextRender }) ) : ( // When it is an element, enhance the element's props with the render prop. React80.cloneElement(components[0], { children: nextRender }) ); } function createInstances() { const context12 = React80.createContext(null); return [React80.forwardRef((props, fref) => React80.createElement(Instances, _extends({ ref: fref, context: context12 }, props))), React80.forwardRef((props, fref) => React80.createElement(Instance, _extends({ ref: fref, context: context12 }, props)))]; } var InstancedAttribute = React80.forwardRef(({ name, defaultValue, normalized, usage = DynamicDrawUsage }, fref) => { const ref = React80.useRef(null); React80.useImperativeHandle(fref, () => ref.current, []); React80.useLayoutEffect(() => { const parent = ref.current.__r3f.parent.object; parent.geometry.attributes[name] = ref.current; const value = Array.isArray(defaultValue) ? defaultValue : [defaultValue]; const array = Array.from({ length: parent.userData.limit }, () => value).flat(); ref.current.array = new Float32Array(array); ref.current.itemSize = value.length; ref.current.count = array.length / ref.current.itemSize; return () => { delete parent.geometry.attributes[name]; }; }, [name]); let iterations = 0; useFrame(() => { const parent = ref.current.__r3f.parent.object; if (parent.userData.frames === Infinity || iterations < parent.userData.frames) { for (let i4 = 0; i4 < parent.userData.instances.length; i4++) { const instance2 = parent.userData.instances[i4].current; const value = instance2[name]; if (value !== void 0) { ref.current.set(Array.isArray(value) ? value : typeof value.toArray === "function" ? value.toArray() : [value], i4 * ref.current.itemSize); ref.current.needsUpdate = true; } } iterations++; } }); return React80.createElement("instancedBufferAttribute", { ref, usage, normalized }); }); // node_modules/@react-three/drei/core/SpriteAnimator.js var context5 = React81.createContext(null); function useSpriteAnimator() { return React81.useContext(context5); } function isSpriteData(data) { return data !== null && "meta" in data && "frames" in data; } var geometry2 = new PlaneGeometry(1, 1); var SpriteAnimator = React81.forwardRef(({ startFrame = 0, endFrame, fps = 30, frameName = "", textureDataURL, textureImageURL, loop = false, numberOfFrames = 1, autoPlay = true, animationNames, onStart, onEnd, onLoopEnd, onFrame, play, pause = false, flipX = false, alphaTest = 0, children, asSprite = false, offset, playBackwards = false, resetOnEnd = false, maxItems = 1, instanceItems = [[0, 0, 0]], spriteDataset, canvasRenderingContext2DSettings, roundFramePosition = false, meshProps = {}, ...props }, fref) => { const ref = React81.useRef(new Group()); const spriteData = React81.useRef(null); const matRef = React81.useRef(null); const spriteRef = React81.useRef(null); const timerOffset = React81.useRef(window.performance.now()); const currentFrame = React81.useRef(startFrame); const currentFrameName = React81.useRef(frameName); const fpsInterval = fps > 0 ? 1e3 / fps : 0; const [spriteTexture, setSpriteTexture] = React81.useState(new Texture()); const totalFrames = React81.useRef(0); const [aspect, setAspect] = React81.useState(new Vector3(1, 1, 1)); const flipOffset = flipX ? -1 : 1; const pauseRef = React81.useRef(pause); const pos = React81.useRef(offset); const softEnd = React81.useRef(false); const { spriteObj, loadJsonAndTexture } = useSpriteLoader(null, null, animationNames, numberOfFrames, void 0, canvasRenderingContext2DSettings); const frameNameRef = React81.useRef(frameName); const parseSpriteDataLite = React81.useCallback((textureData, data) => { if (data === null) { if (numberOfFrames) { totalFrames.current = numberOfFrames; if (playBackwards) { currentFrame.current = numberOfFrames - 1; } spriteData.current = data; } } else { var _spriteData$current$f, _spriteData$current; spriteData.current = data; if (spriteData.current && Array.isArray(spriteData.current.frames)) { totalFrames.current = spriteData.current.frames.length; } else if (spriteData.current && typeof spriteData.current === "object" && frameNameRef.current) { totalFrames.current = spriteData.current.frames[frameNameRef.current].length; } else { totalFrames.current = 0; } if (playBackwards) { currentFrame.current = totalFrames.current - 1; } const { w, h } = getFirstFrame((_spriteData$current$f = (_spriteData$current = spriteData.current) == null ? void 0 : _spriteData$current.frames) !== null && _spriteData$current$f !== void 0 ? _spriteData$current$f : [], frameNameRef.current).sourceSize; const aspect2 = calculateAspectRatio(w, h); setAspect(aspect2); if (matRef.current) { matRef.current.map = textureData; } } setSpriteTexture(textureData); }, [numberOfFrames, playBackwards]); const modifySpritePosition = React81.useCallback(() => { if (!spriteData.current) return; const { meta: { size: metaInfo }, frames } = spriteData.current; const { w: frameW, h: frameH } = Array.isArray(frames) ? frames[0].sourceSize : frameName ? frames[frameName] ? frames[frameName][0].sourceSize : { w: 0, h: 0 } : { w: 0, h: 0 }; if (matRef.current && matRef.current.map) { matRef.current.map.wrapS = matRef.current.map.wrapT = RepeatWrapping; matRef.current.map.center.set(0, 0); matRef.current.map.repeat.set(1 * flipOffset / (metaInfo.w / frameW), 1 / (metaInfo.h / frameH)); } const framesV = (metaInfo.h - 1) / frameH; const frameOffsetY = 1 / framesV; if (matRef.current && matRef.current.map) { matRef.current.map.offset.x = 0; matRef.current.map.offset.y = 1 - frameOffsetY; } if (onStart) { onStart({ currentFrameName: frameName !== null && frameName !== void 0 ? frameName : "", currentFrame: currentFrame.current }); } }, [flipOffset, frameName, onStart]); const state = React81.useMemo(() => ({ current: pos.current, offset: pos.current, imageUrl: textureImageURL, hasEnded: false, ref: fref }), [textureImageURL, fref]); React81.useImperativeHandle(fref, () => ref.current, []); React81.useLayoutEffect(() => { pos.current = offset; }, [offset]); const calculateAspectRatio = (width, height) => { var _spriteRef$current; const ret = new Vector3(); const aspectRatio = height / width; ret.set(1, aspectRatio, 1); (_spriteRef$current = spriteRef.current) == null || _spriteRef$current.scale.copy(ret); return ret; }; React81.useEffect(() => { if (spriteDataset) { var _spriteDataset$sprite; parseSpriteDataLite(spriteDataset == null || (_spriteDataset$sprite = spriteDataset.spriteTexture) == null ? void 0 : _spriteDataset$sprite.clone(), spriteDataset.spriteData); } else { if (textureImageURL && textureDataURL) { loadJsonAndTexture(textureImageURL, textureDataURL); } } }, [loadJsonAndTexture, spriteDataset, textureDataURL, textureImageURL, parseSpriteDataLite]); React81.useEffect(() => { if (spriteObj) { var _spriteObj$spriteText; parseSpriteDataLite(spriteObj == null || (_spriteObj$spriteText = spriteObj.spriteTexture) == null ? void 0 : _spriteObj$spriteText.clone(), spriteObj == null ? void 0 : spriteObj.spriteData); } }, [spriteObj, parseSpriteDataLite]); React81.useEffect(() => { state.hasEnded = false; if (spriteData.current && playBackwards === true) { var _ref; currentFrame.current = ((_ref = spriteData.current.frames.length) !== null && _ref !== void 0 ? _ref : 0) - 1; } else { currentFrame.current = 0; } }, [playBackwards, state]); React81.useLayoutEffect(() => { modifySpritePosition(); }, [spriteTexture, flipX, modifySpritePosition]); React81.useEffect(() => { if (autoPlay) { pauseRef.current = false; } }, [autoPlay]); React81.useLayoutEffect(() => { if (currentFrameName.current !== frameName && frameName) { currentFrame.current = 0; currentFrameName.current = frameName; state.hasEnded = false; if (fpsInterval <= 0) { currentFrame.current = endFrame || startFrame || 0; } if (spriteData.current) { const { w, h } = getFirstFrame(spriteData.current.frames, frameName).sourceSize; const _aspect = calculateAspectRatio(w, h); setAspect(_aspect); } } }, [frameName, fpsInterval, state, endFrame, startFrame]); const runAnimation = () => { if (!isSpriteData(spriteData.current)) return; const { meta: { size: metaInfo }, frames } = spriteData.current; const { w: frameW, h: frameH } = getFirstFrame(frames, frameName).sourceSize; const spriteFrames = Array.isArray(frames) ? frames : frameName ? frames[frameName] : []; const _endFrame = endFrame || spriteFrames.length - 1; var _offset2 = offset === void 0 ? state.current : offset; if (fpsInterval <= 0) { currentFrame.current = endFrame || startFrame || 0; calculateFinalPosition(frameW, frameH, metaInfo, spriteFrames); return; } const now2 = window.performance.now(); const diff = now2 - timerOffset.current; if (diff <= fpsInterval) return; var endCondition = playBackwards ? currentFrame.current < 0 : currentFrame.current > _endFrame; var onStartCondition = playBackwards ? currentFrame.current === _endFrame : currentFrame.current === 0; var manualProgressEndCondition = playBackwards ? currentFrame.current < 0 : currentFrame.current >= _endFrame; if (endCondition) { currentFrame.current = loop ? startFrame !== null && startFrame !== void 0 ? startFrame : 0 : 0; if (playBackwards) { currentFrame.current = _endFrame; } if (loop) { onLoopEnd == null || onLoopEnd({ currentFrameName: frameName !== null && frameName !== void 0 ? frameName : "", currentFrame: currentFrame.current }); } else { onEnd == null || onEnd({ currentFrameName: frameName !== null && frameName !== void 0 ? frameName : "", currentFrame: currentFrame.current }); state.hasEnded = !resetOnEnd; if (resetOnEnd) { pauseRef.current = true; } } if (!loop) return; } else if (onStartCondition) { onStart == null || onStart({ currentFrameName: frameName !== null && frameName !== void 0 ? frameName : "", currentFrame: currentFrame.current }); } if (_offset2 !== void 0 && manualProgressEndCondition) { if (softEnd.current === false) { onEnd == null || onEnd({ currentFrameName: frameName !== null && frameName !== void 0 ? frameName : "", currentFrame: currentFrame.current }); softEnd.current = true; } } else { softEnd.current = false; } if (diff <= fpsInterval) return; timerOffset.current = now2 - diff % fpsInterval; calculateFinalPosition(frameW, frameH, metaInfo, spriteFrames); }; const calculateFinalPosition = (frameW, frameH, metaInfo, spriteFrames) => { var _offset2 = offset === void 0 ? state.current : offset; const targetFrame = currentFrame.current; let finalValX = 0; let finalValY = 0; calculateAspectRatio(frameW, frameH); const framesH = roundFramePosition ? Math.round((metaInfo.w - 1) / frameW) : (metaInfo.w - 1) / frameW; const framesV = roundFramePosition ? Math.round((metaInfo.h - 1) / frameH) : (metaInfo.h - 1) / frameH; if (!spriteFrames[targetFrame]) { return; } const { frame: { x: frameX, y: frameY }, sourceSize: { w: originalSizeX, h: originalSizeY } } = spriteFrames[targetFrame]; const frameOffsetX = 1 / framesH; const frameOffsetY = 1 / framesV; if (matRef.current && matRef.current.map) { finalValX = flipOffset > 0 ? frameOffsetX * (frameX / originalSizeX) : frameOffsetX * (frameX / originalSizeX) - matRef.current.map.repeat.x; finalValY = Math.abs(1 - frameOffsetY) - frameOffsetY * (frameY / originalSizeY); matRef.current.map.offset.x = finalValX; matRef.current.map.offset.y = finalValY; } if (_offset2 !== void 0 && _offset2 !== null) { let frameIndex = Math.floor(_offset2 * spriteFrames.length); frameIndex = Math.max(0, Math.min(frameIndex, spriteFrames.length - 1)); if (isNaN(frameIndex)) { frameIndex = 0; } currentFrame.current = frameIndex; } else { if (playBackwards) { currentFrame.current -= 1; } else { currentFrame.current += 1; } } }; useFrame((_state, _delta) => { var _spriteData$current2, _matRef$current; if (!((_spriteData$current2 = spriteData.current) != null && _spriteData$current2.frames) || !((_matRef$current = matRef.current) != null && _matRef$current.map)) { return; } if (pauseRef.current) { return; } if (!state.hasEnded && (autoPlay || play)) { runAnimation(); onFrame == null || onFrame({ currentFrameName: currentFrameName.current, currentFrame: currentFrame.current }); } }); function multiplyScale(initialScale = new Vector3(1, 1, 1), newScale = 1) { if (typeof newScale === "number") return initialScale.multiplyScalar(newScale); if (Array.isArray(newScale)) return initialScale.multiply(new Vector3(...newScale)); if (newScale instanceof Vector3) return initialScale.multiply(newScale); } return React81.createElement("group", _extends({}, props, { ref, scale: multiplyScale(aspect, props.scale) }), React81.createElement(context5.Provider, { value: state }, asSprite && React81.createElement(Billboard, null, React81.createElement("mesh", _extends({ ref: spriteRef, scale: 1, geometry: geometry2 }, meshProps), React81.createElement("meshBasicMaterial", { premultipliedAlpha: false, toneMapped: false, side: DoubleSide, ref: matRef, map: spriteTexture, transparent: true, alphaTest: alphaTest !== null && alphaTest !== void 0 ? alphaTest : 0 }))), !asSprite && React81.createElement(Instances, _extends({ geometry: geometry2, limit: maxItems !== null && maxItems !== void 0 ? maxItems : 1 }, meshProps), React81.createElement("meshBasicMaterial", { premultipliedAlpha: false, toneMapped: false, side: DoubleSide, ref: matRef, map: spriteTexture, transparent: true, alphaTest: alphaTest !== null && alphaTest !== void 0 ? alphaTest : 0 }), (instanceItems !== null && instanceItems !== void 0 ? instanceItems : [0]).map((item, index2) => React81.createElement(Instance, _extends({ key: index2, ref: (instanceItems == null ? void 0 : instanceItems.length) === 1 ? spriteRef : null, position: item, scale: 1 }, meshProps)))), children)); }); // node_modules/@react-three/drei/core/CurveModifier.js var React82 = __toESM(require_react()); var CurveModifier = React82.forwardRef(({ children, curve }, ref) => { const [scene] = React82.useState(() => new Scene()); const [obj, set] = React82.useState(); const modifier = React82.useRef(null); React82.useLayoutEffect(() => { modifier.current = new Flow(scene.children[0]); set(modifier.current.object3D); }, [children]); React82.useEffect(() => { var _modifier$current; if (curve) (_modifier$current = modifier.current) == null || _modifier$current.updateCurve(0, curve); }, [curve]); React82.useImperativeHandle(ref, () => modifier.current); return React82.createElement(React82.Fragment, null, createPortal(children, scene), obj && React82.createElement("primitive", { object: obj })); }); // node_modules/@react-three/drei/core/MeshDistortMaterial.js var React83 = __toESM(require_react()); // node_modules/@react-three/drei/helpers/glsl/distort.vert.glsl.js var distort = "#define GLSLIFY 1\nvec3 mod289(vec3 x){return x-floor(x*(1.0/289.0))*289.0;}vec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}vec4 permute(vec4 x){return mod289(((x*34.0)+1.0)*x);}vec4 taylorInvSqrt(vec4 r){return 1.79284291400159-0.85373472095314*r;}float snoise(vec3 v){const vec2 C=vec2(1.0/6.0,1.0/3.0);const vec4 D=vec4(0.0,0.5,1.0,2.0);vec3 i=floor(v+dot(v,C.yyy));vec3 x0=v-i+dot(i,C.xxx);vec3 g=step(x0.yzx,x0.xyz);vec3 l=1.0-g;vec3 i1=min(g.xyz,l.zxy);vec3 i2=max(g.xyz,l.zxy);vec3 x1=x0-i1+C.xxx;vec3 x2=x0-i2+C.yyy;vec3 x3=x0-D.yyy;i=mod289(i);vec4 p=permute(permute(permute(i.z+vec4(0.0,i1.z,i2.z,1.0))+i.y+vec4(0.0,i1.y,i2.y,1.0))+i.x+vec4(0.0,i1.x,i2.x,1.0));float n_=0.142857142857;vec3 ns=n_*D.wyz-D.xzx;vec4 j=p-49.0*floor(p*ns.z*ns.z);vec4 x_=floor(j*ns.z);vec4 y_=floor(j-7.0*x_);vec4 x=x_*ns.x+ns.yyyy;vec4 y=y_*ns.x+ns.yyyy;vec4 h=1.0-abs(x)-abs(y);vec4 b0=vec4(x.xy,y.xy);vec4 b1=vec4(x.zw,y.zw);vec4 s0=floor(b0)*2.0+1.0;vec4 s1=floor(b1)*2.0+1.0;vec4 sh=-step(h,vec4(0.0));vec4 a0=b0.xzyw+s0.xzyw*sh.xxyy;vec4 a1=b1.xzyw+s1.xzyw*sh.zzww;vec3 p0=vec3(a0.xy,h.x);vec3 p1=vec3(a0.zw,h.y);vec3 p2=vec3(a1.xy,h.z);vec3 p3=vec3(a1.zw,h.w);vec4 norm=taylorInvSqrt(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3)));p0*=norm.x;p1*=norm.y;p2*=norm.z;p3*=norm.w;vec4 m=max(0.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),0.0);m=m*m;return 42.0*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3)));}"; // node_modules/@react-three/drei/core/MeshDistortMaterial.js var DistortMaterialImpl = class extends MeshPhysicalMaterial { constructor(parameters = {}) { super(parameters); this.setValues(parameters); this._time = { value: 0 }; this._distort = { value: 0.4 }; this._radius = { value: 1 }; } // FIXME Use `THREE.WebGLProgramParametersWithUniforms` type when able to target @types/three@0.160.0 onBeforeCompile(shader) { shader.uniforms.time = this._time; shader.uniforms.radius = this._radius; shader.uniforms.distort = this._distort; shader.vertexShader = ` uniform float time; uniform float radius; uniform float distort; ${distort} ${shader.vertexShader} `; shader.vertexShader = shader.vertexShader.replace("#include ", ` float updateTime = time / 50.0; float noise = snoise(vec3(position / 2.0 + updateTime * 5.0)); vec3 transformed = vec3(position * (noise * pow(distort, 2.0) + radius)); `); } get time() { return this._time.value; } set time(v5) { this._time.value = v5; } get distort() { return this._distort.value; } set distort(v5) { this._distort.value = v5; } get radius() { return this._radius.value; } set radius(v5) { this._radius.value = v5; } }; var MeshDistortMaterial = React83.forwardRef(({ speed = 1, ...props }, ref) => { const [material] = React83.useState(() => new DistortMaterialImpl()); useFrame((state) => material && (material.time = state.clock.elapsedTime * speed)); return React83.createElement("primitive", _extends({ object: material, ref, attach: "material" }, props)); }); // node_modules/@react-three/drei/core/MeshWobbleMaterial.js var React84 = __toESM(require_react()); var WobbleMaterialImpl = class extends MeshStandardMaterial { constructor(parameters = {}) { super(parameters); this.setValues(parameters); this._time = { value: 0 }; this._factor = { value: 1 }; } // FIXME Use `THREE.WebGLProgramParametersWithUniforms` type when able to target @types/three@0.160.0 onBeforeCompile(shader) { shader.uniforms.time = this._time; shader.uniforms.factor = this._factor; shader.vertexShader = ` uniform float time; uniform float factor; ${shader.vertexShader} `; shader.vertexShader = shader.vertexShader.replace("#include ", `float theta = sin( time + position.y ) / 2.0 * factor; float c = cos( theta ); float s = sin( theta ); mat3 m = mat3( c, 0, s, 0, 1, 0, -s, 0, c ); vec3 transformed = vec3( position ) * m; vNormal = vNormal * m;`); } get time() { return this._time.value; } set time(v5) { this._time.value = v5; } get factor() { return this._factor.value; } set factor(v5) { this._factor.value = v5; } }; var MeshWobbleMaterial = React84.forwardRef(({ speed = 1, ...props }, ref) => { const [material] = React84.useState(() => new WobbleMaterialImpl()); useFrame((state) => material && (material.time = state.clock.elapsedTime * speed)); return React84.createElement("primitive", _extends({ object: material, ref, attach: "material" }, props)); }); // node_modules/@react-three/drei/core/MeshReflectorMaterial.js var React85 = __toESM(require_react()); // node_modules/@react-three/drei/materials/ConvolutionMaterial.js var ConvolutionMaterial = class extends ShaderMaterial { constructor(texelSize = new Vector2()) { super({ uniforms: { inputBuffer: new Uniform(null), depthBuffer: new Uniform(null), resolution: new Uniform(new Vector2()), texelSize: new Uniform(new Vector2()), halfTexelSize: new Uniform(new Vector2()), kernel: new Uniform(0), scale: new Uniform(1), cameraNear: new Uniform(0), cameraFar: new Uniform(1), minDepthThreshold: new Uniform(0), maxDepthThreshold: new Uniform(1), depthScale: new Uniform(0), depthToBlurRatioBias: new Uniform(0.25) }, fragmentShader: `#include #include uniform sampler2D inputBuffer; uniform sampler2D depthBuffer; uniform float cameraNear; uniform float cameraFar; uniform float minDepthThreshold; uniform float maxDepthThreshold; uniform float depthScale; uniform float depthToBlurRatioBias; varying vec2 vUv; varying vec2 vUv0; varying vec2 vUv1; varying vec2 vUv2; varying vec2 vUv3; void main() { float depthFactor = 0.0; #ifdef USE_DEPTH vec4 depth = texture2D(depthBuffer, vUv); depthFactor = smoothstep(minDepthThreshold, maxDepthThreshold, 1.0-(depth.r * depth.a)); depthFactor *= depthScale; depthFactor = max(0.0, min(1.0, depthFactor + 0.25)); #endif vec4 sum = texture2D(inputBuffer, mix(vUv0, vUv, depthFactor)); sum += texture2D(inputBuffer, mix(vUv1, vUv, depthFactor)); sum += texture2D(inputBuffer, mix(vUv2, vUv, depthFactor)); sum += texture2D(inputBuffer, mix(vUv3, vUv, depthFactor)); gl_FragColor = sum * 0.25 ; #include #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }`, vertexShader: `uniform vec2 texelSize; uniform vec2 halfTexelSize; uniform float kernel; uniform float scale; varying vec2 vUv; varying vec2 vUv0; varying vec2 vUv1; varying vec2 vUv2; varying vec2 vUv3; void main() { vec2 uv = position.xy * 0.5 + 0.5; vUv = uv; vec2 dUv = (texelSize * vec2(kernel) + halfTexelSize) * scale; vUv0 = vec2(uv.x - dUv.x, uv.y + dUv.y); vUv1 = vec2(uv.x + dUv.x, uv.y + dUv.y); vUv2 = vec2(uv.x + dUv.x, uv.y - dUv.y); vUv3 = vec2(uv.x - dUv.x, uv.y - dUv.y); gl_Position = vec4(position.xy, 1.0, 1.0); }`, blending: NoBlending, depthWrite: false, depthTest: false }); this.toneMapped = false; this.setTexelSize(texelSize.x, texelSize.y); this.kernel = new Float32Array([0, 1, 2, 2, 3]); } setTexelSize(x, y) { this.uniforms.texelSize.value.set(x, y); this.uniforms.halfTexelSize.value.set(x, y).multiplyScalar(0.5); } setResolution(resolution) { this.uniforms.resolution.value.copy(resolution); } }; // node_modules/@react-three/drei/materials/BlurPass.js var BlurPass = class { constructor({ gl, resolution, width = 500, height = 500, minDepthThreshold = 0, maxDepthThreshold = 1, depthScale = 0, depthToBlurRatioBias = 0.25 }) { this.renderToScreen = false; this.renderTargetA = new WebGLRenderTarget(resolution, resolution, { minFilter: LinearFilter, magFilter: LinearFilter, stencilBuffer: false, depthBuffer: false, type: HalfFloatType }); this.renderTargetB = this.renderTargetA.clone(); this.convolutionMaterial = new ConvolutionMaterial(); this.convolutionMaterial.setTexelSize(1 / width, 1 / height); this.convolutionMaterial.setResolution(new Vector2(width, height)); this.scene = new Scene(); this.camera = new Camera(); this.convolutionMaterial.uniforms.minDepthThreshold.value = minDepthThreshold; this.convolutionMaterial.uniforms.maxDepthThreshold.value = maxDepthThreshold; this.convolutionMaterial.uniforms.depthScale.value = depthScale; this.convolutionMaterial.uniforms.depthToBlurRatioBias.value = depthToBlurRatioBias; this.convolutionMaterial.defines.USE_DEPTH = depthScale > 0; const vertices = new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0]); const uvs = new Float32Array([0, 0, 2, 0, 0, 2]); const geometry3 = new BufferGeometry(); geometry3.setAttribute("position", new BufferAttribute(vertices, 3)); geometry3.setAttribute("uv", new BufferAttribute(uvs, 2)); this.screen = new Mesh(geometry3, this.convolutionMaterial); this.screen.frustumCulled = false; this.scene.add(this.screen); } render(renderer, inputBuffer, outputBuffer) { const scene = this.scene; const camera = this.camera; const renderTargetA = this.renderTargetA; const renderTargetB = this.renderTargetB; let material = this.convolutionMaterial; let uniforms = material.uniforms; uniforms.depthBuffer.value = inputBuffer.depthTexture; const kernel = material.kernel; let lastRT = inputBuffer; let destRT; let i4, l2; for (i4 = 0, l2 = kernel.length - 1; i4 < l2; ++i4) { destRT = (i4 & 1) === 0 ? renderTargetA : renderTargetB; uniforms.kernel.value = kernel[i4]; uniforms.inputBuffer.value = lastRT.texture; renderer.setRenderTarget(destRT); renderer.render(scene, camera); lastRT = destRT; } uniforms.kernel.value = kernel[i4]; uniforms.inputBuffer.value = lastRT.texture; renderer.setRenderTarget(this.renderToScreen ? null : outputBuffer); renderer.render(scene, camera); } }; // node_modules/@react-three/drei/materials/MeshReflectorMaterial.js var MeshReflectorMaterial = class extends MeshStandardMaterial { constructor(parameters = {}) { super(parameters); this._tDepth = { value: null }; this._distortionMap = { value: null }; this._tDiffuse = { value: null }; this._tDiffuseBlur = { value: null }; this._textureMatrix = { value: null }; this._hasBlur = { value: false }; this._mirror = { value: 0 }; this._mixBlur = { value: 0 }; this._blurStrength = { value: 0.5 }; this._minDepthThreshold = { value: 0.9 }; this._maxDepthThreshold = { value: 1 }; this._depthScale = { value: 0 }; this._depthToBlurRatioBias = { value: 0.25 }; this._distortion = { value: 1 }; this._mixContrast = { value: 1 }; this.setValues(parameters); } onBeforeCompile(shader) { var _shader$defines; if (!((_shader$defines = shader.defines) != null && _shader$defines.USE_UV)) { shader.defines.USE_UV = ""; } shader.uniforms.hasBlur = this._hasBlur; shader.uniforms.tDiffuse = this._tDiffuse; shader.uniforms.tDepth = this._tDepth; shader.uniforms.distortionMap = this._distortionMap; shader.uniforms.tDiffuseBlur = this._tDiffuseBlur; shader.uniforms.textureMatrix = this._textureMatrix; shader.uniforms.mirror = this._mirror; shader.uniforms.mixBlur = this._mixBlur; shader.uniforms.mixStrength = this._blurStrength; shader.uniforms.minDepthThreshold = this._minDepthThreshold; shader.uniforms.maxDepthThreshold = this._maxDepthThreshold; shader.uniforms.depthScale = this._depthScale; shader.uniforms.depthToBlurRatioBias = this._depthToBlurRatioBias; shader.uniforms.distortion = this._distortion; shader.uniforms.mixContrast = this._mixContrast; shader.vertexShader = ` uniform mat4 textureMatrix; varying vec4 my_vUv; ${shader.vertexShader}`; shader.vertexShader = shader.vertexShader.replace("#include ", `#include my_vUv = textureMatrix * vec4( position, 1.0 ); gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );`); shader.fragmentShader = ` uniform sampler2D tDiffuse; uniform sampler2D tDiffuseBlur; uniform sampler2D tDepth; uniform sampler2D distortionMap; uniform float distortion; uniform float cameraNear; uniform float cameraFar; uniform bool hasBlur; uniform float mixBlur; uniform float mirror; uniform float mixStrength; uniform float minDepthThreshold; uniform float maxDepthThreshold; uniform float mixContrast; uniform float depthScale; uniform float depthToBlurRatioBias; varying vec4 my_vUv; ${shader.fragmentShader}`; shader.fragmentShader = shader.fragmentShader.replace("#include ", `#include float distortionFactor = 0.0; #ifdef USE_DISTORTION distortionFactor = texture2D(distortionMap, vUv).r * distortion; #endif vec4 new_vUv = my_vUv; new_vUv.x += distortionFactor; new_vUv.y += distortionFactor; vec4 base = texture2DProj(tDiffuse, new_vUv); vec4 blur = texture2DProj(tDiffuseBlur, new_vUv); vec4 merge = base; #ifdef USE_NORMALMAP vec2 normal_uv = vec2(0.0); vec4 normalColor = texture2D(normalMap, vUv * normalScale); vec3 my_normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) ); vec3 coord = new_vUv.xyz / new_vUv.w; normal_uv = coord.xy + coord.z * my_normal.xz * 0.05; vec4 base_normal = texture2D(tDiffuse, normal_uv); vec4 blur_normal = texture2D(tDiffuseBlur, normal_uv); merge = base_normal; blur = blur_normal; #endif float depthFactor = 0.0001; float blurFactor = 0.0; #ifdef USE_DEPTH vec4 depth = texture2DProj(tDepth, new_vUv); depthFactor = smoothstep(minDepthThreshold, maxDepthThreshold, 1.0-(depth.r * depth.a)); depthFactor *= depthScale; depthFactor = max(0.0001, min(1.0, depthFactor)); #ifdef USE_BLUR blur = blur * min(1.0, depthFactor + depthToBlurRatioBias); merge = merge * min(1.0, depthFactor + 0.5); #else merge = merge * depthFactor; #endif #endif float reflectorRoughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 reflectorTexelRoughness = texture2D( roughnessMap, vUv ); reflectorRoughnessFactor *= reflectorTexelRoughness.g; #endif #ifdef USE_BLUR blurFactor = min(1.0, mixBlur * reflectorRoughnessFactor); merge = mix(merge, blur, blurFactor); #endif vec4 newMerge = vec4(0.0, 0.0, 0.0, 1.0); newMerge.r = (merge.r - 0.5) * mixContrast + 0.5; newMerge.g = (merge.g - 0.5) * mixContrast + 0.5; newMerge.b = (merge.b - 0.5) * mixContrast + 0.5; diffuseColor.rgb = diffuseColor.rgb * ((1.0 - min(1.0, mirror)) + newMerge.rgb * mixStrength); `); } get tDiffuse() { return this._tDiffuse.value; } set tDiffuse(v5) { this._tDiffuse.value = v5; } get tDepth() { return this._tDepth.value; } set tDepth(v5) { this._tDepth.value = v5; } get distortionMap() { return this._distortionMap.value; } set distortionMap(v5) { this._distortionMap.value = v5; } get tDiffuseBlur() { return this._tDiffuseBlur.value; } set tDiffuseBlur(v5) { this._tDiffuseBlur.value = v5; } get textureMatrix() { return this._textureMatrix.value; } set textureMatrix(v5) { this._textureMatrix.value = v5; } get hasBlur() { return this._hasBlur.value; } set hasBlur(v5) { this._hasBlur.value = v5; } get mirror() { return this._mirror.value; } set mirror(v5) { this._mirror.value = v5; } get mixBlur() { return this._mixBlur.value; } set mixBlur(v5) { this._mixBlur.value = v5; } get mixStrength() { return this._blurStrength.value; } set mixStrength(v5) { this._blurStrength.value = v5; } get minDepthThreshold() { return this._minDepthThreshold.value; } set minDepthThreshold(v5) { this._minDepthThreshold.value = v5; } get maxDepthThreshold() { return this._maxDepthThreshold.value; } set maxDepthThreshold(v5) { this._maxDepthThreshold.value = v5; } get depthScale() { return this._depthScale.value; } set depthScale(v5) { this._depthScale.value = v5; } get depthToBlurRatioBias() { return this._depthToBlurRatioBias.value; } set depthToBlurRatioBias(v5) { this._depthToBlurRatioBias.value = v5; } get distortion() { return this._distortion.value; } set distortion(v5) { this._distortion.value = v5; } get mixContrast() { return this._mixContrast.value; } set mixContrast(v5) { this._mixContrast.value = v5; } }; // node_modules/@react-three/drei/core/MeshReflectorMaterial.js var MeshReflectorMaterial2 = React85.forwardRef(({ mixBlur = 0, mixStrength = 1, resolution = 256, blur = [0, 0], minDepthThreshold = 0.9, maxDepthThreshold = 1, depthScale = 0, depthToBlurRatioBias = 0.25, mirror = 0, distortion = 1, mixContrast = 1, distortionMap, reflectorOffset = 0, ...props }, ref) => { extend({ MeshReflectorMaterialImpl: MeshReflectorMaterial }); const gl = useThree(({ gl: gl2 }) => gl2); const camera = useThree(({ camera: camera2 }) => camera2); const scene = useThree(({ scene: scene2 }) => scene2); blur = Array.isArray(blur) ? blur : [blur, blur]; const hasBlur = blur[0] + blur[1] > 0; const blurX = blur[0]; const blurY = blur[1]; const materialRef = React85.useRef(null); React85.useImperativeHandle(ref, () => materialRef.current, []); const [reflectorPlane] = React85.useState(() => new Plane()); const [normal2] = React85.useState(() => new Vector3()); const [reflectorWorldPosition] = React85.useState(() => new Vector3()); const [cameraWorldPosition] = React85.useState(() => new Vector3()); const [rotationMatrix2] = React85.useState(() => new Matrix4()); const [lookAtPosition] = React85.useState(() => new Vector3(0, 0, -1)); const [clipPlane] = React85.useState(() => new Vector4()); const [view] = React85.useState(() => new Vector3()); const [target2] = React85.useState(() => new Vector3()); const [q] = React85.useState(() => new Vector4()); const [textureMatrix] = React85.useState(() => new Matrix4()); const [virtualCamera] = React85.useState(() => new PerspectiveCamera()); const beforeRender = React85.useCallback(() => { var _materialRef$current; const parent = materialRef.current.parent || ((_materialRef$current = materialRef.current) == null || (_materialRef$current = _materialRef$current.__r3f.parent) == null ? void 0 : _materialRef$current.object); if (!parent) return; reflectorWorldPosition.setFromMatrixPosition(parent.matrixWorld); cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); rotationMatrix2.extractRotation(parent.matrixWorld); normal2.set(0, 0, 1); normal2.applyMatrix4(rotationMatrix2); reflectorWorldPosition.addScaledVector(normal2, reflectorOffset); view.subVectors(reflectorWorldPosition, cameraWorldPosition); if (view.dot(normal2) > 0) return; view.reflect(normal2).negate(); view.add(reflectorWorldPosition); rotationMatrix2.extractRotation(camera.matrixWorld); lookAtPosition.set(0, 0, -1); lookAtPosition.applyMatrix4(rotationMatrix2); lookAtPosition.add(cameraWorldPosition); target2.subVectors(reflectorWorldPosition, lookAtPosition); target2.reflect(normal2).negate(); target2.add(reflectorWorldPosition); virtualCamera.position.copy(view); virtualCamera.up.set(0, 1, 0); virtualCamera.up.applyMatrix4(rotationMatrix2); virtualCamera.up.reflect(normal2); virtualCamera.lookAt(target2); 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(parent.matrixWorld); reflectorPlane.setFromNormalAndCoplanarPoint(normal2, reflectorWorldPosition); reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse); clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant); const projectionMatrix = virtualCamera.projectionMatrix; q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; q.z = -1; q.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; clipPlane.multiplyScalar(2 / clipPlane.dot(q)); projectionMatrix.elements[2] = clipPlane.x; projectionMatrix.elements[6] = clipPlane.y; projectionMatrix.elements[10] = clipPlane.z + 1; projectionMatrix.elements[14] = clipPlane.w; }, [camera, reflectorOffset]); const [fbo1, fbo2, blurpass, reflectorProps] = React85.useMemo(() => { const parameters = { minFilter: LinearFilter, magFilter: LinearFilter, type: HalfFloatType }; const fbo12 = new WebGLRenderTarget(resolution, resolution, parameters); fbo12.depthBuffer = true; fbo12.depthTexture = new DepthTexture(resolution, resolution); fbo12.depthTexture.format = DepthFormat; fbo12.depthTexture.type = UnsignedShortType; const fbo22 = new WebGLRenderTarget(resolution, resolution, parameters); const blurpass2 = new BlurPass({ gl, resolution, width: blurX, height: blurY, minDepthThreshold, maxDepthThreshold, depthScale, depthToBlurRatioBias }); const reflectorProps2 = { mirror, textureMatrix, mixBlur, tDiffuse: fbo12.texture, tDepth: fbo12.depthTexture, tDiffuseBlur: fbo22.texture, hasBlur, mixStrength, minDepthThreshold, maxDepthThreshold, depthScale, depthToBlurRatioBias, distortion, distortionMap, mixContrast, "defines-USE_BLUR": hasBlur ? "" : void 0, "defines-USE_DEPTH": depthScale > 0 ? "" : void 0, "defines-USE_DISTORTION": distortionMap ? "" : void 0 }; return [fbo12, fbo22, blurpass2, reflectorProps2]; }, [gl, blurX, blurY, textureMatrix, resolution, mirror, hasBlur, mixBlur, mixStrength, minDepthThreshold, maxDepthThreshold, depthScale, depthToBlurRatioBias, distortion, distortionMap, mixContrast]); useFrame(() => { var _materialRef$current2; const parent = materialRef.current.parent || ((_materialRef$current2 = materialRef.current) == null || (_materialRef$current2 = _materialRef$current2.__r3f.parent) == null ? void 0 : _materialRef$current2.object); if (!parent) return; parent.visible = false; const currentXrEnabled = gl.xr.enabled; const currentShadowAutoUpdate = gl.shadowMap.autoUpdate; beforeRender(); gl.xr.enabled = false; gl.shadowMap.autoUpdate = false; gl.setRenderTarget(fbo1); gl.state.buffers.depth.setMask(true); if (!gl.autoClear) gl.clear(); gl.render(scene, virtualCamera); if (hasBlur) blurpass.render(gl, fbo1, fbo2); gl.xr.enabled = currentXrEnabled; gl.shadowMap.autoUpdate = currentShadowAutoUpdate; parent.visible = true; gl.setRenderTarget(null); }); return React85.createElement("meshReflectorMaterialImpl", _extends({ attach: "material", key: "key" + reflectorProps["defines-USE_BLUR"] + reflectorProps["defines-USE_DEPTH"] + reflectorProps["defines-USE_DISTORTION"], ref: materialRef }, reflectorProps, props)); }); // node_modules/@react-three/drei/core/MeshRefractionMaterial.js var React86 = __toESM(require_react()); var import_react17 = __toESM(require_react()); // node_modules/@react-three/drei/materials/MeshRefractionMaterial.js var MeshRefractionMaterial = shaderMaterial( { envMap: null, bounces: 3, ior: 2.4, correctMips: true, aberrationStrength: 0.01, fresnel: 0, bvh: new MeshBVHUniformStruct(), color: new Color("white"), opacity: 1, resolution: new Vector2(), viewMatrixInverse: new Matrix4(), projectionMatrixInverse: new Matrix4() }, /*glsl*/ ` uniform mat4 viewMatrixInverse; varying vec3 vWorldPosition; varying vec3 vNormal; varying mat4 vModelMatrixInverse; #include void main() { #include vec4 transformedNormal = vec4(normal, 0.0); vec4 transformedPosition = vec4(position, 1.0); #ifdef USE_INSTANCING transformedNormal = instanceMatrix * transformedNormal; transformedPosition = instanceMatrix * transformedPosition; #endif #ifdef USE_INSTANCING vModelMatrixInverse = inverse(modelMatrix * instanceMatrix); #else vModelMatrixInverse = inverse(modelMatrix); #endif vWorldPosition = (modelMatrix * transformedPosition).xyz; vNormal = normalize((viewMatrixInverse * vec4(normalMatrix * transformedNormal.xyz, 0.0)).xyz); gl_Position = projectionMatrix * viewMatrix * modelMatrix * transformedPosition; }`, /*glsl*/ ` #define ENVMAP_TYPE_CUBE_UV precision highp isampler2D; precision highp usampler2D; varying vec3 vWorldPosition; varying vec3 vNormal; varying mat4 vModelMatrixInverse; #include #ifdef ENVMAP_TYPE_CUBEM uniform samplerCube envMap; #else uniform sampler2D envMap; #endif uniform float bounces; ${shaderStructs} ${shaderIntersectFunction} uniform BVH bvh; uniform float ior; uniform bool correctMips; uniform vec2 resolution; uniform float fresnel; uniform mat4 modelMatrix; uniform mat4 projectionMatrixInverse; uniform mat4 viewMatrixInverse; uniform float aberrationStrength; uniform vec3 color; uniform float opacity; float fresnelFunc(vec3 viewDirection, vec3 worldNormal) { return pow( 1.0 + dot( viewDirection, worldNormal), 10.0 ); } vec3 totalInternalReflection(vec3 ro, vec3 rd, vec3 normal, float ior, mat4 modelMatrixInverse) { vec3 rayOrigin = ro; vec3 rayDirection = rd; rayDirection = refract(rayDirection, normal, 1.0 / ior); rayOrigin = vWorldPosition + rayDirection * 0.001; rayOrigin = (modelMatrixInverse * vec4(rayOrigin, 1.0)).xyz; rayDirection = normalize((modelMatrixInverse * vec4(rayDirection, 0.0)).xyz); for(float i = 0.0; i < bounces; i++) { uvec4 faceIndices = uvec4( 0u ); vec3 faceNormal = vec3( 0.0, 0.0, 1.0 ); vec3 barycoord = vec3( 0.0 ); float side = 1.0; float dist = 0.0; bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ); vec3 hitPos = rayOrigin + rayDirection * max(dist - 0.001, 0.0); vec3 tempDir = refract(rayDirection, faceNormal, ior); if (length(tempDir) != 0.0) { rayDirection = tempDir; break; } rayDirection = reflect(rayDirection, faceNormal); rayOrigin = hitPos + rayDirection * 0.01; } rayDirection = normalize((modelMatrix * vec4(rayDirection, 0.0)).xyz); return rayDirection; } #include #include #ifdef ENVMAP_TYPE_CUBEM vec4 textureGradient(samplerCube envMap, vec3 rayDirection, vec3 directionCamPerfect) { return textureGrad(envMap, rayDirection, dFdx(correctMips ? directionCamPerfect: rayDirection), dFdy(correctMips ? directionCamPerfect: rayDirection)); } #else vec4 textureGradient(sampler2D envMap, vec3 rayDirection, vec3 directionCamPerfect) { vec2 uvv = equirectUv( rayDirection ); vec2 smoothUv = equirectUv( directionCamPerfect ); return textureGrad(envMap, uvv, dFdx(correctMips ? smoothUv : uvv), dFdy(correctMips ? smoothUv : uvv)); } #endif void main() { vec2 uv = gl_FragCoord.xy / resolution; vec3 directionCamPerfect = (projectionMatrixInverse * vec4(uv * 2.0 - 1.0, 0.0, 1.0)).xyz; directionCamPerfect = (viewMatrixInverse * vec4(directionCamPerfect, 0.0)).xyz; directionCamPerfect = normalize(directionCamPerfect); vec3 normal = vNormal; vec3 rayOrigin = cameraPosition; vec3 rayDirection = normalize(vWorldPosition - cameraPosition); vec4 diffuseColor = vec4(color, opacity); #include #ifdef CHROMATIC_ABERRATIONS vec3 rayDirectionG = totalInternalReflection(rayOrigin, rayDirection, normal, max(ior, 1.0), vModelMatrixInverse); #ifdef FAST_CHROMA vec3 rayDirectionR = normalize(rayDirectionG + 1.0 * vec3(aberrationStrength / 2.0)); vec3 rayDirectionB = normalize(rayDirectionG - 1.0 * vec3(aberrationStrength / 2.0)); #else vec3 rayDirectionR = totalInternalReflection(rayOrigin, rayDirection, normal, max(ior * (1.0 - aberrationStrength), 1.0), vModelMatrixInverse); vec3 rayDirectionB = totalInternalReflection(rayOrigin, rayDirection, normal, max(ior * (1.0 + aberrationStrength), 1.0), vModelMatrixInverse); #endif float finalColorR = textureGradient(envMap, rayDirectionR, directionCamPerfect).r; float finalColorG = textureGradient(envMap, rayDirectionG, directionCamPerfect).g; float finalColorB = textureGradient(envMap, rayDirectionB, directionCamPerfect).b; diffuseColor.rgb *= vec3(finalColorR, finalColorG, finalColorB); #else rayDirection = totalInternalReflection(rayOrigin, rayDirection, normal, max(ior, 1.0), vModelMatrixInverse); diffuseColor.rgb *= textureGradient(envMap, rayDirection, directionCamPerfect).rgb; #endif vec3 viewDirection = normalize(vWorldPosition - cameraPosition); float nFresnel = fresnelFunc(viewDirection, normal) * fresnel; gl_FragColor = vec4(mix(diffuseColor.rgb, vec3(1.0), nFresnel), diffuseColor.a); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }` ); // node_modules/@react-three/drei/core/MeshRefractionMaterial.js var isCubeTexture2 = (def) => def && def.isCubeTexture; function MeshRefractionMaterial2({ aberrationStrength = 0, fastChroma = true, envMap, ...props }) { extend({ MeshRefractionMaterial }); const material = (0, import_react17.useRef)(null); const { size: size2 } = useThree(); const defines = (0, import_react17.useMemo)(() => { var _ref, _envMap$image$; const temp5 = {}; const isCubeMap = isCubeTexture2(envMap); const w = (_ref = isCubeMap ? (_envMap$image$ = envMap.image[0]) == null ? void 0 : _envMap$image$.width : envMap.image.width) !== null && _ref !== void 0 ? _ref : 1024; const cubeSize = w / 4; const _lodMax = Math.floor(Math.log2(cubeSize)); const _cubeSize = Math.pow(2, _lodMax); const width = 3 * Math.max(_cubeSize, 16 * 7); const height = 4 * _cubeSize; if (isCubeMap) temp5.ENVMAP_TYPE_CUBEM = ""; temp5.CUBEUV_TEXEL_WIDTH = `${1 / width}`; temp5.CUBEUV_TEXEL_HEIGHT = `${1 / height}`; temp5.CUBEUV_MAX_MIP = `${_lodMax}.0`; if (aberrationStrength > 0) temp5.CHROMATIC_ABERRATIONS = ""; if (fastChroma) temp5.FAST_CHROMA = ""; return temp5; }, [aberrationStrength, fastChroma]); (0, import_react17.useLayoutEffect)(() => { var _material$current; const geometry3 = (_material$current = material.current) == null || (_material$current = _material$current.__r3f) == null || (_material$current = _material$current.parent) == null || (_material$current = _material$current.object) == null ? void 0 : _material$current.geometry; if (geometry3) { material.current.bvh = new MeshBVHUniformStruct(); material.current.bvh.updateFrom(new MeshBVH(geometry3.clone().toNonIndexed(), { strategy: SAH })); } }, []); useFrame(({ camera }) => { material.current.viewMatrixInverse = camera.matrixWorld; material.current.projectionMatrixInverse = camera.projectionMatrixInverse; }); return React86.createElement("meshRefractionMaterial", _extends({ // @ts-ignore key: JSON.stringify(defines), defines, ref: material, resolution: [size2.width, size2.height], aberrationStrength, envMap }, props)); } // node_modules/@react-three/drei/core/MeshTransmissionMaterial.js var React87 = __toESM(require_react()); // node_modules/@react-three/drei/materials/DiscardMaterial.js var DiscardMaterial = shaderMaterial({}, "void main() { }", "void main() { gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); discard; }"); // node_modules/@react-three/drei/core/MeshTransmissionMaterial.js var MeshTransmissionMaterialImpl = class extends MeshPhysicalMaterial { constructor(samples = 6, transmissionSampler = false) { super(); this.uniforms = { chromaticAberration: { value: 0.05 }, // Transmission must always be 0, unless transmissionSampler is being used transmission: { value: 0 }, // Instead a workaround is used, see below for reasons why _transmission: { value: 1 }, transmissionMap: { value: null }, // Roughness is 1 in THREE.MeshPhysicalMaterial but it makes little sense in a transmission material roughness: { value: 0 }, thickness: { value: 0 }, thicknessMap: { value: null }, attenuationDistance: { value: Infinity }, attenuationColor: { value: new Color("white") }, anisotropicBlur: { value: 0.1 }, time: { value: 0 }, distortion: { value: 0 }, distortionScale: { value: 0.5 }, temporalDistortion: { value: 0 }, buffer: { value: null } }; this.onBeforeCompile = (shader) => { shader.uniforms = { ...shader.uniforms, ...this.uniforms }; if (this.anisotropy > 0) shader.defines.USE_ANISOTROPY = ""; if (transmissionSampler) shader.defines.USE_SAMPLER = ""; else shader.defines.USE_TRANSMISSION = ""; shader.fragmentShader = /*glsl*/ ` uniform float chromaticAberration; uniform float anisotropicBlur; uniform float time; uniform float distortion; uniform float distortionScale; uniform float temporalDistortion; uniform sampler2D buffer; vec3 random3(vec3 c) { float j = 4096.0*sin(dot(c,vec3(17.0, 59.4, 15.0))); vec3 r; r.z = fract(512.0*j); j *= .125; r.x = fract(512.0*j); j *= .125; r.y = fract(512.0*j); return r-0.5; } uint hash( uint x ) { x += ( x << 10u ); x ^= ( x >> 6u ); x += ( x << 3u ); x ^= ( x >> 11u ); x += ( x << 15u ); return x; } // Compound versions of the hashing algorithm I whipped together. uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y) ); } uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ); } uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); } // Construct a float with half-open range [0:1] using low 23 bits. // All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0. float floatConstruct( uint m ) { const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask const uint ieeeOne = 0x3F800000u; // 1.0 in IEEE binary32 m &= ieeeMantissa; // Keep only mantissa bits (fractional part) m |= ieeeOne; // Add fractional part to 1.0 float f = uintBitsToFloat( m ); // Range [1:2] return f - 1.0; // Range [0:1] } // Pseudo-random value in half-open range [0:1]. float randomBase( float x ) { return floatConstruct(hash(floatBitsToUint(x))); } float randomBase( vec2 v ) { return floatConstruct(hash(floatBitsToUint(v))); } float randomBase( vec3 v ) { return floatConstruct(hash(floatBitsToUint(v))); } float randomBase( vec4 v ) { return floatConstruct(hash(floatBitsToUint(v))); } float rand(float seed) { float result = randomBase(vec3(gl_FragCoord.xy, seed)); return result; } const float F3 = 0.3333333; const float G3 = 0.1666667; float snoise(vec3 p) { vec3 s = floor(p + dot(p, vec3(F3))); vec3 x = p - s + dot(s, vec3(G3)); vec3 e = step(vec3(0.0), x - x.yzx); vec3 i1 = e*(1.0 - e.zxy); vec3 i2 = 1.0 - e.zxy*(1.0 - e); vec3 x1 = x - i1 + G3; vec3 x2 = x - i2 + 2.0*G3; vec3 x3 = x - 1.0 + 3.0*G3; vec4 w, d; w.x = dot(x, x); w.y = dot(x1, x1); w.z = dot(x2, x2); w.w = dot(x3, x3); w = max(0.6 - w, 0.0); d.x = dot(random3(s), x); d.y = dot(random3(s + i1), x1); d.z = dot(random3(s + i2), x2); d.w = dot(random3(s + 1.0), x3); w *= w; w *= w; d *= w; return dot(d, vec4(52.0)); } float snoiseFractal(vec3 m) { return 0.5333333* snoise(m) +0.2666667* snoise(2.0*m) +0.1333333* snoise(4.0*m) +0.0666667* snoise(8.0*m); } ` + shader.fragmentShader; shader.fragmentShader = shader.fragmentShader.replace( "#include ", /*glsl*/ ` #ifdef USE_TRANSMISSION // Transmission code is based on glTF-Sampler-Viewer // https://github.com/KhronosGroup/glTF-Sample-Viewer uniform float _transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { // Direction of refracted light. vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); // Compute rotation-independant scaling of the model matrix. vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); // The thickness is specified in local space. return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and // an IOR of 1.5 results in the default amount of microfacet refraction. return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); #ifdef USE_SAMPLER #ifdef texture2DLodEXT return texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod); #else return texture2D(transmissionSamplerMap, fragCoord.xy, framebufferLod); #endif #else return texture2D(buffer, fragCoord.xy); #endif } vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all. return radiance; } else { // Compute light attenuation using Beer's law. vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); // Beer's law return transmittance * radiance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; // Project refracted vector on the framebuffer, while mapping to normalized device coordinates. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; // Sample framebuffer to get pixel the refracted ray hits. vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance ); // Get the specular component. vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a ); } #endif ` ); shader.fragmentShader = shader.fragmentShader.replace( "#include ", /*glsl*/ ` // Improve the refraction to use the world pos material.transmission = _transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vUv ).g; #endif vec3 pos = vWorldPosition; float runningSeed = 0.0; vec3 v = normalize( cameraPosition - pos ); vec3 n = inverseTransformDirection( normal, viewMatrix ); vec3 transmission = vec3(0.0); float transmissionR, transmissionB, transmissionG; float randomCoords = rand(runningSeed++); float thickness_smear = thickness * max(pow(roughnessFactor, 0.33), anisotropicBlur); vec3 distortionNormal = vec3(0.0); vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion; if (distortion > 0.0) { distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset))); } for (float i = 0.0; i < ${samples}.0; i ++) { vec3 sampleNorm = normalize(n + roughnessFactor * roughnessFactor * 2.0 * normalize(vec3(rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5)) * pow(rand(runningSeed++), 0.33) + distortionNormal); transmissionR = getIBLVolumeRefraction( sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness + thickness_smear * (i + randomCoords) / float(${samples}), material.attenuationColor, material.attenuationDistance ).r; transmissionG = getIBLVolumeRefraction( sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + chromaticAberration * (i + randomCoords) / float(${samples})) , material.thickness + thickness_smear * (i + randomCoords) / float(${samples}), material.attenuationColor, material.attenuationDistance ).g; transmissionB = getIBLVolumeRefraction( sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * chromaticAberration * (i + randomCoords) / float(${samples})), material.thickness + thickness_smear * (i + randomCoords) / float(${samples}), material.attenuationColor, material.attenuationDistance ).b; transmission.r += transmissionR; transmission.g += transmissionG; transmission.b += transmissionB; } transmission /= ${samples}.0; totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission ); ` ); }; Object.keys(this.uniforms).forEach((name) => Object.defineProperty(this, name, { get: () => this.uniforms[name].value, set: (v5) => this.uniforms[name].value = v5 })); } }; var MeshTransmissionMaterial = React87.forwardRef(({ buffer: buffer2, transmissionSampler = false, backside = false, side = FrontSide, transmission = 1, thickness = 0, backsideThickness = 0, backsideEnvMapIntensity = 1, samples = 10, resolution, backsideResolution, background, anisotropy, anisotropicBlur, ...props }, fref) => { extend({ MeshTransmissionMaterial: MeshTransmissionMaterialImpl }); const ref = React87.useRef(null); const [discardMaterial] = React87.useState(() => new DiscardMaterial()); const fboBack = useFBO(backsideResolution || resolution); const fboMain = useFBO(resolution); let oldBg; let oldEnvMapIntensity; let oldTone; let parent; useFrame((state) => { ref.current.time = state.clock.elapsedTime; if (ref.current.buffer === fboMain.texture && !transmissionSampler) { var _r3f$parent; parent = (_r3f$parent = ref.current.__r3f.parent) == null ? void 0 : _r3f$parent.object; if (parent) { oldTone = state.gl.toneMapping; oldBg = state.scene.background; oldEnvMapIntensity = ref.current.envMapIntensity; state.gl.toneMapping = NoToneMapping; if (background) state.scene.background = background; parent.material = discardMaterial; if (backside) { state.gl.setRenderTarget(fboBack); state.gl.render(state.scene, state.camera); parent.material = ref.current; parent.material.buffer = fboBack.texture; parent.material.thickness = backsideThickness; parent.material.side = BackSide; parent.material.envMapIntensity = backsideEnvMapIntensity; } state.gl.setRenderTarget(fboMain); state.gl.render(state.scene, state.camera); parent.material = ref.current; parent.material.thickness = thickness; parent.material.side = side; parent.material.buffer = fboMain.texture; parent.material.envMapIntensity = oldEnvMapIntensity; state.scene.background = oldBg; state.gl.setRenderTarget(null); state.gl.toneMapping = oldTone; } } }); React87.useImperativeHandle(fref, () => ref.current, []); return React87.createElement("meshTransmissionMaterial", _extends({ // Samples must re-compile the shader so we memoize it args: [samples, transmissionSampler], ref }, props, { buffer: buffer2 || fboMain.texture, _transmission: transmission, anisotropicBlur: anisotropicBlur !== null && anisotropicBlur !== void 0 ? anisotropicBlur : anisotropy, transmission: transmissionSampler ? transmission : 0, thickness, side })); }); // node_modules/@react-three/drei/core/MeshDiscardMaterial.js var React88 = __toESM(require_react()); var MeshDiscardMaterial = React88.forwardRef((props, fref) => { extend({ DiscardMaterialImpl: DiscardMaterial }); return React88.createElement("discardMaterialImpl", _extends({ ref: fref }, props)); }); // node_modules/@react-three/drei/core/MultiMaterial.js var React89 = __toESM(require_react()); function MultiMaterial(props) { const group = React89.useRef(null); React89.useLayoutEffect(() => { const parent = group.current.parent; const geometry3 = parent == null ? void 0 : parent.geometry; if (geometry3) { const oldMaterial = parent.material; parent.material = group.current.__r3f.children.map((instance2) => instance2.object); const oldGroups = [...geometry3.groups]; geometry3.clearGroups(); parent.material.forEach((material, index2) => { if (index2 < parent.material.length - 1) material.depthWrite = false; geometry3.addGroup(0, Infinity, index2); }); return () => { parent.material = oldMaterial; geometry3.groups = oldGroups; }; } }); return React89.createElement("group", _extends({ ref: group }, props)); } // node_modules/@react-three/drei/core/PointMaterial.js var React90 = __toESM(require_react()); var opaque_fragment = version2 >= 154 ? "opaque_fragment" : "output_fragment"; var PointMaterialImpl = class extends PointsMaterial { constructor(props) { super(props); this.onBeforeCompile = (shader, renderer) => { const { isWebGL2 } = renderer.capabilities; shader.fragmentShader = shader.fragmentShader.replace(`#include <${opaque_fragment}>`, ` ${!isWebGL2 ? `#extension GL_OES_standard_derivatives : enable #include <${opaque_fragment}>` : `#include <${opaque_fragment}>`} vec2 cxy = 2.0 * gl_PointCoord - 1.0; float r = dot(cxy, cxy); float delta = fwidth(r); float mask = 1.0 - smoothstep(1.0 - delta, 1.0 + delta, r); gl_FragColor = vec4(gl_FragColor.rgb, mask * gl_FragColor.a ); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> `); }; } }; var PointMaterial = React90.forwardRef((props, ref) => { const [material] = React90.useState(() => new PointMaterialImpl(null)); return React90.createElement("primitive", _extends({}, props, { object: material, ref, attach: "material" })); }); // node_modules/@react-three/drei/core/softShadows.js var React91 = __toESM(require_react()); var pcss = ({ focus = 0, size: size2 = 25, samples = 10 } = {}) => ` #define PENUMBRA_FILTER_SIZE float(${size2}) #define RGB_NOISE_FUNCTION(uv) (randRGB(uv)) vec3 randRGB(vec2 uv) { return vec3( fract(sin(dot(uv, vec2(12.75613, 38.12123))) * 13234.76575), fract(sin(dot(uv, vec2(19.45531, 58.46547))) * 43678.23431), fract(sin(dot(uv, vec2(23.67817, 78.23121))) * 93567.23423) ); } vec3 lowPassRandRGB(vec2 uv) { // 3x3 convolution (average) // can be implemented as separable with an extra buffer for a total of 6 samples instead of 9 vec3 result = vec3(0); result += RGB_NOISE_FUNCTION(uv + vec2(-1.0, -1.0)); result += RGB_NOISE_FUNCTION(uv + vec2(-1.0, 0.0)); result += RGB_NOISE_FUNCTION(uv + vec2(-1.0, +1.0)); result += RGB_NOISE_FUNCTION(uv + vec2( 0.0, -1.0)); result += RGB_NOISE_FUNCTION(uv + vec2( 0.0, 0.0)); result += RGB_NOISE_FUNCTION(uv + vec2( 0.0, +1.0)); result += RGB_NOISE_FUNCTION(uv + vec2(+1.0, -1.0)); result += RGB_NOISE_FUNCTION(uv + vec2(+1.0, 0.0)); result += RGB_NOISE_FUNCTION(uv + vec2(+1.0, +1.0)); result *= 0.111111111; // 1.0 / 9.0 return result; } vec3 highPassRandRGB(vec2 uv) { // by subtracting the low-pass signal from the original signal, we're being left with the high-pass signal // hp(x) = x - lp(x) return RGB_NOISE_FUNCTION(uv) - lowPassRandRGB(uv) + 0.5; } vec2 vogelDiskSample(int sampleIndex, int sampleCount, float angle) { const float goldenAngle = 2.399963f; // radians float r = sqrt(float(sampleIndex) + 0.5f) / sqrt(float(sampleCount)); float theta = float(sampleIndex) * goldenAngle + angle; float sine = sin(theta); float cosine = cos(theta); return vec2(cosine, sine) * r; } float penumbraSize( const in float zReceiver, const in float zBlocker ) { // Parallel plane estimation return (zReceiver - zBlocker) / zBlocker; } float findBlocker(sampler2D shadowMap, vec2 uv, float compare, float angle) { float texelSize = 1.0 / float(textureSize(shadowMap, 0).x); float blockerDepthSum = float(${focus}); float blockers = 0.0; int j = 0; vec2 offset = vec2(0.); float depth = 0.; #pragma unroll_loop_start for(int i = 0; i < ${samples}; i ++) { offset = (vogelDiskSample(j, ${samples}, angle) * texelSize) * 2.0 * PENUMBRA_FILTER_SIZE; depth = unpackRGBAToDepth( texture2D( shadowMap, uv + offset)); if (depth < compare) { blockerDepthSum += depth; blockers++; } j++; } #pragma unroll_loop_end if (blockers > 0.0) { return blockerDepthSum / blockers; } return -1.0; } float vogelFilter(sampler2D shadowMap, vec2 uv, float zReceiver, float filterRadius, float angle) { float texelSize = 1.0 / float(textureSize(shadowMap, 0).x); float shadow = 0.0f; int j = 0; vec2 vogelSample = vec2(0.0); vec2 offset = vec2(0.0); #pragma unroll_loop_start for (int i = 0; i < ${samples}; i++) { vogelSample = vogelDiskSample(j, ${samples}, angle) * texelSize; offset = vogelSample * (1.0 + filterRadius * float(${size2})); shadow += step( zReceiver, unpackRGBAToDepth( texture2D( shadowMap, uv + offset ) ) ); j++; } #pragma unroll_loop_end return shadow * 1.0 / ${samples}.0; } float PCSS (sampler2D shadowMap, vec4 coords) { vec2 uv = coords.xy; float zReceiver = coords.z; // Assumed to be eye-space z in this code float angle = highPassRandRGB(gl_FragCoord.xy).r * PI2; float avgBlockerDepth = findBlocker(shadowMap, uv, zReceiver, angle); if (avgBlockerDepth == -1.0) { return 1.0; } float penumbraRatio = penumbraSize(zReceiver, avgBlockerDepth); return vogelFilter(shadowMap, uv, zReceiver, 1.25 * penumbraRatio, angle); }`; function reset(gl, scene, camera) { scene.traverse((object) => { if (object.material) { gl.properties.remove(object.material); object.material.dispose == null || object.material.dispose(); } }); gl.info.programs.length = 0; gl.compile(scene, camera); } function SoftShadows({ focus = 0, samples = 10, size: size2 = 25 }) { const gl = useThree((state) => state.gl); const scene = useThree((state) => state.scene); const camera = useThree((state) => state.camera); React91.useEffect(() => { const original = ShaderChunk.shadowmap_pars_fragment; ShaderChunk.shadowmap_pars_fragment = ShaderChunk.shadowmap_pars_fragment.replace("#ifdef USE_SHADOWMAP", "#ifdef USE_SHADOWMAP\n" + pcss({ size: size2, samples, focus })).replace("#if defined( SHADOWMAP_TYPE_PCF )", "\nreturn PCSS(shadowMap, shadowCoord);\n#if defined( SHADOWMAP_TYPE_PCF )"); reset(gl, scene, camera); return () => { ShaderChunk.shadowmap_pars_fragment = original; reset(gl, scene, camera); }; }, [focus, size2, samples]); return null; } // node_modules/@react-three/drei/core/shapes.js var React92 = __toESM(require_react()); function create2(type, effect) { const El = type + "Geometry"; return React92.forwardRef(({ args, children, ...props }, fref) => { const ref = React92.useRef(null); React92.useImperativeHandle(fref, () => ref.current); React92.useLayoutEffect(() => void (effect == null ? void 0 : effect(ref.current))); return React92.createElement("mesh", _extends({ ref }, props), React92.createElement(El, { attach: "geometry", args }), children); }); } var Box = create2("box"); var Circle = create2("circle"); var Cone = create2("cone"); var Cylinder = create2("cylinder"); var Sphere2 = create2("sphere"); var Plane2 = create2("plane"); var Tube = create2("tube"); var Torus = create2("torus"); var TorusKnot2 = create2("torusKnot"); var Tetrahedron = create2("tetrahedron"); var Ring = create2("ring"); var Polyhedron = create2("polyhedron"); var Icosahedron = create2("icosahedron"); var Octahedron = create2("octahedron"); var Dodecahedron = create2("dodecahedron"); var Extrude = create2("extrude"); var Lathe = create2("lathe"); var Capsule2 = create2("capsule"); var Shape2 = create2("shape", ({ geometry: geometry3 }) => { const pos = geometry3.attributes.position; const b32 = new Box3().setFromBufferAttribute(pos); const b3size = new Vector3(); b32.getSize(b3size); const uv = []; let x = 0, y = 0, u = 0, v5 = 0; for (let i4 = 0; i4 < pos.count; i4++) { x = pos.getX(i4); y = pos.getY(i4); u = (x - b32.min.x) / b3size.x; v5 = (y - b32.min.y) / b3size.y; uv.push(u, v5); } geometry3.setAttribute("uv", new Float32BufferAttribute(uv, 2)); }); // node_modules/@react-three/drei/core/RoundedBox.js var React93 = __toESM(require_react()); var eps = 1e-5; function createShape(width, height, radius0) { const shape = new Shape(); const radius = radius0 - eps; shape.absarc(eps, eps, eps, -Math.PI / 2, -Math.PI, true); shape.absarc(eps, height - radius * 2, eps, Math.PI, Math.PI / 2, true); shape.absarc(width - radius * 2, height - radius * 2, eps, Math.PI / 2, 0, true); shape.absarc(width - radius * 2, eps, eps, 0, -Math.PI / 2, true); return shape; } var RoundedBox = React93.forwardRef(function RoundedBox2({ args: [width = 1, height = 1, depth = 1] = [], radius = 0.05, steps = 1, smoothness = 4, bevelSegments = 4, creaseAngle = 0.4, children, ...rest }, ref) { return React93.createElement("mesh", _extends({ ref }, rest), React93.createElement(RoundedBoxGeometry2, { args: [width, height, depth], radius, steps, smoothness, bevelSegments, creaseAngle }), children); }); var RoundedBoxGeometry2 = React93.forwardRef(function RoundedBoxGeometry3({ args: [width = 1, height = 1, depth = 1] = [], radius = 0.05, steps = 1, smoothness = 4, bevelSegments = 4, creaseAngle = 0.4, ...rest }, ref) { const shape = React93.useMemo(() => createShape(width, height, radius), [width, height, radius]); const params = React93.useMemo(() => ({ depth: depth - radius * 2, bevelEnabled: true, bevelSegments: bevelSegments * 2, steps, bevelSize: radius - eps, bevelThickness: radius, curveSegments: smoothness }), [depth, radius, smoothness, bevelSegments, steps]); const geomRef = React93.useRef(null); React93.useLayoutEffect(() => { if (geomRef.current) { geomRef.current.center(); toCreasedNormals(geomRef.current, creaseAngle); } }, [shape, params, creaseAngle]); React93.useImperativeHandle(ref, () => geomRef.current); return React93.createElement("extrudeGeometry", _extends({ ref: geomRef, args: [shape, params] }, rest)); }); // node_modules/@react-three/drei/core/ScreenQuad.js var React94 = __toESM(require_react()); function createScreenQuadGeometry() { const geometry3 = new BufferGeometry(); const vertices = new Float32Array([-1, -1, 3, -1, -1, 3]); geometry3.boundingSphere = new Sphere(); geometry3.boundingSphere.set(new Vector3(), Infinity); geometry3.setAttribute("position", new BufferAttribute(vertices, 2)); return geometry3; } var ScreenQuad = React94.forwardRef(function ScreenQuad2({ children, ...restProps }, ref) { const geometry3 = React94.useMemo(createScreenQuadGeometry, []); return React94.createElement("mesh", _extends({ ref, geometry: geometry3, frustumCulled: false }, restProps), children); }); // node_modules/@react-three/drei/core/Resize.js var React95 = __toESM(require_react()); var Resize = React95.forwardRef(({ children, width, height, depth, box3, precise = true, ...props }, fRef) => { const ref = React95.useRef(null); const outer = React95.useRef(null); const inner = React95.useRef(null); React95.useLayoutEffect(() => { outer.current.matrixWorld.identity(); let box = box3 || new Box3().setFromObject(inner.current, precise); const w = box.max.x - box.min.x; const h = box.max.y - box.min.y; const d2 = box.max.z - box.min.z; let dimension = Math.max(w, h, d2); if (width) dimension = w; if (height) dimension = h; if (depth) dimension = d2; outer.current.scale.setScalar(1 / dimension); }, [width, height, depth, box3, precise]); React95.useImperativeHandle(fRef, () => ref.current, []); return React95.createElement("group", _extends({ ref }, props), React95.createElement("group", { ref: outer }, React95.createElement("group", { ref: inner }, children))); }); // node_modules/@react-three/drei/core/Bounds.js var React96 = __toESM(require_react()); var AnimationState = (function(AnimationState2) { AnimationState2[AnimationState2["NONE"] = 0] = "NONE"; AnimationState2[AnimationState2["START"] = 1] = "START"; AnimationState2[AnimationState2["ACTIVE"] = 2] = "ACTIVE"; return AnimationState2; })(AnimationState || {}); var isOrthographic = (def) => def && def.isOrthographicCamera; var isBox3 = (def) => def && def.isBox3; var interpolateFuncDefault = (t3) => { return 1 - Math.exp(-5 * t3) + 7e-3 * t3; }; var context6 = React96.createContext(null); function Bounds({ children, maxDuration = 1, margin = 1.2, observe, fit, clip, interpolateFunc = interpolateFuncDefault, onFit }) { const ref = React96.useRef(null); const { camera, size: size2, invalidate } = useThree(); const controls = useThree((state) => state.controls); const onFitRef = React96.useRef(onFit); onFitRef.current = onFit; const origin2 = React96.useRef({ camPos: new Vector3(), camRot: new Quaternion(), camZoom: 1 }); const goal = React96.useRef({ camPos: void 0, camRot: void 0, camZoom: void 0, camUp: void 0, target: void 0 }); const animationState = React96.useRef(AnimationState.NONE); const t3 = React96.useRef(0); const [box] = React96.useState(() => new Box3()); const api = React96.useMemo(() => { function getSize() { const boxSize = box.getSize(new Vector3()); const center3 = box.getCenter(new Vector3()); const maxSize = Math.max(boxSize.x, boxSize.y, boxSize.z); const fitHeightDistance = isOrthographic(camera) ? maxSize * 4 : maxSize / (2 * Math.atan(Math.PI * camera.fov / 360)); const fitWidthDistance = isOrthographic(camera) ? maxSize * 4 : fitHeightDistance / camera.aspect; const distance3 = margin * Math.max(fitHeightDistance, fitWidthDistance); return { box, size: boxSize, center: center3, distance: distance3 }; } return { getSize, refresh(object) { if (isBox3(object)) box.copy(object); else { const target2 = object || ref.current; if (!target2) return this; target2.updateWorldMatrix(true, true); box.setFromObject(target2); } if (box.isEmpty()) { const max2 = camera.position.length() || 10; box.setFromCenterAndSize(new Vector3(), new Vector3(max2, max2, max2)); } origin2.current.camPos.copy(camera.position); origin2.current.camRot.copy(camera.quaternion); isOrthographic(camera) && (origin2.current.camZoom = camera.zoom); goal.current.camPos = void 0; goal.current.camRot = void 0; goal.current.camZoom = void 0; goal.current.camUp = void 0; goal.current.target = void 0; return this; }, reset() { const { center: center3, distance: distance3 } = getSize(); const direction2 = camera.position.clone().sub(center3).normalize(); goal.current.camPos = center3.clone().addScaledVector(direction2, distance3); goal.current.target = center3.clone(); const mCamRot = new Matrix4().lookAt(goal.current.camPos, goal.current.target, camera.up); goal.current.camRot = new Quaternion().setFromRotationMatrix(mCamRot); animationState.current = AnimationState.START; t3.current = 0; return this; }, moveTo(position2) { goal.current.camPos = Array.isArray(position2) ? new Vector3(...position2) : position2.clone(); animationState.current = AnimationState.START; t3.current = 0; return this; }, lookAt({ target: target2, up }) { goal.current.target = Array.isArray(target2) ? new Vector3(...target2) : target2.clone(); if (up) { goal.current.camUp = Array.isArray(up) ? new Vector3(...up) : up.clone(); } else { goal.current.camUp = camera.up.clone(); } const mCamRot = new Matrix4().lookAt(goal.current.camPos || camera.position, goal.current.target, goal.current.camUp); goal.current.camRot = new Quaternion().setFromRotationMatrix(mCamRot); animationState.current = AnimationState.START; t3.current = 0; return this; }, /** * @deprecated Use moveTo and lookAt instead */ to({ position: position2, target: target2 }) { return this.moveTo(position2).lookAt({ target: target2 }); }, fit() { if (!isOrthographic(camera)) { return this.reset(); } let maxHeight = 0, maxWidth = 0; const vertices = [new Vector3(box.min.x, box.min.y, box.min.z), new Vector3(box.min.x, box.max.y, box.min.z), new Vector3(box.min.x, box.min.y, box.max.z), new Vector3(box.min.x, box.max.y, box.max.z), new Vector3(box.max.x, box.max.y, box.max.z), new Vector3(box.max.x, box.max.y, box.min.z), new Vector3(box.max.x, box.min.y, box.max.z), new Vector3(box.max.x, box.min.y, box.min.z)]; const pos = goal.current.camPos || camera.position; const target2 = goal.current.target || (controls == null ? void 0 : controls.target); const up = goal.current.camUp || camera.up; const mCamWInv = target2 ? new Matrix4().lookAt(pos, target2, up).setPosition(pos).invert() : camera.matrixWorldInverse; for (const v5 of vertices) { v5.applyMatrix4(mCamWInv); maxHeight = Math.max(maxHeight, Math.abs(v5.y)); maxWidth = Math.max(maxWidth, Math.abs(v5.x)); } maxHeight *= 2; maxWidth *= 2; const zoomForHeight = (camera.top - camera.bottom) / maxHeight; const zoomForWidth = (camera.right - camera.left) / maxWidth; goal.current.camZoom = Math.min(zoomForHeight, zoomForWidth) / margin; animationState.current = AnimationState.START; t3.current = 0; onFitRef.current && onFitRef.current(this.getSize()); return this; }, clip() { const { distance: distance3 } = getSize(); camera.near = distance3 / 100; camera.far = distance3 * 100; camera.updateProjectionMatrix(); if (controls) { controls.maxDistance = distance3 * 10; controls.update(); } invalidate(); return this; } }; }, [box, camera, controls, margin, invalidate]); React96.useLayoutEffect(() => { if (controls) { const callback = () => { if (controls && goal.current.target && animationState.current !== AnimationState.NONE) { const front = new Vector3().setFromMatrixColumn(camera.matrix, 2); const d0 = origin2.current.camPos.distanceTo(controls.target); const d1 = (goal.current.camPos || origin2.current.camPos).distanceTo(goal.current.target); const d2 = (1 - t3.current) * d0 + t3.current * d1; controls.target.copy(camera.position).addScaledVector(front, -d2); controls.update(); } animationState.current = AnimationState.NONE; }; controls.addEventListener("start", callback); return () => controls.removeEventListener("start", callback); } }, [controls]); const count = React96.useRef(0); React96.useLayoutEffect(() => { if (observe || count.current++ === 0) { api.refresh(); if (fit) api.reset().fit(); if (clip) api.clip(); } }, [size2, clip, fit, observe, camera, controls]); useFrame((state, delta) => { if (animationState.current === AnimationState.START) { animationState.current = AnimationState.ACTIVE; invalidate(); } else if (animationState.current === AnimationState.ACTIVE) { t3.current += delta / maxDuration; if (t3.current >= 1) { goal.current.camPos && camera.position.copy(goal.current.camPos); goal.current.camRot && camera.quaternion.copy(goal.current.camRot); goal.current.camUp && camera.up.copy(goal.current.camUp); goal.current.camZoom && isOrthographic(camera) && (camera.zoom = goal.current.camZoom); camera.updateMatrixWorld(); camera.updateProjectionMatrix(); if (controls && goal.current.target) { controls.target.copy(goal.current.target); controls.update(); } animationState.current = AnimationState.NONE; } else { const k = interpolateFunc(t3.current); goal.current.camPos && camera.position.lerpVectors(origin2.current.camPos, goal.current.camPos, k); goal.current.camRot && camera.quaternion.slerpQuaternions(origin2.current.camRot, goal.current.camRot, k); goal.current.camUp && camera.up.set(0, 1, 0).applyQuaternion(camera.quaternion); goal.current.camZoom && isOrthographic(camera) && (camera.zoom = (1 - k) * origin2.current.camZoom + k * goal.current.camZoom); camera.updateMatrixWorld(); camera.updateProjectionMatrix(); } invalidate(); } }); return React96.createElement("group", { ref }, React96.createElement(context6.Provider, { value: api }, children)); } function useBounds() { return React96.useContext(context6); } // node_modules/@react-three/drei/core/CameraShake.js var React97 = __toESM(require_react()); var CameraShake = React97.forwardRef(({ intensity = 1, decay, decayRate = 0.65, maxYaw = 0.1, maxPitch = 0.1, maxRoll = 0.1, yawFrequency = 0.1, pitchFrequency = 0.1, rollFrequency = 0.1 }, ref) => { const camera = useThree((state) => state.camera); const defaultControls = useThree((state) => state.controls); const intensityRef = React97.useRef(intensity); const initialRotation = React97.useRef(camera.rotation.clone()); const [yawNoise] = React97.useState(() => new SimplexNoise()); const [pitchNoise] = React97.useState(() => new SimplexNoise()); const [rollNoise] = React97.useState(() => new SimplexNoise()); const constrainIntensity = () => { if (intensityRef.current < 0 || intensityRef.current > 1) { intensityRef.current = intensityRef.current < 0 ? 0 : 1; } }; React97.useImperativeHandle(ref, () => ({ getIntensity: () => intensityRef.current, setIntensity: (val) => { intensityRef.current = val; constrainIntensity(); } }), []); React97.useEffect(() => { if (defaultControls) { const callback = () => void (initialRotation.current = camera.rotation.clone()); defaultControls.addEventListener("change", callback); callback(); return () => void defaultControls.removeEventListener("change", callback); } }, [camera, defaultControls]); useFrame((state, delta) => { const shake = Math.pow(intensityRef.current, 2); const yaw = maxYaw * shake * yawNoise.noise(state.clock.elapsedTime * yawFrequency, 1); const pitch = maxPitch * shake * pitchNoise.noise(state.clock.elapsedTime * pitchFrequency, 1); const roll = maxRoll * shake * rollNoise.noise(state.clock.elapsedTime * rollFrequency, 1); camera.rotation.set(initialRotation.current.x + pitch, initialRotation.current.y + yaw, initialRotation.current.z + roll); if (decay && intensityRef.current > 0) { intensityRef.current -= decayRate * delta; constrainIntensity(); } }); return null; }); // node_modules/@react-three/drei/core/Float.js var React98 = __toESM(require_react()); var Float = React98.forwardRef(({ children, enabled = true, speed = 1, rotationIntensity = 1, floatIntensity = 1, floatingRange = [-0.1, 0.1], autoInvalidate = false, ...props }, forwardRef82) => { const ref = React98.useRef(null); React98.useImperativeHandle(forwardRef82, () => ref.current, []); const offset = React98.useRef(Math.random() * 1e4); useFrame((state) => { var _floatingRange$, _floatingRange$2; if (!enabled || speed === 0) return; if (autoInvalidate) state.invalidate(); const t3 = offset.current + state.clock.elapsedTime; ref.current.rotation.x = Math.cos(t3 / 4 * speed) / 8 * rotationIntensity; ref.current.rotation.y = Math.sin(t3 / 4 * speed) / 8 * rotationIntensity; ref.current.rotation.z = Math.sin(t3 / 4 * speed) / 20 * rotationIntensity; let yPosition = Math.sin(t3 / 4 * speed) / 10; yPosition = MathUtils.mapLinear(yPosition, -0.1, 0.1, (_floatingRange$ = floatingRange == null ? void 0 : floatingRange[0]) !== null && _floatingRange$ !== void 0 ? _floatingRange$ : -0.1, (_floatingRange$2 = floatingRange == null ? void 0 : floatingRange[1]) !== null && _floatingRange$2 !== void 0 ? _floatingRange$2 : 0.1); ref.current.position.y = yPosition * floatIntensity; ref.current.updateMatrix(); }); return React98.createElement("group", props, React98.createElement("group", { ref, matrixAutoUpdate: false }, children)); }); // node_modules/@react-three/drei/core/Stage.js var React102 = __toESM(require_react()); // node_modules/@react-three/drei/core/Environment.js var React99 = __toESM(require_react()); // node_modules/@monogrid/gainmap-js/dist/QuadRenderer-Bj1xl_EK.js var getBufferForType = (type, width, height) => { let out7; switch (type) { case UnsignedByteType: out7 = new Uint8ClampedArray(width * height * 4); break; case HalfFloatType: out7 = new Uint16Array(width * height * 4); break; case UnsignedIntType: out7 = new Uint32Array(width * height * 4); break; case ByteType: out7 = new Int8Array(width * height * 4); break; case ShortType: out7 = new Int16Array(width * height * 4); break; case IntType: out7 = new Int32Array(width * height * 4); break; case FloatType: out7 = new Float32Array(width * height * 4); break; default: throw new Error("Unsupported data type"); } return out7; }; var _canReadPixelsResult; var canReadPixels = (type, renderer, camera, renderTargetOptions) => { if (_canReadPixelsResult !== void 0) return _canReadPixelsResult; const testRT = new WebGLRenderTarget(1, 1, renderTargetOptions); renderer.setRenderTarget(testRT); const mesh = new Mesh(new PlaneGeometry(), new MeshBasicMaterial({ color: 16777215 })); renderer.render(mesh, camera); renderer.setRenderTarget(null); const out7 = getBufferForType(type, testRT.width, testRT.height); renderer.readRenderTargetPixels(testRT, 0, 0, testRT.width, testRT.height, out7); testRT.dispose(); mesh.geometry.dispose(); mesh.material.dispose(); _canReadPixelsResult = out7[0] !== 0; return _canReadPixelsResult; }; var QuadRenderer = class _QuadRenderer { _renderer; _rendererIsDisposable = false; _material; _scene; _camera; _quad; _renderTarget; _width; _height; _type; _colorSpace; _supportsReadPixels = true; /** * Constructs a new QuadRenderer * * @param options Parameters for this QuadRenderer */ constructor(options) { this._width = options.width; this._height = options.height; this._type = options.type; this._colorSpace = options.colorSpace; const rtOptions = { // fixed options format: RGBAFormat, depthBuffer: false, stencilBuffer: false, // user options type: this._type, // set in class property colorSpace: this._colorSpace, // set in class property anisotropy: options.renderTargetOptions?.anisotropy !== void 0 ? options.renderTargetOptions?.anisotropy : 1, generateMipmaps: options.renderTargetOptions?.generateMipmaps !== void 0 ? options.renderTargetOptions?.generateMipmaps : false, magFilter: options.renderTargetOptions?.magFilter !== void 0 ? options.renderTargetOptions?.magFilter : LinearFilter, minFilter: options.renderTargetOptions?.minFilter !== void 0 ? options.renderTargetOptions?.minFilter : LinearFilter, samples: options.renderTargetOptions?.samples !== void 0 ? options.renderTargetOptions?.samples : void 0, wrapS: options.renderTargetOptions?.wrapS !== void 0 ? options.renderTargetOptions?.wrapS : ClampToEdgeWrapping, wrapT: options.renderTargetOptions?.wrapT !== void 0 ? options.renderTargetOptions?.wrapT : ClampToEdgeWrapping }; this._material = options.material; if (options.renderer) { this._renderer = options.renderer; } else { this._renderer = _QuadRenderer.instantiateRenderer(); this._rendererIsDisposable = true; } this._scene = new Scene(); this._camera = new OrthographicCamera(); this._camera.position.set(0, 0, 10); this._camera.left = -0.5; this._camera.right = 0.5; this._camera.top = 0.5; this._camera.bottom = -0.5; this._camera.updateProjectionMatrix(); if (!canReadPixels(this._type, this._renderer, this._camera, rtOptions)) { let alternativeType; switch (this._type) { case HalfFloatType: alternativeType = this._renderer.extensions.has("EXT_color_buffer_float") ? FloatType : void 0; break; } if (alternativeType !== void 0) { console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${FloatType}`); this._type = alternativeType; } else { this._supportsReadPixels = false; console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"); } } this._quad = new Mesh(new PlaneGeometry(), this._material); this._quad.geometry.computeBoundingBox(); this._scene.add(this._quad); this._renderTarget = new WebGLRenderTarget(this.width, this.height, rtOptions); this._renderTarget.texture.mapping = options.renderTargetOptions?.mapping !== void 0 ? options.renderTargetOptions?.mapping : UVMapping; } /** * Instantiates a temporary renderer * * @returns */ static instantiateRenderer() { const renderer = new WebGLRenderer(); renderer.setSize(128, 128); return renderer; } /** * Renders the input texture using the specified material */ render = () => { this._renderer.setRenderTarget(this._renderTarget); try { this._renderer.render(this._scene, this._camera); } catch (e2) { this._renderer.setRenderTarget(null); throw e2; } this._renderer.setRenderTarget(null); }; /** * Obtains a Buffer containing the rendered texture. * * @throws Error if the browser cannot read pixels from this RenderTarget type. * @returns a TypedArray containing RGBA values from this renderer */ toArray() { if (!this._supportsReadPixels) throw new Error("Can't read pixels in this browser"); const out7 = getBufferForType(this._type, this._width, this._height); this._renderer.readRenderTargetPixels(this._renderTarget, 0, 0, this._width, this._height, out7); return out7; } /** * Performs a readPixel operation in the renderTarget * and returns a DataTexture containing the read data * * @param options options * @returns */ toDataTexture(options) { const returnValue = new DataTexture( // fixed values this.toArray(), this.width, this.height, RGBAFormat, this._type, // user values options?.mapping || UVMapping, options?.wrapS || ClampToEdgeWrapping, options?.wrapT || ClampToEdgeWrapping, options?.magFilter || LinearFilter, options?.minFilter || LinearFilter, options?.anisotropy || 1, // fixed value LinearSRGBColorSpace ); returnValue.generateMipmaps = options?.generateMipmaps !== void 0 ? options?.generateMipmaps : false; return returnValue; } /** * If using a disposable renderer, it will dispose it. */ disposeOnDemandRenderer() { this._renderer.setRenderTarget(null); if (this._rendererIsDisposable) { this._renderer.dispose(); this._renderer.forceContextLoss(); } } /** * Will dispose of **all** assets used by this renderer. * * * @param disposeRenderTarget will dispose of the renderTarget which will not be usable later * set this to true if you passed the `renderTarget.texture` to a `PMREMGenerator` * or are otherwise done with it. * * @example * ```js * const loader = new HDRJPGLoader(renderer) * const result = await loader.loadAsync('gainmap.jpeg') * const mesh = new Mesh(geometry, new MeshBasicMaterial({ map: result.renderTarget.texture }) ) * // DO NOT dispose the renderTarget here, * // it is used directly in the material * result.dispose() * ``` * * @example * ```js * const loader = new HDRJPGLoader(renderer) * const pmremGenerator = new PMREMGenerator( renderer ); * const result = await loader.loadAsync('gainmap.jpeg') * const envMap = pmremGenerator.fromEquirectangular(result.renderTarget.texture) * const mesh = new Mesh(geometry, new MeshStandardMaterial({ envMap }) ) * // renderTarget can be disposed here * // because it was used to generate a PMREM texture * result.dispose(true) * ``` */ dispose(disposeRenderTarget) { this.disposeOnDemandRenderer(); if (disposeRenderTarget) { this.renderTarget.dispose(); } if (this.material instanceof ShaderMaterial) { Object.values(this.material.uniforms).forEach((v5) => { if (v5.value instanceof Texture) v5.value.dispose(); }); } Object.values(this.material).forEach((value) => { if (value instanceof Texture) value.dispose(); }); this.material.dispose(); this._quad.geometry.dispose(); } /** * Width of the texture */ get width() { return this._width; } set width(value) { this._width = value; this._renderTarget.setSize(this._width, this._height); } /** * Height of the texture */ get height() { return this._height; } set height(value) { this._height = value; this._renderTarget.setSize(this._width, this._height); } /** * The renderer used */ get renderer() { return this._renderer; } /** * The `WebGLRenderTarget` used. */ get renderTarget() { return this._renderTarget; } set renderTarget(value) { this._renderTarget = value; this._width = value.width; this._height = value.height; } /** * The `Material` used. */ get material() { return this._material; } /** * */ get type() { return this._type; } get colorSpace() { return this._colorSpace; } }; // node_modules/@monogrid/gainmap-js/dist/Loader-DLI-_JDP.js function createDecodeFunction(config) { return (params) => { const { sdr, gainMap, renderer } = params; if (sdr.colorSpace !== SRGBColorSpace) { console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"); sdr.colorSpace = SRGBColorSpace; } sdr.needsUpdate = true; if (gainMap.colorSpace !== LinearSRGBColorSpace) { console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"); gainMap.colorSpace = LinearSRGBColorSpace; } gainMap.needsUpdate = true; const material = config.createMaterial({ ...params, sdr, gainMap }); const quadRenderer = config.createQuadRenderer({ width: sdr.image.width, height: sdr.image.height, type: HalfFloatType, colorSpace: LinearSRGBColorSpace, material, renderer, renderTargetOptions: params.renderTargetOptions }); return quadRenderer; }; } var GainMapNotFoundError = class extends Error { }; var XMPMetadataNotFoundError = class extends Error { }; var getXMLValue = (xml, tag, defaultValue) => { const attributeMatch = new RegExp(`${tag}="([^"]*)"`, "i").exec(xml); if (attributeMatch) return attributeMatch[1]; const tagMatch = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)`, "i").exec(xml); if (tagMatch) { const liValues = tagMatch[1].match(/([^<]*)<\/rdf:li>/g); if (liValues && liValues.length === 3) { return liValues.map((v5) => v5.replace(/<\/?rdf:li>/g, "")); } return tagMatch[1].trim(); } if (defaultValue !== void 0) return defaultValue; throw new Error(`Can't find ${tag} in gainmap metadata`); }; var extractXMP = (input) => { let str; if (typeof TextDecoder !== "undefined") str = new TextDecoder().decode(input); else str = input.toString(); let start = str.indexOf("", start); const xmpBlock = str.slice(start, end + 10); try { const gainMapMin = getXMLValue(xmpBlock, "hdrgm:GainMapMin", "0"); const gainMapMax = getXMLValue(xmpBlock, "hdrgm:GainMapMax"); const gamma = getXMLValue(xmpBlock, "hdrgm:Gamma", "1"); const offsetSDR = getXMLValue(xmpBlock, "hdrgm:OffsetSDR", "0.015625"); const offsetHDR = getXMLValue(xmpBlock, "hdrgm:OffsetHDR", "0.015625"); const hdrCapacityMinMatch = /hdrgm:HDRCapacityMin="([^"]*)"/.exec(xmpBlock); const hdrCapacityMin = hdrCapacityMinMatch ? hdrCapacityMinMatch[1] : "0"; const hdrCapacityMaxMatch = /hdrgm:HDRCapacityMax="([^"]*)"/.exec(xmpBlock); if (!hdrCapacityMaxMatch) throw new Error("Incomplete gainmap metadata"); const hdrCapacityMax = hdrCapacityMaxMatch[1]; return { gainMapMin: Array.isArray(gainMapMin) ? gainMapMin.map((v5) => parseFloat(v5)) : [parseFloat(gainMapMin), parseFloat(gainMapMin), parseFloat(gainMapMin)], gainMapMax: Array.isArray(gainMapMax) ? gainMapMax.map((v5) => parseFloat(v5)) : [parseFloat(gainMapMax), parseFloat(gainMapMax), parseFloat(gainMapMax)], gamma: Array.isArray(gamma) ? gamma.map((v5) => parseFloat(v5)) : [parseFloat(gamma), parseFloat(gamma), parseFloat(gamma)], offsetSdr: Array.isArray(offsetSDR) ? offsetSDR.map((v5) => parseFloat(v5)) : [parseFloat(offsetSDR), parseFloat(offsetSDR), parseFloat(offsetSDR)], offsetHdr: Array.isArray(offsetHDR) ? offsetHDR.map((v5) => parseFloat(v5)) : [parseFloat(offsetHDR), parseFloat(offsetHDR), parseFloat(offsetHDR)], hdrCapacityMin: parseFloat(hdrCapacityMin), hdrCapacityMax: parseFloat(hdrCapacityMax) }; } catch (e2) { } start = str.indexOf(" { const debug = this.options.debug; const dataView = new DataView(imageArrayBuffer.buffer); if (dataView.getUint16(0) !== 65496) { reject(new Error("Not a valid jpeg")); return; } const length3 = dataView.byteLength; let offset = 2; let loops = 0; let marker; while (offset < length3) { if (++loops > 250) { reject(new Error(`Found no marker after ${loops} loops 😵`)); return; } if (dataView.getUint8(offset) !== 255) { reject(new Error(`Not a valid marker at offset 0x${offset.toString(16)}, found: 0x${dataView.getUint8(offset).toString(16)}`)); return; } marker = dataView.getUint8(offset + 1); if (debug) console.log(`Marker: ${marker.toString(16)}`); if (marker === 226) { if (debug) console.log("Found APP2 marker (0xffe2)"); const formatPt = offset + 4; if (dataView.getUint32(formatPt) === 1297106432) { const tiffOffset = formatPt + 4; let bigEnd; if (dataView.getUint16(tiffOffset) === 18761) { bigEnd = false; } else if (dataView.getUint16(tiffOffset) === 19789) { bigEnd = true; } else { reject(new Error("No valid endianness marker found in TIFF header")); return; } if (dataView.getUint16(tiffOffset + 2, !bigEnd) !== 42) { reject(new Error("Not valid TIFF data! (no 0x002A marker)")); return; } const firstIFDOffset = dataView.getUint32(tiffOffset + 4, !bigEnd); if (firstIFDOffset < 8) { reject(new Error("Not valid TIFF data! (First offset less than 8)")); return; } const dirStart = tiffOffset + firstIFDOffset; const count = dataView.getUint16(dirStart, !bigEnd); const entriesStart = dirStart + 2; let numberOfImages = 0; for (let i4 = entriesStart; i4 < entriesStart + 12 * count; i4 += 12) { if (dataView.getUint16(i4, !bigEnd) === 45057) { numberOfImages = dataView.getUint32(i4 + 8, !bigEnd); } } const nextIFDOffsetLen = 4; const MPImageListValPt = dirStart + 2 + count * 12 + nextIFDOffsetLen; const images = []; for (let i4 = MPImageListValPt; i4 < MPImageListValPt + numberOfImages * 16; i4 += 16) { const image = { MPType: dataView.getUint32(i4, !bigEnd), size: dataView.getUint32(i4 + 4, !bigEnd), // This offset is specified relative to the address of the MP Endian // field in the MP Header, unless the image is a First Individual Image, // in which case the value of the offset shall be NULL (0x00000000). dataOffset: dataView.getUint32(i4 + 8, !bigEnd), dependantImages: dataView.getUint32(i4 + 12, !bigEnd), start: -1, end: -1, isFII: false }; if (!image.dataOffset) { image.start = 0; image.isFII = true; } else { image.start = tiffOffset + image.dataOffset; image.isFII = false; } image.end = image.start + image.size; images.push(image); } if (this.options.extractNonFII && images.length) { const bufferBlob = new Blob([dataView]); const imgs = []; for (const image of images) { if (image.isFII && !this.options.extractFII) { continue; } const imageBlob = bufferBlob.slice(image.start, image.end + 1, "image/jpeg"); imgs.push(imageBlob); } resolve(imgs); } } } offset += 2 + dataView.getUint16(offset + 2); } }); } }; var extractGainmapFromJPEG = async (jpegFile) => { const metadata = extractXMP(jpegFile); if (!metadata) throw new XMPMetadataNotFoundError("Gain map XMP metadata not found"); const mpfExtractor = new MPFExtractor({ extractFII: true, extractNonFII: true }); const images = await mpfExtractor.extract(jpegFile); if (images.length !== 2) throw new GainMapNotFoundError("Gain map recovery image not found"); return { sdr: new Uint8Array(await images[0].arrayBuffer()), gainMap: new Uint8Array(await images[1].arrayBuffer()), metadata }; }; var getHTMLImageFromBlob = (blob) => { return new Promise((resolve, reject) => { const img = document.createElement("img"); img.onload = () => { resolve(img); }; img.onerror = (e2) => { reject(e2); }; img.src = URL.createObjectURL(blob); }); }; var LoaderBaseShared = class extends Loader { _renderer; _renderTargetOptions; _internalLoadingManager; _config; constructor(config, manager) { super(manager); this._config = config; if (config.renderer) this._renderer = config.renderer; this._internalLoadingManager = new LoadingManager(); } setRenderer(renderer) { this._renderer = renderer; return this; } setRenderTargetOptions(options) { this._renderTargetOptions = options; return this; } prepareQuadRenderer() { if (!this._renderer) { console.warn("WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer."); } const material = this._config.createMaterial({ gainMapMax: [1, 1, 1], gainMapMin: [0, 0, 0], gamma: [1, 1, 1], offsetHdr: [1, 1, 1], offsetSdr: [1, 1, 1], hdrCapacityMax: 1, hdrCapacityMin: 0, maxDisplayBoost: 1, gainMap: new Texture(), sdr: new Texture() }); return this._config.createQuadRenderer({ width: 16, height: 16, type: HalfFloatType, colorSpace: LinearSRGBColorSpace, material, renderer: this._renderer, renderTargetOptions: this._renderTargetOptions }); } async processImages(sdrBuffer, gainMapBuffer, imageOrientation) { const gainMapBlob = gainMapBuffer ? new Blob([gainMapBuffer], { type: "image/jpeg" }) : void 0; const sdrBlob = new Blob([sdrBuffer], { type: "image/jpeg" }); let sdrImage; let gainMapImage; let needsFlip = false; if (typeof createImageBitmap === "undefined") { const res = await Promise.all([ gainMapBlob ? getHTMLImageFromBlob(gainMapBlob) : Promise.resolve(void 0), getHTMLImageFromBlob(sdrBlob) ]); gainMapImage = res[0]; sdrImage = res[1]; needsFlip = imageOrientation === "flipY"; } else { const res = await Promise.all([ gainMapBlob ? createImageBitmap(gainMapBlob, { imageOrientation: imageOrientation || "flipY" }) : Promise.resolve(void 0), createImageBitmap(sdrBlob, { imageOrientation: imageOrientation || "flipY" }) ]); gainMapImage = res[0]; sdrImage = res[1]; } return { sdrImage, gainMapImage, needsFlip }; } createTextures(sdrImage, gainMapImage, needsFlip) { const gainMap = new Texture(gainMapImage || new ImageData(2, 2), UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType, 1, LinearSRGBColorSpace); gainMap.flipY = needsFlip; gainMap.needsUpdate = true; const sdr = new Texture(sdrImage, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType, 1, SRGBColorSpace); sdr.flipY = needsFlip; sdr.needsUpdate = true; return { gainMap, sdr }; } updateQuadRenderer(quadRenderer, sdrImage, gainMap, sdr, metadata) { quadRenderer.width = sdrImage.width; quadRenderer.height = sdrImage.height; quadRenderer.material.gainMap = gainMap; quadRenderer.material.sdr = sdr; quadRenderer.material.gainMapMin = metadata.gainMapMin; quadRenderer.material.gainMapMax = metadata.gainMapMax; quadRenderer.material.offsetHdr = metadata.offsetHdr; quadRenderer.material.offsetSdr = metadata.offsetSdr; quadRenderer.material.gamma = metadata.gamma; quadRenderer.material.hdrCapacityMin = metadata.hdrCapacityMin; quadRenderer.material.hdrCapacityMax = metadata.hdrCapacityMax; quadRenderer.material.maxDisplayBoost = Math.pow(2, metadata.hdrCapacityMax); quadRenderer.material.needsUpdate = true; } }; // node_modules/@monogrid/gainmap-js/dist/decode.js var vertexShader2 = ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } ` ); var fragmentShader2 = ( /* glsl */ ` // min half float value #define HALF_FLOAT_MIN vec3( -65504, -65504, -65504 ) // max half float value #define HALF_FLOAT_MAX vec3( 65504, 65504, 65504 ) uniform sampler2D sdr; uniform sampler2D gainMap; uniform vec3 gamma; uniform vec3 offsetHdr; uniform vec3 offsetSdr; uniform vec3 gainMapMin; uniform vec3 gainMapMax; uniform float weightFactor; varying vec2 vUv; void main() { vec3 rgb = texture2D( sdr, vUv ).rgb; vec3 recovery = texture2D( gainMap, vUv ).rgb; vec3 logRecovery = pow( recovery, gamma ); vec3 logBoost = gainMapMin * ( 1.0 - logRecovery ) + gainMapMax * logRecovery; vec3 hdrColor = (rgb + offsetSdr) * exp2( logBoost * weightFactor ) - offsetHdr; vec3 clampedHdrColor = max( HALF_FLOAT_MIN, min( HALF_FLOAT_MAX, hdrColor )); gl_FragColor = vec4( clampedHdrColor , 1.0 ); } ` ); var GainMapDecoderMaterial = class extends ShaderMaterial { _maxDisplayBoost; _hdrCapacityMin; _hdrCapacityMax; /** * * @param params */ constructor({ gamma, offsetHdr, offsetSdr, gainMapMin, gainMapMax, maxDisplayBoost, hdrCapacityMin, hdrCapacityMax, sdr, gainMap }) { super({ name: "GainMapDecoderMaterial", vertexShader: vertexShader2, fragmentShader: fragmentShader2, uniforms: { sdr: { value: sdr }, gainMap: { value: gainMap }, gamma: { value: new Vector3(1 / gamma[0], 1 / gamma[1], 1 / gamma[2]) }, offsetHdr: { value: new Vector3().fromArray(offsetHdr) }, offsetSdr: { value: new Vector3().fromArray(offsetSdr) }, gainMapMin: { value: new Vector3().fromArray(gainMapMin) }, gainMapMax: { value: new Vector3().fromArray(gainMapMax) }, weightFactor: { value: (Math.log2(maxDisplayBoost) - hdrCapacityMin) / (hdrCapacityMax - hdrCapacityMin) } }, blending: NoBlending, depthTest: false, depthWrite: false }); this._maxDisplayBoost = maxDisplayBoost; this._hdrCapacityMin = hdrCapacityMin; this._hdrCapacityMax = hdrCapacityMax; this.needsUpdate = true; this.uniformsNeedUpdate = true; } get sdr() { return this.uniforms.sdr.value; } set sdr(value) { this.uniforms.sdr.value = value; } get gainMap() { return this.uniforms.gainMap.value; } set gainMap(value) { this.uniforms.gainMap.value = value; } /** * @see {@link GainMapMetadata.offsetHdr} */ get offsetHdr() { return this.uniforms.offsetHdr.value.toArray(); } set offsetHdr(value) { this.uniforms.offsetHdr.value.fromArray(value); } /** * @see {@link GainMapMetadata.offsetSdr} */ get offsetSdr() { return this.uniforms.offsetSdr.value.toArray(); } set offsetSdr(value) { this.uniforms.offsetSdr.value.fromArray(value); } /** * @see {@link GainMapMetadata.gainMapMin} */ get gainMapMin() { return this.uniforms.gainMapMin.value.toArray(); } set gainMapMin(value) { this.uniforms.gainMapMin.value.fromArray(value); } /** * @see {@link GainMapMetadata.gainMapMax} */ get gainMapMax() { return this.uniforms.gainMapMax.value.toArray(); } set gainMapMax(value) { this.uniforms.gainMapMax.value.fromArray(value); } /** * @see {@link GainMapMetadata.gamma} */ get gamma() { const g = this.uniforms.gamma.value; return [1 / g.x, 1 / g.y, 1 / g.z]; } set gamma(value) { const g = this.uniforms.gamma.value; g.x = 1 / value[0]; g.y = 1 / value[1]; g.z = 1 / value[2]; } /** * @see {@link GainMapMetadata.hdrCapacityMin} * @remarks Logarithmic space */ get hdrCapacityMin() { return this._hdrCapacityMin; } set hdrCapacityMin(value) { this._hdrCapacityMin = value; this.calculateWeight(); } /** * @see {@link GainMapMetadata.hdrCapacityMin} * @remarks Logarithmic space */ get hdrCapacityMax() { return this._hdrCapacityMax; } set hdrCapacityMax(value) { this._hdrCapacityMax = value; this.calculateWeight(); } /** * @see {@link GainmapDecodingParameters.maxDisplayBoost} * @remarks Non Logarithmic space */ get maxDisplayBoost() { return this._maxDisplayBoost; } set maxDisplayBoost(value) { this._maxDisplayBoost = Math.max(1, Math.min(65504, value)); this.calculateWeight(); } calculateWeight() { const val = (Math.log2(this._maxDisplayBoost) - this._hdrCapacityMin) / (this._hdrCapacityMax - this._hdrCapacityMin); this.uniforms.weightFactor.value = Math.max(0, Math.min(1, val)); } }; var decodeImpl = createDecodeFunction({ renderer: WebGLRenderer, createMaterial: (params) => new GainMapDecoderMaterial(params), createQuadRenderer: (params) => new QuadRenderer(params) }); var LoaderBaseWebGL = class extends LoaderBaseShared { constructor(renderer, manager) { super({ renderer, createMaterial: (params) => new GainMapDecoderMaterial(params), createQuadRenderer: (params) => new QuadRenderer(params) }, manager); } /** * @private * @param quadRenderer * @param metadata * @param sdrBuffer * @param gainMapBuffer */ async render(quadRenderer, metadata, sdrBuffer, gainMapBuffer) { const { sdrImage, gainMapImage, needsFlip } = await this.processImages(sdrBuffer, gainMapBuffer, "flipY"); const { gainMap, sdr } = this.createTextures(sdrImage, gainMapImage, needsFlip); this.updateQuadRenderer(quadRenderer, sdrImage, gainMap, sdr, metadata); quadRenderer.render(); } }; var GainMapLoader = class extends LoaderBaseWebGL { /** * Loads a gainmap using separate data * * sdr image * * gain map image * * metadata json * * useful for webp gain maps * * @param urls An array in the form of [sdr.jpg, gainmap.jpg, metadata.json] * @param onLoad Load complete callback, will receive the result * @param onProgress Progress callback, will receive a `ProgressEvent` * @param onError Error callback * @returns */ load([sdrUrl, gainMapUrl, metadataUrl], onLoad, onProgress, onError) { const quadRenderer = this.prepareQuadRenderer(); let sdr; let gainMap; let metadata; const loadCheck = async () => { if (sdr && gainMap && metadata) { try { await this.render(quadRenderer, metadata, sdr, gainMap); } catch (error) { this.manager.itemError(sdrUrl); this.manager.itemError(gainMapUrl); this.manager.itemError(metadataUrl); if (typeof onError === "function") onError(error); quadRenderer.disposeOnDemandRenderer(); return; } if (typeof onLoad === "function") onLoad(quadRenderer); this.manager.itemEnd(sdrUrl); this.manager.itemEnd(gainMapUrl); this.manager.itemEnd(metadataUrl); quadRenderer.disposeOnDemandRenderer(); } }; let sdrLengthComputable = true; let sdrTotal = 0; let sdrLoaded = 0; let gainMapLengthComputable = true; let gainMapTotal = 0; let gainMapLoaded = 0; let metadataLengthComputable = true; let metadataTotal = 0; let metadataLoaded = 0; const progressHandler = () => { if (typeof onProgress === "function") { const total = sdrTotal + gainMapTotal + metadataTotal; const loaded = sdrLoaded + gainMapLoaded + metadataLoaded; const lengthComputable = sdrLengthComputable && gainMapLengthComputable && metadataLengthComputable; onProgress(new ProgressEvent("progress", { lengthComputable, loaded, total })); } }; this.manager.itemStart(sdrUrl); this.manager.itemStart(gainMapUrl); this.manager.itemStart(metadataUrl); const sdrLoader = new FileLoader(this._internalLoadingManager); sdrLoader.setResponseType("arraybuffer"); sdrLoader.setRequestHeader(this.requestHeader); sdrLoader.setPath(this.path); sdrLoader.setWithCredentials(this.withCredentials); sdrLoader.load(sdrUrl, async (buffer2) => { if (typeof buffer2 === "string") throw new Error("Invalid sdr buffer"); sdr = buffer2; await loadCheck(); }, (e2) => { sdrLengthComputable = e2.lengthComputable; sdrLoaded = e2.loaded; sdrTotal = e2.total; progressHandler(); }, (error) => { this.manager.itemError(sdrUrl); if (typeof onError === "function") onError(error); }); const gainMapLoader = new FileLoader(this._internalLoadingManager); gainMapLoader.setResponseType("arraybuffer"); gainMapLoader.setRequestHeader(this.requestHeader); gainMapLoader.setPath(this.path); gainMapLoader.setWithCredentials(this.withCredentials); gainMapLoader.load(gainMapUrl, async (buffer2) => { if (typeof buffer2 === "string") throw new Error("Invalid gainmap buffer"); gainMap = buffer2; await loadCheck(); }, (e2) => { gainMapLengthComputable = e2.lengthComputable; gainMapLoaded = e2.loaded; gainMapTotal = e2.total; progressHandler(); }, (error) => { this.manager.itemError(gainMapUrl); if (typeof onError === "function") onError(error); }); const metadataLoader = new FileLoader(this._internalLoadingManager); metadataLoader.setRequestHeader(this.requestHeader); metadataLoader.setPath(this.path); metadataLoader.setWithCredentials(this.withCredentials); metadataLoader.load(metadataUrl, async (json) => { if (typeof json !== "string") throw new Error("Invalid metadata string"); metadata = JSON.parse(json); await loadCheck(); }, (e2) => { metadataLengthComputable = e2.lengthComputable; metadataLoaded = e2.loaded; metadataTotal = e2.total; progressHandler(); }, (error) => { this.manager.itemError(metadataUrl); if (typeof onError === "function") onError(error); }); return quadRenderer; } }; var HDRJPGLoader = class extends LoaderBaseWebGL { /** * Loads a JPEG containing gain map metadata * Renders a normal SDR image if gainmap data is not found * * @param url Path to a JPEG file containing embedded gain map metadata * @param onLoad Load complete callback, will receive the result * @param onProgress Progress callback, will receive a `ProgressEvent` * @param onError Error callback * @returns */ load(url, onLoad, onProgress, onError) { const quadRenderer = this.prepareQuadRenderer(); const loader2 = new FileLoader(this._internalLoadingManager); loader2.setResponseType("arraybuffer"); loader2.setRequestHeader(this.requestHeader); loader2.setPath(this.path); loader2.setWithCredentials(this.withCredentials); this.manager.itemStart(url); loader2.load(url, async (jpeg) => { if (typeof jpeg === "string") throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]"); const jpegBuffer = new Uint8Array(jpeg); let sdrJPEG; let gainMapJPEG; let metadata; try { const extractionResult = await extractGainmapFromJPEG(jpegBuffer); sdrJPEG = extractionResult.sdr; gainMapJPEG = extractionResult.gainMap; metadata = extractionResult.metadata; } catch (e2) { if (e2 instanceof XMPMetadataNotFoundError || e2 instanceof GainMapNotFoundError) { console.warn(`Failure to reconstruct an HDR image from ${url}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`); metadata = { gainMapMin: [0, 0, 0], gainMapMax: [1, 1, 1], gamma: [1, 1, 1], hdrCapacityMin: 0, hdrCapacityMax: 1, offsetHdr: [0, 0, 0], offsetSdr: [0, 0, 0] }; sdrJPEG = jpegBuffer; } else { throw e2; } } try { await this.render(quadRenderer, metadata, sdrJPEG.buffer, gainMapJPEG?.buffer); } catch (error) { this.manager.itemError(url); if (typeof onError === "function") onError(error); quadRenderer.disposeOnDemandRenderer(); return; } if (typeof onLoad === "function") onLoad(quadRenderer); this.manager.itemEnd(url); quadRenderer.disposeOnDemandRenderer(); }, onProgress, (error) => { this.manager.itemError(url); if (typeof onError === "function") onError(error); }); return quadRenderer; } }; // node_modules/@react-three/drei/helpers/environment-assets.js var presetsObj = { apartment: "lebombo_1k.hdr", city: "potsdamer_platz_1k.hdr", dawn: "kiara_1_dawn_1k.hdr", forest: "forest_slope_1k.hdr", lobby: "st_fagans_interior_1k.hdr", night: "dikhololo_night_1k.hdr", park: "rooitou_park_1k.hdr", studio: "studio_small_03_1k.hdr", sunset: "venice_sunset_1k.hdr", warehouse: "empty_warehouse_01_1k.hdr" }; // node_modules/@react-three/drei/core/useEnvironment.js var import_react18 = __toESM(require_react()); var CUBEMAP_ROOT = "https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/"; var isArray2 = (arr) => Array.isArray(arr); var defaultFiles = ["/px.png", "/nx.png", "/py.png", "/ny.png", "/pz.png", "/nz.png"]; function useEnvironment({ files = defaultFiles, path = "", preset = void 0, colorSpace = void 0, extensions: extensions2 } = {}) { if (preset) { validatePreset(preset); files = presetsObj[preset]; path = CUBEMAP_ROOT; } const multiFile = isArray2(files); const { extension, isCubemap } = getExtension(files); const loader2 = getLoader(extension); if (!loader2) throw new Error("useEnvironment: Unrecognized file extension: " + files); const gl = useThree((state) => state.gl); (0, import_react18.useLayoutEffect)(() => { if (extension !== "webp" && extension !== "jpg" && extension !== "jpeg") return; function clearGainmapTexture() { useLoader.clear(loader2, multiFile ? [files] : files); } gl.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true }); }, [files, gl.domElement]); const loaderResult = useLoader(loader2, multiFile ? [files] : files, (loader3) => { if (extension === "webp" || extension === "jpg" || extension === "jpeg") { loader3.setRenderer(gl); } loader3.setPath == null || loader3.setPath(path); if (extensions2) extensions2(loader3); }); let texture = multiFile ? ( // @ts-ignore loaderResult[0] ) : loaderResult; if (extension === "jpg" || extension === "jpeg" || extension === "webp") { var _renderTarget; texture = (_renderTarget = texture.renderTarget) == null ? void 0 : _renderTarget.texture; } texture.mapping = isCubemap ? CubeReflectionMapping : EquirectangularReflectionMapping; texture.colorSpace = colorSpace !== null && colorSpace !== void 0 ? colorSpace : isCubemap ? "srgb" : "srgb-linear"; return texture; } var preloadDefaultOptions = { files: defaultFiles, path: "", preset: void 0, extensions: void 0 }; useEnvironment.preload = (preloadOptions) => { const options = { ...preloadDefaultOptions, ...preloadOptions }; let { files, path = "" } = options; const { preset, extensions: extensions2 } = options; if (preset) { validatePreset(preset); files = presetsObj[preset]; path = CUBEMAP_ROOT; } const { extension } = getExtension(files); if (extension === "webp" || extension === "jpg" || extension === "jpeg") { throw new Error("useEnvironment: Preloading gainmaps is not supported"); } const loader2 = getLoader(extension); if (!loader2) throw new Error("useEnvironment: Unrecognized file extension: " + files); useLoader.preload(loader2, isArray2(files) ? [files] : files, (loader3) => { loader3.setPath == null || loader3.setPath(path); if (extensions2) extensions2(loader3); }); }; var clearDefaultOptins = { files: defaultFiles, preset: void 0 }; useEnvironment.clear = (clearOptions) => { const options = { ...clearDefaultOptins, ...clearOptions }; let { files } = options; const { preset } = options; if (preset) { validatePreset(preset); files = presetsObj[preset]; } const { extension } = getExtension(files); const loader2 = getLoader(extension); if (!loader2) throw new Error("useEnvironment: Unrecognized file extension: " + files); useLoader.clear(loader2, isArray2(files) ? [files] : files); }; function validatePreset(preset) { if (!(preset in presetsObj)) throw new Error("Preset must be one of: " + Object.keys(presetsObj).join(", ")); } function getExtension(files) { var _firstEntry$split$pop; const isCubemap = isArray2(files) && files.length === 6; const isGainmap = isArray2(files) && files.length === 3 && files.some((file) => file.endsWith("json")); const firstEntry = isArray2(files) ? files[0] : files; const extension = isCubemap ? "cube" : isGainmap ? "webp" : firstEntry.startsWith("data:application/exr") ? "exr" : firstEntry.startsWith("data:application/hdr") ? "hdr" : firstEntry.startsWith("data:image/jpeg") ? "jpg" : (_firstEntry$split$pop = firstEntry.split(".").pop()) == null || (_firstEntry$split$pop = _firstEntry$split$pop.split("?")) == null || (_firstEntry$split$pop = _firstEntry$split$pop.shift()) == null ? void 0 : _firstEntry$split$pop.toLowerCase(); return { extension, isCubemap, isGainmap }; } function getLoader(extension) { const loader2 = extension === "cube" ? CubeTextureLoader : extension === "hdr" ? RGBELoader : extension === "exr" ? EXRLoader : extension === "jpg" || extension === "jpeg" ? HDRJPGLoader : extension === "webp" ? GainMapLoader : null; return loader2; } // node_modules/@react-three/drei/core/Environment.js var isRef = (obj) => obj.current && obj.current.isScene; var resolveScene = (scene) => isRef(scene) ? scene.current : scene; function setEnvProps(background, scene, defaultScene, texture, sceneProps = {}) { var _target$backgroundRot, _target$backgroundRot2, _target$environmentRo, _target$environmentRo2; sceneProps = { backgroundBlurriness: 0, backgroundIntensity: 1, backgroundRotation: [0, 0, 0], environmentIntensity: 1, environmentRotation: [0, 0, 0], ...sceneProps }; const target2 = resolveScene(scene || defaultScene); const oldbg = target2.background; const oldenv = target2.environment; const oldSceneProps = { // @ts-ignore backgroundBlurriness: target2.backgroundBlurriness, // @ts-ignore backgroundIntensity: target2.backgroundIntensity, // @ts-ignore backgroundRotation: (_target$backgroundRot = (_target$backgroundRot2 = target2.backgroundRotation) == null || _target$backgroundRot2.clone == null ? void 0 : _target$backgroundRot2.clone()) !== null && _target$backgroundRot !== void 0 ? _target$backgroundRot : [0, 0, 0], // @ts-ignore environmentIntensity: target2.environmentIntensity, // @ts-ignore environmentRotation: (_target$environmentRo = (_target$environmentRo2 = target2.environmentRotation) == null || _target$environmentRo2.clone == null ? void 0 : _target$environmentRo2.clone()) !== null && _target$environmentRo !== void 0 ? _target$environmentRo : [0, 0, 0] }; if (background !== "only") target2.environment = texture; if (background) target2.background = texture; applyProps(target2, sceneProps); return () => { if (background !== "only") target2.environment = oldenv; if (background) target2.background = oldbg; applyProps(target2, oldSceneProps); }; } function EnvironmentMap({ scene, background = false, map: map2, ...config }) { const defaultScene = useThree((state) => state.scene); React99.useLayoutEffect(() => { if (map2) return setEnvProps(background, scene, defaultScene, map2, config); }); return null; } function EnvironmentCube({ background = false, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }) { const texture = useEnvironment(rest); const defaultScene = useThree((state) => state.scene); React99.useLayoutEffect(() => { return setEnvProps(background, scene, defaultScene, texture, { backgroundBlurriness: blur !== null && blur !== void 0 ? blur : backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation }); }); React99.useEffect(() => { return () => { texture.dispose(); }; }, [texture]); return null; } function EnvironmentPortal({ children, near = 0.1, far = 1e3, resolution = 256, frames = 1, map: map2, background = false, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, scene, files, path, preset = void 0, extensions: extensions2 }) { const gl = useThree((state) => state.gl); const defaultScene = useThree((state) => state.scene); const camera = React99.useRef(null); const [virtualScene] = React99.useState(() => new Scene()); const fbo = React99.useMemo(() => { const fbo2 = new WebGLCubeRenderTarget(resolution); fbo2.texture.type = HalfFloatType; return fbo2; }, [resolution]); React99.useEffect(() => { return () => { fbo.dispose(); }; }, [fbo]); React99.useLayoutEffect(() => { if (frames === 1) { const autoClear = gl.autoClear; gl.autoClear = true; camera.current.update(gl, virtualScene); gl.autoClear = autoClear; } return setEnvProps(background, scene, defaultScene, fbo.texture, { backgroundBlurriness: blur !== null && blur !== void 0 ? blur : backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation }); }, [children, virtualScene, fbo.texture, scene, defaultScene, background, frames, gl]); let count = 1; useFrame(() => { if (frames === Infinity || count < frames) { const autoClear = gl.autoClear; gl.autoClear = true; camera.current.update(gl, virtualScene); gl.autoClear = autoClear; count++; } }); return React99.createElement(React99.Fragment, null, createPortal(React99.createElement(React99.Fragment, null, children, React99.createElement("cubeCamera", { ref: camera, args: [near, far, fbo] }), files || preset ? React99.createElement(EnvironmentCube, { background: true, files, preset, path, extensions: extensions2 }) : map2 ? React99.createElement(EnvironmentMap, { background: true, map: map2, extensions: extensions2 }) : null), virtualScene)); } function EnvironmentGround(props) { var _props$ground, _props$ground2, _scale3, _props$ground3; const textureDefault = useEnvironment(props); const texture = props.map || textureDefault; React99.useMemo(() => extend({ GroundProjectedEnvImpl: GroundProjectedEnv }), []); React99.useEffect(() => { return () => { textureDefault.dispose(); }; }, [textureDefault]); const args = React99.useMemo(() => [texture], [texture]); const height = (_props$ground = props.ground) == null ? void 0 : _props$ground.height; const radius = (_props$ground2 = props.ground) == null ? void 0 : _props$ground2.radius; const scale5 = (_scale3 = (_props$ground3 = props.ground) == null ? void 0 : _props$ground3.scale) !== null && _scale3 !== void 0 ? _scale3 : 1e3; return React99.createElement(React99.Fragment, null, React99.createElement(EnvironmentMap, _extends({}, props, { map: texture })), React99.createElement("groundProjectedEnvImpl", { args, scale: scale5, height, radius })); } function Environment(props) { return props.ground ? React99.createElement(EnvironmentGround, props) : props.map ? React99.createElement(EnvironmentMap, props) : props.children ? React99.createElement(EnvironmentPortal, props) : React99.createElement(EnvironmentCube, props); } // node_modules/@react-three/drei/core/ContactShadows.js var React100 = __toESM(require_react()); var ContactShadows = React100.forwardRef(({ scale: scale5 = 10, frames = Infinity, opacity = 1, width = 1, height = 1, blur = 1, near = 0, far = 10, resolution = 512, smooth = true, color = "#000000", depthWrite = false, renderOrder, ...props }, fref) => { const ref = React100.useRef(null); const scene = useThree((state) => state.scene); const gl = useThree((state) => state.gl); const shadowCamera = React100.useRef(null); width = width * (Array.isArray(scale5) ? scale5[0] : scale5 || 1); height = height * (Array.isArray(scale5) ? scale5[1] : scale5 || 1); const [renderTarget, planeGeometry, depthMaterial, blurPlane, horizontalBlurMaterial, verticalBlurMaterial, renderTargetBlur] = React100.useMemo(() => { const renderTarget2 = new WebGLRenderTarget(resolution, resolution); const renderTargetBlur2 = new WebGLRenderTarget(resolution, resolution); renderTargetBlur2.texture.generateMipmaps = renderTarget2.texture.generateMipmaps = false; const planeGeometry2 = new PlaneGeometry(width, height).rotateX(Math.PI / 2); const blurPlane2 = new Mesh(planeGeometry2); const depthMaterial2 = new MeshDepthMaterial(); depthMaterial2.depthTest = depthMaterial2.depthWrite = false; depthMaterial2.onBeforeCompile = (shader) => { shader.uniforms = { ...shader.uniforms, ucolor: { value: new Color(color) } }; shader.fragmentShader = shader.fragmentShader.replace( `void main() {`, // `uniform vec3 ucolor; void main() { ` ); shader.fragmentShader = shader.fragmentShader.replace( "vec4( vec3( 1.0 - fragCoordZ ), opacity );", // Colorize the shadow, multiply by the falloff so that the center can remain darker "vec4( ucolor * fragCoordZ * 2.0, ( 1.0 - fragCoordZ ) * 1.0 );" ); }; const horizontalBlurMaterial2 = new ShaderMaterial(HorizontalBlurShader); const verticalBlurMaterial2 = new ShaderMaterial(VerticalBlurShader); verticalBlurMaterial2.depthTest = horizontalBlurMaterial2.depthTest = false; return [renderTarget2, planeGeometry2, depthMaterial2, blurPlane2, horizontalBlurMaterial2, verticalBlurMaterial2, renderTargetBlur2]; }, [resolution, width, height, scale5, color]); const blurShadows = (blur2) => { blurPlane.visible = true; blurPlane.material = horizontalBlurMaterial; horizontalBlurMaterial.uniforms.tDiffuse.value = renderTarget.texture; horizontalBlurMaterial.uniforms.h.value = blur2 * 1 / 256; gl.setRenderTarget(renderTargetBlur); gl.render(blurPlane, shadowCamera.current); blurPlane.material = verticalBlurMaterial; verticalBlurMaterial.uniforms.tDiffuse.value = renderTargetBlur.texture; verticalBlurMaterial.uniforms.v.value = blur2 * 1 / 256; gl.setRenderTarget(renderTarget); gl.render(blurPlane, shadowCamera.current); blurPlane.visible = false; }; let count = 0; let initialBackground; let initialOverrideMaterial; useFrame(() => { if (shadowCamera.current && (frames === Infinity || count < frames)) { count++; initialBackground = scene.background; initialOverrideMaterial = scene.overrideMaterial; ref.current.visible = false; scene.background = null; scene.overrideMaterial = depthMaterial; gl.setRenderTarget(renderTarget); gl.render(scene, shadowCamera.current); blurShadows(blur); if (smooth) blurShadows(blur * 0.4); gl.setRenderTarget(null); ref.current.visible = true; scene.overrideMaterial = initialOverrideMaterial; scene.background = initialBackground; } }); React100.useImperativeHandle(fref, () => ref.current, []); return React100.createElement("group", _extends({ "rotation-x": Math.PI / 2 }, props, { ref }), React100.createElement("mesh", { renderOrder, geometry: planeGeometry, scale: [1, -1, 1], rotation: [-Math.PI / 2, 0, 0] }, React100.createElement("meshBasicMaterial", { transparent: true, map: renderTarget.texture, opacity, depthWrite })), React100.createElement("orthographicCamera", { ref: shadowCamera, args: [-width / 2, width / 2, height / 2, -height / 2, near, far] })); }); // node_modules/@react-three/drei/core/AccumulativeShadows.js var React101 = __toESM(require_react()); function isLight3(object) { return object.isLight; } function isGeometry(object) { return !!object.geometry; } var accumulativeContext = React101.createContext(null); var SoftShadowMaterial = shaderMaterial({ color: new Color(), blend: 2, alphaTest: 0.75, opacity: 0, map: null }, `varying vec2 vUv; void main() { gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.); vUv = uv; }`, `varying vec2 vUv; uniform sampler2D map; uniform vec3 color; uniform float opacity; uniform float alphaTest; uniform float blend; void main() { vec4 sampledDiffuseColor = texture2D(map, vUv); gl_FragColor = vec4(color * sampledDiffuseColor.r * blend, max(0.0, (1.0 - (sampledDiffuseColor.r + sampledDiffuseColor.g + sampledDiffuseColor.b) / alphaTest)) * opacity); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }`); var AccumulativeShadows = React101.forwardRef(({ children, temporal, frames = 40, limit = Infinity, blend = 20, scale: scale5 = 10, opacity = 1, alphaTest = 0.75, color = "black", colorBlend = 2, resolution = 1024, toneMapped = true, ...props }, forwardRef82) => { extend({ SoftShadowMaterial }); const gl = useThree((state) => state.gl); const scene = useThree((state) => state.scene); const camera = useThree((state) => state.camera); const invalidate = useThree((state) => state.invalidate); const gPlane = React101.useRef(null); const gLights = React101.useRef(null); const [plm] = React101.useState(() => new ProgressiveLightMap2(gl, scene, resolution)); React101.useLayoutEffect(() => { plm.configure(gPlane.current); }, []); const api = React101.useMemo(() => ({ lights: /* @__PURE__ */ new Map(), temporal: !!temporal, frames: Math.max(2, frames), blend: Math.max(2, frames === Infinity ? blend : frames), count: 0, getMesh: () => gPlane.current, reset: () => { plm.clear(); const material = gPlane.current.material; material.opacity = 0; material.alphaTest = 0; api.count = 0; }, update: (frames2 = 1) => { const material = gPlane.current.material; if (!api.temporal) { material.opacity = opacity; material.alphaTest = alphaTest; } else { material.opacity = Math.min(opacity, material.opacity + opacity / api.blend); material.alphaTest = Math.min(alphaTest, material.alphaTest + alphaTest / api.blend); } gLights.current.visible = true; plm.prepare(); for (let i4 = 0; i4 < frames2; i4++) { api.lights.forEach((light) => light.update()); plm.update(camera, api.blend); } gLights.current.visible = false; plm.finish(); } }), [plm, camera, scene, temporal, frames, blend, opacity, alphaTest]); React101.useLayoutEffect(() => { api.reset(); if (!api.temporal && api.frames !== Infinity) api.update(api.blend); }); React101.useImperativeHandle(forwardRef82, () => api, [api]); useFrame(() => { if ((api.temporal || api.frames === Infinity) && api.count < api.frames && api.count < limit) { invalidate(); api.update(); api.count++; } }); return React101.createElement("group", props, React101.createElement("group", { traverse: () => null, ref: gLights }, React101.createElement(accumulativeContext.Provider, { value: api }, children)), React101.createElement("mesh", { receiveShadow: true, ref: gPlane, scale: scale5, rotation: [-Math.PI / 2, 0, 0] }, React101.createElement("planeGeometry", null), React101.createElement("softShadowMaterial", { transparent: true, depthWrite: false, toneMapped, color, blend: colorBlend, map: plm.progressiveLightMap2.texture }))); }); var RandomizedLight = React101.forwardRef(({ castShadow = true, bias = 1e-3, mapSize = 512, size: size2 = 5, near = 0.5, far = 500, frames = 1, position: position2 = [0, 0, 0], radius = 1, amount = 8, intensity = version2 >= 155 ? Math.PI : 1, ambient = 0.5, ...props }, forwardRef82) => { const gLights = React101.useRef(null); const length3 = new Vector3(...position2).length(); const parent = React101.useContext(accumulativeContext); const update2 = React101.useCallback(() => { let light; if (gLights.current) { for (let l2 = 0; l2 < gLights.current.children.length; l2++) { light = gLights.current.children[l2]; if (Math.random() > ambient) { light.position.set(position2[0] + MathUtils.randFloatSpread(radius), position2[1] + MathUtils.randFloatSpread(radius), position2[2] + MathUtils.randFloatSpread(radius)); } else { let lambda = Math.acos(2 * Math.random() - 1) - Math.PI / 2; let phi = 2 * Math.PI * Math.random(); light.position.set(Math.cos(lambda) * Math.cos(phi) * length3, Math.abs(Math.cos(lambda) * Math.sin(phi) * length3), Math.sin(lambda) * length3); } } } }, [radius, ambient, length3, ...position2]); const api = React101.useMemo(() => ({ update: update2 }), [update2]); React101.useImperativeHandle(forwardRef82, () => api, [api]); React101.useLayoutEffect(() => { var _parent$lights; const group = gLights.current; if (parent) (_parent$lights = parent.lights) == null || _parent$lights.set(group.uuid, api); return () => { var _parent$lights2; return void (parent == null || (_parent$lights2 = parent.lights) == null ? void 0 : _parent$lights2.delete(group.uuid)); }; }, [parent, api]); return React101.createElement("group", _extends({ ref: gLights }, props), Array.from({ length: amount }, (_, index2) => React101.createElement("directionalLight", { key: index2, castShadow, "shadow-bias": bias, "shadow-mapSize": [mapSize, mapSize], intensity: intensity / amount }, React101.createElement("orthographicCamera", { attach: "shadow-camera", args: [-size2, size2, size2, -size2, near, far] })))); }); var ProgressiveLightMap2 = class { constructor(renderer, scene, res = 1024) { this.renderer = renderer; this.res = res; this.scene = scene; this.buffer1Active = false; this.lights = []; this.meshes = []; this.object = null; this.clearColor = new Color(); this.clearAlpha = 0; const textureParams = { type: HalfFloatType, magFilter: NearestFilter, minFilter: NearestFilter }; this.progressiveLightMap1 = new WebGLRenderTarget(this.res, this.res, textureParams); this.progressiveLightMap2 = new WebGLRenderTarget(this.res, this.res, textureParams); this.discardMat = new DiscardMaterial(); this.targetMat = new MeshLambertMaterial({ fog: false }); this.previousShadowMap = { value: this.progressiveLightMap1.texture }; this.averagingWindow = { value: 100 }; this.targetMat.onBeforeCompile = (shader) => { shader.vertexShader = "varying vec2 vUv;\n" + shader.vertexShader.slice(0, -1) + "vUv = uv; gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }"; const bodyStart = shader.fragmentShader.indexOf("void main() {"); shader.fragmentShader = "varying vec2 vUv;\n" + shader.fragmentShader.slice(0, bodyStart) + "uniform sampler2D previousShadowMap;\n uniform float averagingWindow;\n" + shader.fragmentShader.slice(bodyStart - 1, -1) + ` vec3 texelOld = texture2D(previousShadowMap, vUv).rgb; gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/ averagingWindow); }`; shader.uniforms.previousShadowMap = this.previousShadowMap; shader.uniforms.averagingWindow = this.averagingWindow; }; } clear() { this.renderer.getClearColor(this.clearColor); this.clearAlpha = this.renderer.getClearAlpha(); this.renderer.setClearColor("black", 1); this.renderer.setRenderTarget(this.progressiveLightMap1); this.renderer.clear(); this.renderer.setRenderTarget(this.progressiveLightMap2); this.renderer.clear(); this.renderer.setRenderTarget(null); this.renderer.setClearColor(this.clearColor, this.clearAlpha); this.lights = []; this.meshes = []; this.scene.traverse((object) => { if (isGeometry(object)) { this.meshes.push({ object, material: object.material }); } else if (isLight3(object)) { this.lights.push({ object, intensity: object.intensity }); } }); } prepare() { this.lights.forEach((light) => light.object.intensity = 0); this.meshes.forEach((mesh) => mesh.object.material = this.discardMat); } finish() { this.lights.forEach((light) => light.object.intensity = light.intensity); this.meshes.forEach((mesh) => mesh.object.material = mesh.material); } configure(object) { this.object = object; } update(camera, blendWindow = 100) { if (!this.object) return; this.averagingWindow.value = blendWindow; this.object.material = this.targetMat; const activeMap = this.buffer1Active ? this.progressiveLightMap1 : this.progressiveLightMap2; const inactiveMap = this.buffer1Active ? this.progressiveLightMap2 : this.progressiveLightMap1; const oldBg = this.scene.background; this.scene.background = null; this.renderer.setRenderTarget(activeMap); this.previousShadowMap.value = inactiveMap.texture; this.buffer1Active = !this.buffer1Active; this.renderer.render(this.scene, camera); this.renderer.setRenderTarget(null); this.scene.background = oldBg; } }; // node_modules/@react-three/drei/core/Stage.js var presets = { rembrandt: { main: [1, 2, 1], fill: [-2, -0.5, -2] }, portrait: { main: [-1, 2, 0.5], fill: [-1, 0.5, -1.5] }, upfront: { main: [0, 2, 1], fill: [-1, 0.5, -1.5] }, soft: { main: [-2, 4, 4], fill: [-1, 0.5, -1.5] } }; function Refit({ radius, adjustCamera }) { const api = useBounds(); React102.useEffect(() => { if (adjustCamera) api.refresh().clip().fit(); }, [radius, adjustCamera]); return null; } function Stage({ children, center: center3, adjustCamera = true, intensity = 0.5, shadows = "contact", environment = "city", preset = "rembrandt", ...props }) { var _bias, _normalBias, _size, _offset2, _amount, _radius, _ambient, _intensity; const config = typeof preset === "string" ? presets[preset] : preset; const [{ radius, height }, set] = React102.useState({ radius: 0, width: 0, height: 0, depth: 0 }); const shadowBias = (_bias = shadows == null ? void 0 : shadows.bias) !== null && _bias !== void 0 ? _bias : -1e-4; const normalBias = (_normalBias = shadows == null ? void 0 : shadows.normalBias) !== null && _normalBias !== void 0 ? _normalBias : 0; const shadowSize = (_size = shadows == null ? void 0 : shadows.size) !== null && _size !== void 0 ? _size : 1024; const shadowOffset = (_offset2 = shadows == null ? void 0 : shadows.offset) !== null && _offset2 !== void 0 ? _offset2 : 0; const contactShadow = shadows === "contact" || (shadows == null ? void 0 : shadows.type) === "contact"; const accumulativeShadow = shadows === "accumulative" || (shadows == null ? void 0 : shadows.type) === "accumulative"; const shadowSpread = { ...typeof shadows === "object" ? shadows : {} }; const environmentProps = !environment ? null : typeof environment === "string" ? { preset: environment } : environment; const onCentered = React102.useCallback((props2) => { const { width, height: height2, depth, boundingSphere } = props2; set({ radius: boundingSphere.radius, width, height: height2, depth }); if (center3 != null && center3.onCentered) center3.onCentered(props2); }, []); return React102.createElement(React102.Fragment, null, React102.createElement("ambientLight", { intensity: intensity / 3 }), React102.createElement("spotLight", { penumbra: 1, position: [config.main[0] * radius, config.main[1] * radius, config.main[2] * radius], intensity: intensity * 2, castShadow: !!shadows, "shadow-bias": shadowBias, "shadow-normalBias": normalBias, "shadow-mapSize": shadowSize }), React102.createElement("pointLight", { position: [config.fill[0] * radius, config.fill[1] * radius, config.fill[2] * radius], intensity }), React102.createElement(Bounds, _extends({ fit: !!adjustCamera, clip: !!adjustCamera, margin: Number(adjustCamera), observe: true }, props), React102.createElement(Refit, { radius, adjustCamera }), React102.createElement(Center, _extends({}, center3, { position: [0, shadowOffset / 2, 0], onCentered }), children)), React102.createElement("group", { position: [0, -height / 2 - shadowOffset / 2, 0] }, contactShadow && React102.createElement(ContactShadows, _extends({ scale: radius * 4, far: radius, blur: 2 }, shadowSpread)), accumulativeShadow && React102.createElement(AccumulativeShadows, _extends({ temporal: true, frames: 100, alphaTest: 0.9, toneMapped: true, scale: radius * 4 }, shadowSpread), React102.createElement(RandomizedLight, { amount: (_amount = shadowSpread.amount) !== null && _amount !== void 0 ? _amount : 8, radius: (_radius = shadowSpread.radius) !== null && _radius !== void 0 ? _radius : radius, ambient: (_ambient = shadowSpread.ambient) !== null && _ambient !== void 0 ? _ambient : 0.5, intensity: (_intensity = shadowSpread.intensity) !== null && _intensity !== void 0 ? _intensity : 1, position: [config.main[0] * radius, config.main[1] * radius, config.main[2] * radius], size: radius * 4, bias: -shadowBias, mapSize: shadowSize }))), environment && React102.createElement(Environment, environmentProps)); } // node_modules/@react-three/drei/core/Backdrop.js var React103 = __toESM(require_react()); var easeInExpo = (x) => x === 0 ? 0 : Math.pow(2, 10 * x - 10); function Backdrop({ children, floor = 0.25, segments = 20, receiveShadow, ...props }) { const ref = React103.useRef(null); React103.useLayoutEffect(() => { let i4 = 0; const offset = segments / segments / 2; const position2 = ref.current.attributes.position; for (let x = 0; x < segments + 1; x++) { for (let y = 0; y < segments + 1; y++) { position2.setXYZ(i4++, x / segments - offset + (x === 0 ? -floor : 0), y / segments - offset, easeInExpo(x / segments)); } } position2.needsUpdate = true; ref.current.computeVertexNormals(); }, [segments, floor]); return React103.createElement("group", props, React103.createElement("mesh", { receiveShadow, rotation: [-Math.PI / 2, 0, Math.PI / 2] }, React103.createElement("planeGeometry", { ref, args: [1, 1, segments, segments] }), children)); } // node_modules/@react-three/drei/core/Shadow.js var React104 = __toESM(require_react()); var Shadow = React104.forwardRef(({ fog = false, renderOrder, depthWrite = false, colorStop = 0, color = "black", opacity = 0.5, ...props }, ref) => { const canvas = React104.useMemo(() => { const canvas2 = document.createElement("canvas"); canvas2.width = 128; canvas2.height = 128; const context12 = canvas2.getContext("2d"); const gradient = context12.createRadialGradient(canvas2.width / 2, canvas2.height / 2, 0, canvas2.width / 2, canvas2.height / 2, canvas2.width / 2); gradient.addColorStop(colorStop, new Color(color).getStyle()); gradient.addColorStop(1, "rgba(0,0,0,0)"); context12.fillStyle = gradient; context12.fillRect(0, 0, canvas2.width, canvas2.height); return canvas2; }, [color, colorStop]); return React104.createElement("mesh", _extends({ renderOrder, ref, "rotation-x": -Math.PI / 2 }, props), React104.createElement("planeGeometry", null), React104.createElement("meshBasicMaterial", { transparent: true, opacity, fog, depthWrite, side: DoubleSide }, React104.createElement("canvasTexture", { attach: "map", args: [canvas] }))); }); // node_modules/@react-three/drei/core/Caustics.js var React105 = __toESM(require_react()); function createNormalMaterial(side = FrontSide) { const viewMatrix = { value: new Matrix4() }; return Object.assign(new MeshNormalMaterial({ side }), { viewMatrix, onBeforeCompile: (shader) => { shader.uniforms.viewMatrix = viewMatrix; shader.fragmentShader = `vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); } ` + shader.fragmentShader.replace("#include ", `#include normal = inverseTransformDirection( normal, viewMatrix ); `); } }); } var CausticsProjectionMaterial = shaderMaterial({ causticsTexture: null, causticsTextureB: null, color: new Color(), lightProjMatrix: new Matrix4(), lightViewMatrix: new Matrix4() }, `varying vec3 vWorldPosition; void main() { gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.); vec4 worldPosition = modelMatrix * vec4(position, 1.); vWorldPosition = worldPosition.xyz; }`, `varying vec3 vWorldPosition; uniform vec3 color; uniform sampler2D causticsTexture; uniform sampler2D causticsTextureB; uniform mat4 lightProjMatrix; uniform mat4 lightViewMatrix; void main() { // Apply caustics vec4 lightSpacePos = lightProjMatrix * lightViewMatrix * vec4(vWorldPosition, 1.0); lightSpacePos.xyz /= lightSpacePos.w; lightSpacePos.xyz = lightSpacePos.xyz * 0.5 + 0.5; vec3 front = texture2D(causticsTexture, lightSpacePos.xy).rgb; vec3 back = texture2D(causticsTextureB, lightSpacePos.xy).rgb; gl_FragColor = vec4((front + back) * color, 1.0); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }`); var CausticsMaterial = shaderMaterial( { cameraMatrixWorld: new Matrix4(), cameraProjectionMatrixInv: new Matrix4(), normalTexture: null, depthTexture: null, lightDir: new Vector3(0, 1, 0), lightPlaneNormal: new Vector3(0, 1, 0), lightPlaneConstant: 0, near: 0.1, far: 100, modelMatrix: new Matrix4(), worldRadius: 1 / 40, ior: 1.1, bounces: 0, resolution: 1024, size: 10, intensity: 0.5 }, /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`, /* glsl */ ` uniform mat4 cameraMatrixWorld; uniform mat4 cameraProjectionMatrixInv; uniform vec3 lightDir; uniform vec3 lightPlaneNormal; uniform float lightPlaneConstant; uniform float near; uniform float far; uniform float time; uniform float worldRadius; uniform float resolution; uniform float size; uniform float intensity; uniform float ior; precision highp isampler2D; precision highp usampler2D; uniform sampler2D normalTexture; uniform sampler2D depthTexture; uniform float bounces; varying vec2 vUv; vec3 WorldPosFromDepth(float depth, vec2 coord) { float z = depth * 2.0 - 1.0; vec4 clipSpacePosition = vec4(coord * 2.0 - 1.0, z, 1.0); vec4 viewSpacePosition = cameraProjectionMatrixInv * clipSpacePosition; // Perspective division viewSpacePosition /= viewSpacePosition.w; vec4 worldSpacePosition = cameraMatrixWorld * viewSpacePosition; return worldSpacePosition.xyz; } float sdPlane( vec3 p, vec3 n, float h ) { // n must be normalized return dot(p,n) + h; } float planeIntersect( vec3 ro, vec3 rd, vec4 p ) { return -(dot(ro,p.xyz)+p.w)/dot(rd,p.xyz); } vec3 totalInternalReflection(vec3 ro, vec3 rd, vec3 pos, vec3 normal, float ior, out vec3 rayOrigin, out vec3 rayDirection) { rayOrigin = ro; rayDirection = rd; rayDirection = refract(rayDirection, normal, 1.0 / ior); rayOrigin = pos + rayDirection * 0.1; return rayDirection; } void main() { // Each sample consists of random offset in the x and y direction float caustic = 0.0; float causticTexelSize = (1.0 / resolution) * size * 2.0; float texelsNeeded = worldRadius / causticTexelSize; float sampleRadius = texelsNeeded / resolution; float sum = 0.0; if (texture2D(depthTexture, vUv).x == 1.0) { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); return; } vec2 offset1 = vec2(-0.5, -0.5);//vec2(rand() - 0.5, rand() - 0.5); vec2 offset2 = vec2(-0.5, 0.5);//vec2(rand() - 0.5, rand() - 0.5); vec2 offset3 = vec2(0.5, 0.5);//vec2(rand() - 0.5, rand() - 0.5); vec2 offset4 = vec2(0.5, -0.5);//vec2(rand() - 0.5, rand() - 0.5); vec2 uv1 = vUv + offset1 * sampleRadius; vec2 uv2 = vUv + offset2 * sampleRadius; vec2 uv3 = vUv + offset3 * sampleRadius; vec2 uv4 = vUv + offset4 * sampleRadius; vec3 normal1 = texture2D(normalTexture, uv1, -10.0).rgb * 2.0 - 1.0; vec3 normal2 = texture2D(normalTexture, uv2, -10.0).rgb * 2.0 - 1.0; vec3 normal3 = texture2D(normalTexture, uv3, -10.0).rgb * 2.0 - 1.0; vec3 normal4 = texture2D(normalTexture, uv4, -10.0).rgb * 2.0 - 1.0; float depth1 = texture2D(depthTexture, uv1, -10.0).x; float depth2 = texture2D(depthTexture, uv2, -10.0).x; float depth3 = texture2D(depthTexture, uv3, -10.0).x; float depth4 = texture2D(depthTexture, uv4, -10.0).x; // Sanity check the depths if (depth1 == 1.0 || depth2 == 1.0 || depth3 == 1.0 || depth4 == 1.0) { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); return; } vec3 pos1 = WorldPosFromDepth(depth1, uv1); vec3 pos2 = WorldPosFromDepth(depth2, uv2); vec3 pos3 = WorldPosFromDepth(depth3, uv3); vec3 pos4 = WorldPosFromDepth(depth4, uv4); vec3 originPos1 = WorldPosFromDepth(0.0, uv1); vec3 originPos2 = WorldPosFromDepth(0.0, uv2); vec3 originPos3 = WorldPosFromDepth(0.0, uv3); vec3 originPos4 = WorldPosFromDepth(0.0, uv4); vec3 endPos1, endPos2, endPos3, endPos4; vec3 endDir1, endDir2, endDir3, endDir4; totalInternalReflection(originPos1, lightDir, pos1, normal1, ior, endPos1, endDir1); totalInternalReflection(originPos2, lightDir, pos2, normal2, ior, endPos2, endDir2); totalInternalReflection(originPos3, lightDir, pos3, normal3, ior, endPos3, endDir3); totalInternalReflection(originPos4, lightDir, pos4, normal4, ior, endPos4, endDir4); float lightPosArea = length(cross(originPos2 - originPos1, originPos3 - originPos1)) + length(cross(originPos3 - originPos1, originPos4 - originPos1)); float t1 = planeIntersect(endPos1, endDir1, vec4(lightPlaneNormal, lightPlaneConstant)); float t2 = planeIntersect(endPos2, endDir2, vec4(lightPlaneNormal, lightPlaneConstant)); float t3 = planeIntersect(endPos3, endDir3, vec4(lightPlaneNormal, lightPlaneConstant)); float t4 = planeIntersect(endPos4, endDir4, vec4(lightPlaneNormal, lightPlaneConstant)); vec3 finalPos1 = endPos1 + endDir1 * t1; vec3 finalPos2 = endPos2 + endDir2 * t2; vec3 finalPos3 = endPos3 + endDir3 * t3; vec3 finalPos4 = endPos4 + endDir4 * t4; float finalArea = length(cross(finalPos2 - finalPos1, finalPos3 - finalPos1)) + length(cross(finalPos3 - finalPos1, finalPos4 - finalPos1)); caustic += intensity * (lightPosArea / finalArea); // Calculate the area of the triangle in light spaces gl_FragColor = vec4(vec3(max(caustic, 0.0)), 1.0); }` ); var NORMALPROPS = { depth: true, minFilter: LinearFilter, magFilter: LinearFilter, type: UnsignedByteType }; var CAUSTICPROPS = { minFilter: LinearMipmapLinearFilter, magFilter: LinearFilter, type: FloatType, generateMipmaps: true }; var Caustics = React105.forwardRef(({ debug, children, frames = 1, ior = 1.1, color = "white", causticsOnly = false, backside = false, backsideIOR = 1.1, worldRadius = 0.3125, intensity = 0.05, resolution = 2024, lightSource = [5, 5, 5], ...props }, fref) => { extend({ CausticsProjectionMaterial }); const ref = React105.useRef(null); const camera = React105.useRef(null); const scene = React105.useRef(null); const plane = React105.useRef(null); const gl = useThree((state) => state.gl); const helper = useHelper(debug && camera, CameraHelper); const normalTarget = useFBO(resolution, resolution, NORMALPROPS); const normalTargetB = useFBO(resolution, resolution, NORMALPROPS); const causticsTarget = useFBO(resolution, resolution, CAUSTICPROPS); const causticsTargetB = useFBO(resolution, resolution, CAUSTICPROPS); const [normalMat] = React105.useState(() => createNormalMaterial()); const [normalMatB] = React105.useState(() => createNormalMaterial(BackSide)); const [causticsMaterial] = React105.useState(() => new CausticsMaterial()); const [causticsQuad] = React105.useState(() => new FullScreenQuad(causticsMaterial)); React105.useLayoutEffect(() => { ref.current.updateWorldMatrix(false, true); }); let count = 0; const v5 = new Vector3(); const lpF = new Frustum(); const lpM = new Matrix4(); const lpP = new Plane(); const lightDir = new Vector3(); const lightDirInv = new Vector3(); const bounds = new Box3(); const focusPos = new Vector3(); const boundsVertices = []; const worldVerts = []; const projectedVerts = []; const lightDirs = []; const cameraPos = new Vector3(); for (let i4 = 0; i4 < 8; i4++) { boundsVertices.push(new Vector3()); worldVerts.push(new Vector3()); projectedVerts.push(new Vector3()); lightDirs.push(new Vector3()); } useFrame(() => { if (frames === Infinity || count++ < frames) { var _scene$current$parent, _helper$current; if (Array.isArray(lightSource)) lightDir.fromArray(lightSource).normalize(); else lightDir.copy(ref.current.worldToLocal(lightSource.current.getWorldPosition(v5)).normalize()); lightDirInv.copy(lightDir).multiplyScalar(-1); (_scene$current$parent = scene.current.parent) == null || _scene$current$parent.matrixWorld.identity(); bounds.setFromObject(scene.current, true); boundsVertices[0].set(bounds.min.x, bounds.min.y, bounds.min.z); boundsVertices[1].set(bounds.min.x, bounds.min.y, bounds.max.z); boundsVertices[2].set(bounds.min.x, bounds.max.y, bounds.min.z); boundsVertices[3].set(bounds.min.x, bounds.max.y, bounds.max.z); boundsVertices[4].set(bounds.max.x, bounds.min.y, bounds.min.z); boundsVertices[5].set(bounds.max.x, bounds.min.y, bounds.max.z); boundsVertices[6].set(bounds.max.x, bounds.max.y, bounds.min.z); boundsVertices[7].set(bounds.max.x, bounds.max.y, bounds.max.z); for (let i4 = 0; i4 < 8; i4++) { worldVerts[i4].copy(boundsVertices[i4]); } bounds.getCenter(focusPos); boundsVertices.map((v6) => v6.sub(focusPos)); const lightPlane = lpP.set(lightDirInv, 0); boundsVertices.map((v6, i4) => lightPlane.projectPoint(v6, projectedVerts[i4])); const centralVert = projectedVerts.reduce((a6, b5) => a6.add(b5), v5.set(0, 0, 0)).divideScalar(projectedVerts.length); const radius = projectedVerts.map((v6) => v6.distanceTo(centralVert)).reduce((a6, b5) => Math.max(a6, b5)); const dirLength = boundsVertices.map((x) => x.dot(lightDir)).reduce((a6, b5) => Math.max(a6, b5)); camera.current.position.copy(cameraPos.copy(lightDir).multiplyScalar(dirLength).add(focusPos)); camera.current.lookAt(scene.current.localToWorld(focusPos)); const dirMatrix = lpM.lookAt(camera.current.position, focusPos, v5.set(0, 1, 0)); camera.current.left = -radius; camera.current.right = radius; camera.current.top = radius; camera.current.bottom = -radius; const yOffset = v5.set(0, radius, 0).applyMatrix4(dirMatrix); const yTime = (camera.current.position.y + yOffset.y) / lightDir.y; camera.current.near = 0.1; camera.current.far = yTime; camera.current.updateProjectionMatrix(); camera.current.updateMatrixWorld(); const groundProjectedCoords = worldVerts.map((v6, i4) => v6.add(lightDirs[i4].copy(lightDir).multiplyScalar(-v6.y / lightDir.y))); const centerPos = groundProjectedCoords.reduce((a6, b5) => a6.add(b5), v5.set(0, 0, 0)).divideScalar(groundProjectedCoords.length); const maxSize = 2 * groundProjectedCoords.map((v6) => Math.hypot(v6.x - centerPos.x, v6.z - centerPos.z)).reduce((a6, b5) => Math.max(a6, b5)); plane.current.scale.setScalar(maxSize); plane.current.position.copy(centerPos); if (debug) (_helper$current = helper.current) == null || _helper$current.update(); normalMatB.viewMatrix.value = normalMat.viewMatrix.value = camera.current.matrixWorldInverse; const dirLightNearPlane = lpF.setFromProjectionMatrix(lpM.multiplyMatrices(camera.current.projectionMatrix, camera.current.matrixWorldInverse)).planes[4]; causticsMaterial.cameraMatrixWorld = camera.current.matrixWorld; causticsMaterial.cameraProjectionMatrixInv = camera.current.projectionMatrixInverse; causticsMaterial.lightDir = lightDirInv; causticsMaterial.lightPlaneNormal = dirLightNearPlane.normal; causticsMaterial.lightPlaneConstant = dirLightNearPlane.constant; causticsMaterial.near = camera.current.near; causticsMaterial.far = camera.current.far; causticsMaterial.resolution = resolution; causticsMaterial.size = radius; causticsMaterial.intensity = intensity; causticsMaterial.worldRadius = worldRadius; scene.current.visible = true; gl.setRenderTarget(normalTarget); gl.clear(); scene.current.overrideMaterial = normalMat; gl.render(scene.current, camera.current); gl.setRenderTarget(normalTargetB); gl.clear(); if (backside) { scene.current.overrideMaterial = normalMatB; gl.render(scene.current, camera.current); } scene.current.overrideMaterial = null; causticsMaterial.ior = ior; plane.current.material.lightProjMatrix = camera.current.projectionMatrix; plane.current.material.lightViewMatrix = camera.current.matrixWorldInverse; causticsMaterial.normalTexture = normalTarget.texture; causticsMaterial.depthTexture = normalTarget.depthTexture; gl.setRenderTarget(causticsTarget); gl.clear(); causticsQuad.render(gl); causticsMaterial.ior = backsideIOR; causticsMaterial.normalTexture = normalTargetB.texture; causticsMaterial.depthTexture = normalTargetB.depthTexture; gl.setRenderTarget(causticsTargetB); gl.clear(); if (backside) causticsQuad.render(gl); gl.setRenderTarget(null); if (causticsOnly) scene.current.visible = false; } }); React105.useImperativeHandle(fref, () => ref.current, []); return React105.createElement("group", _extends({ ref }, props), React105.createElement("scene", { ref: scene }, React105.createElement("orthographicCamera", { ref: camera, up: [0, 1, 0] }), children), React105.createElement("mesh", { renderOrder: 2, ref: plane, "rotation-x": -Math.PI / 2 }, React105.createElement("planeGeometry", null), React105.createElement("causticsProjectionMaterial", { transparent: true, color, causticsTexture: causticsTarget.texture, causticsTextureB: causticsTargetB.texture, blending: CustomBlending, blendSrc: OneFactor, blendDst: SrcAlphaFactor, depthWrite: false }), debug && React105.createElement(Edges, null, React105.createElement("lineBasicMaterial", { color: "#ffff00", toneMapped: false })))); }); // node_modules/@react-three/drei/core/SpotLight.js var React106 = __toESM(require_react()); // node_modules/@react-three/drei/materials/SpotLightMaterial.js var SpotLightMaterial = class extends ShaderMaterial { constructor() { super({ uniforms: { depth: { value: null }, opacity: { value: 1 }, attenuation: { value: 2.5 }, anglePower: { value: 12 }, spotPosition: { value: new Vector3(0, 0, 0) }, lightColor: { value: new Color("white") }, cameraNear: { value: 0 }, cameraFar: { value: 1 }, resolution: { value: new Vector2(0, 0) } }, transparent: true, depthWrite: false, vertexShader: ( /* glsl */ ` varying vec3 vNormal; varying float vViewZ; varying float vIntensity; uniform vec3 spotPosition; uniform float attenuation; #include #include void main() { // compute intensity vNormal = normalize(normalMatrix * normal); vec4 worldPosition = modelMatrix * vec4(position, 1); vec4 viewPosition = viewMatrix * worldPosition; vViewZ = viewPosition.z; vIntensity = 1.0 - saturate(distance(worldPosition.xyz, spotPosition) / attenuation); gl_Position = projectionMatrix * viewPosition; #include } ` ), fragmentShader: ( /* glsl */ ` varying vec3 vNormal; varying float vViewZ; varying float vIntensity; uniform vec3 lightColor; uniform float anglePower; uniform sampler2D depth; uniform vec2 resolution; uniform float cameraNear; uniform float cameraFar; uniform float opacity; #include #include float readDepth(sampler2D depthSampler, vec2 uv) { float fragCoordZ = texture(depthSampler, uv).r; // https://github.com/mrdoob/three.js/issues/23072 #ifdef USE_LOGDEPTHBUF float viewZ = 1.0 - exp2(fragCoordZ * log(cameraFar + 1.0) / log(2.0)); #else float viewZ = perspectiveDepthToViewZ(fragCoordZ, cameraNear, cameraFar); #endif return viewZ; } void main() { #include vec3 normal = vec3(vNormal.x, vNormal.y, abs(vNormal.z)); float angleIntensity = pow(dot(normal, vec3(0, 0, 1)), anglePower); float intensity = vIntensity * angleIntensity; // fades when z is close to sampled depth, meaning the cone is intersecting existing geometry bool isSoft = resolution[0] > 0.0 && resolution[1] > 0.0; if (isSoft) { vec2 uv = gl_FragCoord.xy / resolution; intensity *= smoothstep(0.0, 1.0, vViewZ - readDepth(depth, uv)); } gl_FragColor = vec4(lightColor, intensity * opacity); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> } ` ) }); } }; // node_modules/@react-three/drei/helpers/glsl/DefaultSpotlightShadowShadows.glsl.js var SpotlightShadowShader = "#define GLSLIFY 1\nvarying vec2 vUv;uniform sampler2D uShadowMap;uniform float uTime;void main(){vec3 color=texture2D(uShadowMap,vUv).xyz;gl_FragColor=vec4(color,1.);}"; // node_modules/@react-three/drei/core/SpotLight.js var isSpotLight = (child) => { return child == null ? void 0 : child.isSpotLight; }; function VolumetricMesh({ opacity = 1, radiusTop, radiusBottom, depthBuffer, color = "white", distance: distance3 = 5, angle = 0.15, attenuation = 5, anglePower = 5 }) { const mesh = React106.useRef(null); const size2 = useThree((state) => state.size); const camera = useThree((state) => state.camera); const dpr = useThree((state) => state.viewport.dpr); const [material] = React106.useState(() => new SpotLightMaterial()); const [vec] = React106.useState(() => new Vector3()); radiusTop = radiusTop === void 0 ? 0.1 : radiusTop; radiusBottom = radiusBottom === void 0 ? angle * 7 : radiusBottom; useFrame(() => { material.uniforms.spotPosition.value.copy(mesh.current.getWorldPosition(vec)); mesh.current.lookAt(mesh.current.parent.target.getWorldPosition(vec)); }); const geom = React106.useMemo(() => { const geometry3 = new CylinderGeometry(radiusTop, radiusBottom, distance3, 128, 64, true); geometry3.applyMatrix4(new Matrix4().makeTranslation(0, -distance3 / 2, 0)); geometry3.applyMatrix4(new Matrix4().makeRotationX(-Math.PI / 2)); return geometry3; }, [distance3, radiusTop, radiusBottom]); return React106.createElement(React106.Fragment, null, React106.createElement("mesh", { ref: mesh, geometry: geom, raycast: () => null }, React106.createElement("primitive", { object: material, attach: "material", "uniforms-opacity-value": opacity, "uniforms-lightColor-value": color, "uniforms-attenuation-value": attenuation, "uniforms-anglePower-value": anglePower, "uniforms-depth-value": depthBuffer, "uniforms-cameraNear-value": camera.near, "uniforms-cameraFar-value": camera.far, "uniforms-resolution-value": depthBuffer ? [size2.width * dpr, size2.height * dpr] : [0, 0] }))); } function useCommon(spotlight, mesh, width, height, distance3) { const [[pos, dir]] = React106.useState(() => [new Vector3(), new Vector3()]); React106.useLayoutEffect(() => { if (isSpotLight(spotlight.current)) { spotlight.current.shadow.mapSize.set(width, height); spotlight.current.shadow.needsUpdate = true; } else { throw new Error("SpotlightShadow must be a child of a SpotLight"); } }, [spotlight, width, height]); useFrame(() => { if (!spotlight.current) return; const A = spotlight.current.position; const B = spotlight.current.target.position; dir.copy(B).sub(A); var len = dir.length(); dir.normalize().multiplyScalar(len * distance3); pos.copy(A).add(dir); mesh.current.position.copy(pos); mesh.current.lookAt(spotlight.current.target.position); }); } function SpotlightShadowWithShader({ distance: distance3 = 0.4, alphaTest = 0.5, map: map2, shader = SpotlightShadowShader, width = 512, height = 512, scale: scale5 = 1, children, ...rest }) { const mesh = React106.useRef(null); const spotlight = rest.spotlightRef; const debug = rest.debug; useCommon(spotlight, mesh, width, height, distance3); const renderTarget = React106.useMemo(() => new WebGLRenderTarget(width, height, { format: RGBAFormat, stencilBuffer: false // depthTexture: null! }), [width, height]); const uniforms = React106.useRef({ uShadowMap: { value: map2 }, uTime: { value: 0 } }); React106.useEffect(() => void (uniforms.current.uShadowMap.value = map2), [map2]); const fsQuad = React106.useMemo(() => new FullScreenQuad(new ShaderMaterial({ uniforms: uniforms.current, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } ` ), fragmentShader: shader })), [shader]); React106.useEffect(() => () => { fsQuad.material.dispose(); fsQuad.dispose(); }, [fsQuad]); React106.useEffect(() => () => renderTarget.dispose(), [renderTarget]); useFrame(({ gl }, dt) => { uniforms.current.uTime.value += dt; gl.setRenderTarget(renderTarget); fsQuad.render(gl); gl.setRenderTarget(null); }); return React106.createElement(React106.Fragment, null, React106.createElement("mesh", { ref: mesh, scale: scale5, castShadow: true }, React106.createElement("planeGeometry", null), React106.createElement("meshBasicMaterial", { transparent: true, side: DoubleSide, alphaTest, alphaMap: renderTarget.texture, "alphaMap-wrapS": RepeatWrapping, "alphaMap-wrapT": RepeatWrapping, opacity: debug ? 1 : 0 }, children))); } function SpotlightShadowWithoutShader({ distance: distance3 = 0.4, alphaTest = 0.5, map: map2, width = 512, height = 512, scale: scale5, children, ...rest }) { const mesh = React106.useRef(null); const spotlight = rest.spotlightRef; const debug = rest.debug; useCommon(spotlight, mesh, width, height, distance3); return React106.createElement(React106.Fragment, null, React106.createElement("mesh", { ref: mesh, scale: scale5, castShadow: true }, React106.createElement("planeGeometry", null), React106.createElement("meshBasicMaterial", { transparent: true, side: DoubleSide, alphaTest, alphaMap: map2, "alphaMap-wrapS": RepeatWrapping, "alphaMap-wrapT": RepeatWrapping, opacity: debug ? 1 : 0 }, children))); } function SpotLightShadow(props) { if (props.shader) return React106.createElement(SpotlightShadowWithShader, props); return React106.createElement(SpotlightShadowWithoutShader, props); } var SpotLight2 = React106.forwardRef(({ // Volumetric opacity = 1, radiusTop, radiusBottom, depthBuffer, color = "white", distance: distance3 = 5, angle = 0.15, attenuation = 5, anglePower = 5, volumetric = true, debug = false, children, ...props }, ref) => { const spotlight = React106.useRef(null); React106.useImperativeHandle(ref, () => spotlight.current, []); return React106.createElement("group", null, debug && spotlight.current && React106.createElement("spotLightHelper", { args: [spotlight.current] }), React106.createElement("spotLight", _extends({ ref: spotlight, angle, color, distance: distance3, castShadow: true }, props), volumetric && React106.createElement(VolumetricMesh, { debug, opacity, radiusTop, radiusBottom, depthBuffer, color, distance: distance3, angle, attenuation, anglePower })), children && React106.cloneElement(children, { spotlightRef: spotlight, debug })); }); // node_modules/@react-three/drei/core/Lightformer.js var React107 = __toESM(require_react()); var Lightformer = React107.forwardRef(({ light, args, map: map2, toneMapped = false, color = "white", form: Form = "rect", intensity = 1, scale: scale5 = 1, target: target2 = [0, 0, 0], children, ...props }, forwardRef82) => { const ref = React107.useRef(null); React107.useImperativeHandle(forwardRef82, () => ref.current, []); React107.useLayoutEffect(() => { if (!children && !props.material) { applyProps(ref.current.material, { color }); ref.current.material.color.multiplyScalar(intensity); } }, [color, intensity, children, props.material]); React107.useLayoutEffect(() => { if (!props.rotation) ref.current.quaternion.identity(); if (target2 && !props.rotation) { "boolean" === typeof target2 ? ref.current.lookAt(0, 0, 0) : ref.current.lookAt(Array.isArray(target2) ? new Vector3(...target2) : target2); } }, [target2, props.rotation]); scale5 = Array.isArray(scale5) && scale5.length === 2 ? [scale5[0], scale5[1], 1] : scale5; return React107.createElement("mesh", _extends({ ref, scale: scale5 }, props), Form === "circle" ? React107.createElement("ringGeometry", { args: args ? args : [0, 0.5, 64] }) : Form === "ring" ? React107.createElement("ringGeometry", { args: args ? args : [0.25, 0.5, 64] }) : Form === "rect" || Form === "plane" ? React107.createElement("planeGeometry", { args: args ? args : [1, 1] }) : Form === "box" ? React107.createElement("boxGeometry", { args: args ? args : [1, 1, 1] }) : React107.createElement(Form, { args }), children ? children : React107.createElement("meshBasicMaterial", { toneMapped, map: map2, side: DoubleSide }), light && React107.createElement("pointLight", _extends({ castShadow: true }, light))); }); // node_modules/@react-three/drei/core/Sky.js var React108 = __toESM(require_react()); function calcPosFromAngles(inclination, azimuth, vector = new Vector3()) { const theta = Math.PI * (inclination - 0.5); const phi = 2 * Math.PI * (azimuth - 0.5); vector.x = Math.cos(phi); vector.y = Math.sin(theta); vector.z = Math.sin(phi); return vector; } var Sky2 = React108.forwardRef(({ inclination = 0.6, azimuth = 0.1, distance: distance3 = 1e3, mieCoefficient = 5e-3, mieDirectionalG = 0.8, rayleigh = 0.5, turbidity = 10, sunPosition = calcPosFromAngles(inclination, azimuth), ...props }, ref) => { const scale5 = React108.useMemo(() => new Vector3().setScalar(distance3), [distance3]); const [sky] = React108.useState(() => new Sky()); return React108.createElement("primitive", _extends({ object: sky, ref, "material-uniforms-mieCoefficient-value": mieCoefficient, "material-uniforms-mieDirectionalG-value": mieDirectionalG, "material-uniforms-rayleigh-value": rayleigh, "material-uniforms-sunPosition-value": sunPosition, "material-uniforms-turbidity-value": turbidity, scale: scale5 }, props)); }); // node_modules/@react-three/drei/core/Stars.js var React109 = __toESM(require_react()); var StarfieldMaterial = class extends ShaderMaterial { constructor() { super({ uniforms: { time: { value: 0 }, fade: { value: 1 } }, vertexShader: ( /* glsl */ ` uniform float time; attribute float size; varying vec3 vColor; void main() { vColor = color; vec4 mvPosition = modelViewMatrix * vec4(position, 0.5); gl_PointSize = size * (30.0 / -mvPosition.z) * (3.0 + sin(time + 100.0)); gl_Position = projectionMatrix * mvPosition; }` ), fragmentShader: ( /* glsl */ ` uniform sampler2D pointTexture; uniform float fade; varying vec3 vColor; void main() { float opacity = 1.0; if (fade == 1.0) { float d = distance(gl_PointCoord, vec2(0.5, 0.5)); opacity = 1.0 / (1.0 + exp(16.0 * (d - 0.25))); } gl_FragColor = vec4(vColor, opacity); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }` ) }); } }; var genStar = (r2) => { return new Vector3().setFromSpherical(new Spherical(r2, Math.acos(1 - Math.random() * 2), Math.random() * 2 * Math.PI)); }; var Stars = React109.forwardRef(({ radius = 100, depth = 50, count = 5e3, saturation = 0, factor = 4, fade: fade2 = false, speed = 1 }, ref) => { const material = React109.useRef(null); const [position2, color, size2] = React109.useMemo(() => { const positions = []; const colors2 = []; const sizes = Array.from({ length: count }, () => (0.5 + 0.5 * Math.random()) * factor); const color2 = new Color(); let r2 = radius + depth; const increment = depth / count; for (let i4 = 0; i4 < count; i4++) { r2 -= increment * Math.random(); positions.push(...genStar(r2).toArray()); color2.setHSL(i4 / count, saturation, 0.9); colors2.push(color2.r, color2.g, color2.b); } return [new Float32Array(positions), new Float32Array(colors2), new Float32Array(sizes)]; }, [count, depth, factor, radius, saturation]); useFrame((state) => material.current && (material.current.uniforms.time.value = state.clock.elapsedTime * speed)); const [starfieldMaterial] = React109.useState(() => new StarfieldMaterial()); return React109.createElement("points", { ref }, React109.createElement("bufferGeometry", null, React109.createElement("bufferAttribute", { attach: "attributes-position", args: [position2, 3] }), React109.createElement("bufferAttribute", { attach: "attributes-color", args: [color, 3] }), React109.createElement("bufferAttribute", { attach: "attributes-size", args: [size2, 1] })), React109.createElement("primitive", { ref: material, object: starfieldMaterial, attach: "material", blending: AdditiveBlending, "uniforms-fade-value": fade2, depthWrite: false, transparent: true, vertexColors: true })); }); // node_modules/@react-three/drei/core/Cloud.js var React110 = __toESM(require_react()); var CLOUD_URL = "https://rawcdn.githack.com/pmndrs/drei-assets/9225a9f1fbd449d9411125c2f419b843d0308c9f/cloud.png"; var parentMatrix2 = new Matrix4(); var translation2 = new Vector3(); var rotation2 = new Quaternion(); var cpos = new Vector3(); var cquat = new Quaternion(); var scale4 = new Vector3(); var context7 = React110.createContext(null); var Clouds = React110.forwardRef(({ children, material = MeshLambertMaterial, texture = CLOUD_URL, range, limit = 200, frustumCulled, ...props }, fref) => { var _image$width, _image$height; const CloudMaterial = React110.useMemo(() => { return class extends material { constructor() { super(); const opaque_fragment2 = parseInt(REVISION.replace(/\D+/g, "")) >= 154 ? "opaque_fragment" : "output_fragment"; this.onBeforeCompile = (shader) => { shader.vertexShader = `attribute float cloudOpacity; varying float vOpacity; ` + shader.vertexShader.replace("#include ", `#include vOpacity = cloudOpacity; `); shader.fragmentShader = `varying float vOpacity; ` + shader.fragmentShader.replace(`#include <${opaque_fragment2}>`, `#include <${opaque_fragment2}> gl_FragColor = vec4(outgoingLight, diffuseColor.a * vOpacity); `); }; } }; }, [material]); extend({ CloudMaterial }); const instance2 = React110.useRef(null); const clouds = React110.useRef([]); const opacities = React110.useMemo(() => new Float32Array(Array.from({ length: limit }, () => 1)), [limit]); const colors2 = React110.useMemo(() => new Float32Array(Array.from({ length: limit }, () => [1, 1, 1]).flat()), [limit]); const cloudTexture = useTexture(texture); let t3 = 0; let index2 = 0; let config; const qat = new Quaternion(); const dir = new Vector3(0, 0, 1); const pos = new Vector3(); useFrame((state, delta) => { t3 = state.clock.elapsedTime; parentMatrix2.copy(instance2.current.matrixWorld).invert(); state.camera.matrixWorld.decompose(cpos, cquat, scale4); for (index2 = 0; index2 < clouds.current.length; index2++) { config = clouds.current[index2]; config.ref.current.matrixWorld.decompose(translation2, rotation2, scale4); translation2.add(pos.copy(config.position).applyQuaternion(rotation2).multiply(scale4)); rotation2.copy(cquat).multiply(qat.setFromAxisAngle(dir, config.rotation += delta * config.rotationFactor)); scale4.multiplyScalar(config.volume + (1 + Math.sin(t3 * config.density * config.speed)) / 2 * config.growth); config.matrix.compose(translation2, rotation2, scale4).premultiply(parentMatrix2); config.dist = translation2.distanceTo(cpos); } clouds.current.sort((a6, b5) => b5.dist - a6.dist); for (index2 = 0; index2 < clouds.current.length; index2++) { config = clouds.current[index2]; opacities[index2] = config.opacity * (config.dist < config.fade - 1 ? config.dist / config.fade : 1); instance2.current.setMatrixAt(index2, config.matrix); instance2.current.setColorAt(index2, config.color); } instance2.current.geometry.attributes.cloudOpacity.needsUpdate = true; instance2.current.instanceMatrix.needsUpdate = true; if (instance2.current.instanceColor) instance2.current.instanceColor.needsUpdate = true; }); React110.useLayoutEffect(() => { const count = Math.min(limit, range !== void 0 ? range : limit, clouds.current.length); instance2.current.count = count; setUpdateRange(instance2.current.instanceMatrix, { start: 0, count: count * 16 }); if (instance2.current.instanceColor) { setUpdateRange(instance2.current.instanceColor, { start: 0, count: count * 3 }); } setUpdateRange(instance2.current.geometry.attributes.cloudOpacity, { start: 0, count }); }); let imageBounds = [(_image$width = cloudTexture.image.width) !== null && _image$width !== void 0 ? _image$width : 1, (_image$height = cloudTexture.image.height) !== null && _image$height !== void 0 ? _image$height : 1]; const max2 = Math.max(imageBounds[0], imageBounds[1]); imageBounds = [imageBounds[0] / max2, imageBounds[1] / max2]; return React110.createElement("group", _extends({ ref: fref }, props), React110.createElement(context7.Provider, { value: clouds }, children, React110.createElement("instancedMesh", { matrixAutoUpdate: false, ref: instance2, args: [null, null, limit], frustumCulled }, React110.createElement("instancedBufferAttribute", { usage: DynamicDrawUsage, attach: "instanceColor", args: [colors2, 3] }), React110.createElement("planeGeometry", { args: [...imageBounds] }, React110.createElement("instancedBufferAttribute", { usage: DynamicDrawUsage, attach: "attributes-cloudOpacity", args: [opacities, 1] })), React110.createElement("cloudMaterial", { key: material.name, map: cloudTexture, transparent: true, depthWrite: false })))); }); var CloudInstance = React110.forwardRef(({ opacity = 1, speed = 0, bounds = [5, 1, 1], segments = 20, color = "#ffffff", fade: fade2 = 10, volume = 6, smallestVolume = 0.25, distribute = null, growth = 4, concentrate = "inside", seed: seed3 = Math.random(), ...props }, fref) => { function random() { const x = Math.sin(seed3++) * 1e4; return x - Math.floor(x); } const parent = React110.useContext(context7); const ref = React110.useRef(null); const uuid = React110.useId(); const clouds = React110.useMemo(() => { return [...new Array(segments)].map((_, index2) => ({ segments, bounds: new Vector3(1, 1, 1), position: new Vector3(), uuid, index: index2, ref, dist: 0, matrix: new Matrix4(), color: new Color(), rotation: index2 * (Math.PI / segments) })); }, [segments, uuid]); React110.useLayoutEffect(() => { clouds.forEach((cloud, index2) => { applyProps(cloud, { volume, color, speed, growth, opacity, fade: fade2, bounds, density: Math.max(0.5, random()), rotationFactor: Math.max(0.2, 0.5 * random()) * speed }); const distributed = distribute == null ? void 0 : distribute(cloud, index2); if (distributed || segments > 1) { var _distributed$point; cloud.position.copy(cloud.bounds).multiply((_distributed$point = distributed == null ? void 0 : distributed.point) !== null && _distributed$point !== void 0 ? _distributed$point : { x: random() * 2 - 1, y: random() * 2 - 1, z: random() * 2 - 1 }); } const xDiff = Math.abs(cloud.position.x); const yDiff = Math.abs(cloud.position.y); const zDiff = Math.abs(cloud.position.z); const max2 = Math.max(xDiff, yDiff, zDiff); cloud.length = 1; if (xDiff === max2) cloud.length -= xDiff / cloud.bounds.x; if (yDiff === max2) cloud.length -= yDiff / cloud.bounds.y; if (zDiff === max2) cloud.length -= zDiff / cloud.bounds.z; cloud.volume = ((distributed == null ? void 0 : distributed.volume) !== void 0 ? distributed.volume : Math.max(Math.max(0, smallestVolume), concentrate === "random" ? random() : concentrate === "inside" ? cloud.length : 1 - cloud.length)) * volume; }); }, [concentrate, bounds, fade2, color, opacity, growth, volume, seed3, segments, speed]); React110.useLayoutEffect(() => { const temp5 = clouds; parent.current = [...parent.current, ...temp5]; return () => { parent.current = parent.current.filter((item) => item.uuid !== uuid); }; }, [clouds]); React110.useImperativeHandle(fref, () => ref.current, []); return React110.createElement("group", _extends({ ref }, props)); }); var Cloud = React110.forwardRef((props, fref) => { const parent = React110.useContext(context7); if (parent) return React110.createElement(CloudInstance, _extends({ ref: fref }, props)); return React110.createElement(Clouds, null, React110.createElement(CloudInstance, _extends({ ref: fref }, props))); }); // node_modules/@react-three/drei/core/Sparkles.js var React111 = __toESM(require_react()); var SparklesImplMaterial = class extends ShaderMaterial { constructor() { super({ uniforms: { time: { value: 0 }, pixelRatio: { value: 1 } }, vertexShader: ( /* glsl */ ` uniform float pixelRatio; uniform float time; attribute float size; attribute float speed; attribute float opacity; attribute vec3 noise; attribute vec3 color; varying vec3 vColor; varying float vOpacity; void main() { vec4 modelPosition = modelMatrix * vec4(position, 1.0); modelPosition.y += sin(time * speed + modelPosition.x * noise.x * 100.0) * 0.2; modelPosition.z += cos(time * speed + modelPosition.x * noise.y * 100.0) * 0.2; modelPosition.x += cos(time * speed + modelPosition.x * noise.z * 100.0) * 0.2; vec4 viewPosition = viewMatrix * modelPosition; vec4 projectionPostion = projectionMatrix * viewPosition; gl_Position = projectionPostion; gl_PointSize = size * 25. * pixelRatio; gl_PointSize *= (1.0 / - viewPosition.z); vColor = color; vOpacity = opacity; } ` ), fragmentShader: ( /* glsl */ ` varying vec3 vColor; varying float vOpacity; void main() { float distanceToCenter = distance(gl_PointCoord, vec2(0.5)); float strength = 0.05 / distanceToCenter - 0.1; gl_FragColor = vec4(vColor, strength * vOpacity); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> } ` ) }); } get time() { return this.uniforms.time.value; } set time(value) { this.uniforms.time.value = value; } get pixelRatio() { return this.uniforms.pixelRatio.value; } set pixelRatio(value) { this.uniforms.pixelRatio.value = value; } }; var isFloat32Array = (def) => def && def.constructor === Float32Array; var expandColor = (v5) => [v5.r, v5.g, v5.b]; var isVector = (v5) => v5 instanceof Vector2 || v5 instanceof Vector3 || v5 instanceof Vector4; var normalizeVector = (v5) => { if (Array.isArray(v5)) return v5; else if (isVector(v5)) return v5.toArray(); return [v5, v5, v5]; }; function usePropAsIsOrAsAttribute(count, prop, setDefault) { return React111.useMemo(() => { if (prop !== void 0) { if (isFloat32Array(prop)) { return prop; } else { if (prop instanceof Color) { const a6 = Array.from({ length: count * 3 }, () => expandColor(prop)).flat(); return Float32Array.from(a6); } else if (isVector(prop) || Array.isArray(prop)) { const a6 = Array.from({ length: count * 3 }, () => normalizeVector(prop)).flat(); return Float32Array.from(a6); } return Float32Array.from({ length: count }, () => prop); } } return Float32Array.from({ length: count }, setDefault); }, [prop]); } var Sparkles = React111.forwardRef(({ noise: noise2 = 1, count = 100, speed = 1, opacity = 1, scale: scale5 = 1, size: size2, color, children, ...props }, forwardRef82) => { React111.useMemo(() => extend({ SparklesImplMaterial }), []); const ref = React111.useRef(null); const dpr = useThree((state) => state.viewport.dpr); const _scale3 = normalizeVector(scale5); const positions = React111.useMemo(() => Float32Array.from(Array.from({ length: count }, () => _scale3.map(MathUtils.randFloatSpread)).flat()), [count, ..._scale3]); const sizes = usePropAsIsOrAsAttribute(count, size2, Math.random); const opacities = usePropAsIsOrAsAttribute(count, opacity); const speeds = usePropAsIsOrAsAttribute(count, speed); const noises = usePropAsIsOrAsAttribute(count * 3, noise2); const colors2 = usePropAsIsOrAsAttribute(color === void 0 ? count * 3 : count, !isFloat32Array(color) ? new Color(color) : color, () => 1); useFrame((state) => { if (ref.current && ref.current.material) ref.current.material.time = state.clock.elapsedTime; }); React111.useImperativeHandle(forwardRef82, () => ref.current, []); return React111.createElement("points", _extends({ key: `particle-${count}-${JSON.stringify(scale5)}` }, props, { ref }), React111.createElement("bufferGeometry", null, React111.createElement("bufferAttribute", { attach: "attributes-position", args: [positions, 3] }), React111.createElement("bufferAttribute", { attach: "attributes-size", args: [sizes, 1] }), React111.createElement("bufferAttribute", { attach: "attributes-opacity", args: [opacities, 1] }), React111.createElement("bufferAttribute", { attach: "attributes-speed", args: [speeds, 1] }), React111.createElement("bufferAttribute", { attach: "attributes-color", args: [colors2, 3] }), React111.createElement("bufferAttribute", { attach: "attributes-noise", args: [noises, 3] })), children ? children : React111.createElement("sparklesImplMaterial", { transparent: true, pixelRatio: dpr, depthWrite: false })); }); // node_modules/@react-three/drei/core/MatcapTexture.js var React112 = __toESM(require_react()); function getFormatString(format) { switch (format) { case 64: return "-64px"; case 128: return "-128px"; case 256: return "-256px"; case 512: return "-512px"; default: return ""; } } var LIST_URL = "https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/matcaps.json"; var MATCAP_ROOT = "https://rawcdn.githack.com/emmelleppi/matcaps/9b36ccaaf0a24881a39062d05566c9e92be4aa0d"; function useMatcapTexture(id = 0, format = 1024, onLoad) { const matcapList = suspend(() => fetch(LIST_URL).then((res) => res.json()), ["matcapList"]); const DEFAULT_MATCAP = matcapList[0]; const numTot = React112.useMemo(() => Object.keys(matcapList).length, []); const fileHash = React112.useMemo(() => { if (typeof id === "string") { return id; } else if (typeof id === "number") { return matcapList[id]; } return null; }, [id]); const fileName = `${fileHash || DEFAULT_MATCAP}${getFormatString(format)}.png`; const url = `${MATCAP_ROOT}/${format}/${fileName}`; const matcapTexture = useTexture(url, onLoad); return [matcapTexture, url, numTot]; } var MatcapTexture = ({ children, id, format, onLoad }) => { const texture = useMatcapTexture(id, format, onLoad); return React112.createElement(React112.Fragment, null, children == null ? void 0 : children(texture)); }; // node_modules/@react-three/drei/core/NormalTexture.js var React113 = __toESM(require_react()); var NORMAL_ROOT = "https://rawcdn.githack.com/pmndrs/drei-assets/7a3104997e1576f83472829815b00880d88b32fb"; var LIST_URL2 = "https://cdn.jsdelivr.net/gh/pmndrs/drei-assets@master/normals/normals.json"; function useNormalTexture(id = 0, settings = {}, onLoad) { const { repeat: repeat2 = [1, 1], anisotropy = 1, offset = [0, 0] } = settings; const normalsList = suspend(() => fetch(LIST_URL2).then((res) => res.json()), ["normalsList"]); const numTot = React113.useMemo(() => Object.keys(normalsList).length, []); const DEFAULT_NORMAL = normalsList[0]; const imageName = normalsList[id] || DEFAULT_NORMAL; const url = `${NORMAL_ROOT}/normals/${imageName}`; const normalTexture = useTexture(url, onLoad); React113.useLayoutEffect(() => { if (!normalTexture) return; normalTexture.wrapS = normalTexture.wrapT = RepeatWrapping; normalTexture.repeat = new Vector2(repeat2[0], repeat2[1]); normalTexture.offset = new Vector2(offset[0], offset[1]); normalTexture.anisotropy = anisotropy; }, [normalTexture, anisotropy, repeat2, offset]); return [normalTexture, url, numTot]; } var NormalTexture = ({ children, id, onLoad, ...settings }) => { const ret = useNormalTexture(id, settings, onLoad); return React113.createElement(React113.Fragment, null, children == null ? void 0 : children(ret)); }; // node_modules/@react-three/drei/core/Wireframe.js var React115 = __toESM(require_react()); // node_modules/@react-three/drei/materials/WireframeMaterial.js var React114 = __toESM(require_react()); var WireframeMaterialShaders = { uniforms: { strokeOpacity: 1, fillOpacity: 0.25, fillMix: 0, thickness: 0.05, colorBackfaces: false, dashInvert: true, dash: false, dashRepeats: 4, dashLength: 0.5, squeeze: false, squeezeMin: 0.2, squeezeMax: 1, stroke: new Color("#ff0000"), backfaceStroke: new Color("#0000ff"), fill: new Color("#00ff00") }, vertex: ( /* glsl */ ` attribute vec3 barycentric; varying vec3 v_edges_Barycentric; varying vec3 v_edges_Position; void initWireframe() { v_edges_Barycentric = barycentric; v_edges_Position = position.xyz; } ` ), fragment: ( /* glsl */ ` #ifndef PI #define PI 3.1415926535897932384626433832795 #endif varying vec3 v_edges_Barycentric; varying vec3 v_edges_Position; uniform float strokeOpacity; uniform float fillOpacity; uniform float fillMix; uniform float thickness; uniform bool colorBackfaces; // Dash uniform bool dashInvert; uniform bool dash; uniform bool dashOnly; uniform float dashRepeats; uniform float dashLength; // Squeeze uniform bool squeeze; uniform float squeezeMin; uniform float squeezeMax; // Colors uniform vec3 stroke; uniform vec3 backfaceStroke; uniform vec3 fill; // This is like float wireframe_aastep(float threshold, float dist) { float afwidth = fwidth(dist) * 0.5; return smoothstep(threshold - afwidth, threshold + afwidth, dist); } float wireframe_map(float value, float min1, float max1, float min2, float max2) { return min2 + (value - min1) * (max2 - min2) / (max1 - min1); } float getWireframe() { vec3 barycentric = v_edges_Barycentric; // Distance from center of each triangle to its edges. float d = min(min(barycentric.x, barycentric.y), barycentric.z); // for dashed rendering, we can use this to get the 0 .. 1 value of the line length float positionAlong = max(barycentric.x, barycentric.y); if (barycentric.y < barycentric.x && barycentric.y < barycentric.z) { positionAlong = 1.0 - positionAlong; } // the thickness of the stroke float computedThickness = wireframe_map(thickness, 0.0, 1.0, 0.0, 0.34); // if we want to shrink the thickness toward the center of the line segment if (squeeze) { computedThickness *= mix(squeezeMin, squeezeMax, (1.0 - sin(positionAlong * PI))); } // Create dash pattern if (dash) { // here we offset the stroke position depending on whether it // should overlap or not float offset = 1.0 / dashRepeats * dashLength / 2.0; if (!dashInvert) { offset += 1.0 / dashRepeats / 2.0; } // if we should animate the dash or not // if (dashAnimate) { // offset += time * 0.22; // } // create the repeating dash pattern float pattern = fract((positionAlong + offset) * dashRepeats); computedThickness *= 1.0 - wireframe_aastep(dashLength, pattern); } // compute the anti-aliased stroke edge float edge = 1.0 - wireframe_aastep(computedThickness, d); return edge; } ` ) }; var WireframeMaterial = shaderMaterial(WireframeMaterialShaders.uniforms, WireframeMaterialShaders.vertex + /* glsl */ ` void main() { initWireframe(); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `, WireframeMaterialShaders.fragment + /* glsl */ ` void main () { // Compute color float edge = getWireframe(); vec4 colorStroke = vec4(stroke, edge); #ifdef FLIP_SIDED colorStroke.rgb = backfaceStroke; #endif vec4 colorFill = vec4(fill, fillOpacity); vec4 outColor = mix(colorFill, colorStroke, edge * strokeOpacity); gl_FragColor = outColor; } `); function setWireframeOverride(material, uniforms) { material.onBeforeCompile = (shader) => { shader.uniforms = { ...shader.uniforms, ...uniforms }; shader.vertexShader = shader.vertexShader.replace("void main() {", ` ${WireframeMaterialShaders.vertex} void main() { initWireframe(); `); shader.fragmentShader = shader.fragmentShader.replace("void main() {", ` ${WireframeMaterialShaders.fragment} void main() { `); shader.fragmentShader = shader.fragmentShader.replace( "#include ", /* glsl */ ` #include float edge = getWireframe(); vec4 colorStroke = vec4(stroke, edge); #ifdef FLIP_SIDED colorStroke.rgb = backfaceStroke; #endif vec4 colorFill = vec4(mix(diffuseColor.rgb, fill, fillMix), mix(diffuseColor.a, fillOpacity, fillMix)); vec4 outColor = mix(colorFill, colorStroke, edge * strokeOpacity); diffuseColor.rgb = outColor.rgb; diffuseColor.a *= outColor.a; ` ); }; material.side = DoubleSide; material.transparent = true; } function useWireframeUniforms(uniforms, props) { React114.useEffect(() => { var _props$fillOpacity; return void (uniforms.fillOpacity.value = (_props$fillOpacity = props.fillOpacity) !== null && _props$fillOpacity !== void 0 ? _props$fillOpacity : uniforms.fillOpacity.value); }, [props.fillOpacity]); React114.useEffect(() => { var _props$fillMix; return void (uniforms.fillMix.value = (_props$fillMix = props.fillMix) !== null && _props$fillMix !== void 0 ? _props$fillMix : uniforms.fillMix.value); }, [props.fillMix]); React114.useEffect(() => { var _props$strokeOpacity; return void (uniforms.strokeOpacity.value = (_props$strokeOpacity = props.strokeOpacity) !== null && _props$strokeOpacity !== void 0 ? _props$strokeOpacity : uniforms.strokeOpacity.value); }, [props.strokeOpacity]); React114.useEffect(() => { var _props$thickness; return void (uniforms.thickness.value = (_props$thickness = props.thickness) !== null && _props$thickness !== void 0 ? _props$thickness : uniforms.thickness.value); }, [props.thickness]); React114.useEffect(() => void (uniforms.colorBackfaces.value = !!props.colorBackfaces), [props.colorBackfaces]); React114.useEffect(() => void (uniforms.dash.value = !!props.dash), [props.dash]); React114.useEffect(() => void (uniforms.dashInvert.value = !!props.dashInvert), [props.dashInvert]); React114.useEffect(() => { var _props$dashRepeats; return void (uniforms.dashRepeats.value = (_props$dashRepeats = props.dashRepeats) !== null && _props$dashRepeats !== void 0 ? _props$dashRepeats : uniforms.dashRepeats.value); }, [props.dashRepeats]); React114.useEffect(() => { var _props$dashLength; return void (uniforms.dashLength.value = (_props$dashLength = props.dashLength) !== null && _props$dashLength !== void 0 ? _props$dashLength : uniforms.dashLength.value); }, [props.dashLength]); React114.useEffect(() => void (uniforms.squeeze.value = !!props.squeeze), [props.squeeze]); React114.useEffect(() => { var _props$squeezeMin; return void (uniforms.squeezeMin.value = (_props$squeezeMin = props.squeezeMin) !== null && _props$squeezeMin !== void 0 ? _props$squeezeMin : uniforms.squeezeMin.value); }, [props.squeezeMin]); React114.useEffect(() => { var _props$squeezeMax; return void (uniforms.squeezeMax.value = (_props$squeezeMax = props.squeezeMax) !== null && _props$squeezeMax !== void 0 ? _props$squeezeMax : uniforms.squeezeMax.value); }, [props.squeezeMax]); React114.useEffect(() => void (uniforms.stroke.value = props.stroke ? new Color(props.stroke) : uniforms.stroke.value), [props.stroke]); React114.useEffect(() => void (uniforms.fill.value = props.fill ? new Color(props.fill) : uniforms.fill.value), [props.fill]); React114.useEffect(() => void (uniforms.backfaceStroke.value = props.backfaceStroke ? new Color(props.backfaceStroke) : uniforms.backfaceStroke.value), [props.backfaceStroke]); } // node_modules/@react-three/drei/core/Wireframe.js function isWithGeometry(object) { return !!(object != null && object.geometry); } function isGeometry2(object) { return !!(object != null && object.isBufferGeometry); } function isRefObject2(object) { return !!(object != null && object.current); } function isRef2(object) { return (object == null ? void 0 : object.current) !== void 0; } function isWireframeGeometry(geometry3) { return geometry3.type === "WireframeGeometry"; } function getUniforms2() { const u = {}; for (const key in WireframeMaterialShaders.uniforms) { u[key] = { value: WireframeMaterialShaders.uniforms[key] }; } return u; } function getBarycentricCoordinates(geometry3, removeEdge) { const position2 = geometry3.getAttribute("position"); const count = position2.count; const barycentric = []; for (let i4 = 0; i4 < count; i4++) { const even = i4 % 2 === 0; const Q = removeEdge ? 1 : 0; if (even) { barycentric.push(0, 0, 1, 0, 1, 0, 1, 0, Q); } else { barycentric.push(0, 1, 0, 0, 0, 1, 1, 0, Q); } } return new BufferAttribute(Float32Array.from(barycentric), 3); } function getInputGeometry(inputGeometry) { const geo = isRefObject2(inputGeometry) ? inputGeometry.current : inputGeometry; if (!isGeometry2(geo)) { if (isWireframeGeometry(geo)) { throw new Error("Wireframe: WireframeGeometry is not supported."); } const parent = geo.parent; if (isWithGeometry(parent)) { if (isWireframeGeometry(parent.geometry)) { throw new Error("Wireframe: WireframeGeometry is not supported."); } return parent.geometry; } } else { return geo; } } function setBarycentricCoordinates(geometry3, simplify) { if (geometry3.index) { console.warn("Wireframe: Requires non-indexed geometry, converting to non-indexed geometry."); const nonIndexedGeo = geometry3.toNonIndexed(); geometry3.copy(nonIndexedGeo); geometry3.setIndex(null); } const newBarycentric = getBarycentricCoordinates(geometry3, simplify); geometry3.setAttribute("barycentric", newBarycentric); } function WireframeWithCustomGeo({ geometry: customGeometry, simplify = false, ...props }) { extend({ MeshWireframeMaterial: WireframeMaterial }); const [geometry3, setGeometry] = React115.useState(null); React115.useLayoutEffect(() => { const geom = getInputGeometry(customGeometry); if (!geom) { throw new Error("Wireframe: geometry prop must be a BufferGeometry or a ref to a BufferGeometry."); } setBarycentricCoordinates(geom, simplify); if (isRef2(customGeometry)) { setGeometry(geom); } }, [simplify, customGeometry]); const drawnGeo = isRef2(customGeometry) ? geometry3 : customGeometry; return React115.createElement(React115.Fragment, null, drawnGeo && React115.createElement("mesh", { geometry: drawnGeo }, React115.createElement("meshWireframeMaterial", _extends({ attach: "material", transparent: true, side: DoubleSide, polygonOffset: true, polygonOffsetFactor: -4 }, props, { extensions: { derivatives: true, fragDepth: false, drawBuffers: false, shaderTextureLOD: false } })))); } function WireframeWithoutCustomGeo({ simplify = false, ...props }) { const objectRef = React115.useRef(null); const uniforms = React115.useMemo(() => getUniforms2(), [WireframeMaterialShaders.uniforms]); useWireframeUniforms(uniforms, props); React115.useLayoutEffect(() => { const geom = getInputGeometry(objectRef); if (!geom) { throw new Error("Wireframe: Must be a child of a Mesh, Line or Points object or specify a geometry prop."); } const og = geom.clone(); setBarycentricCoordinates(geom, simplify); return () => { geom.copy(og); og.dispose(); }; }, [simplify]); React115.useLayoutEffect(() => { const parentMesh = objectRef.current.parent; const og = parentMesh.material.clone(); setWireframeOverride(parentMesh.material, uniforms); return () => { parentMesh.material.dispose(); parentMesh.material = og; }; }, []); return React115.createElement("object3D", { ref: objectRef }); } function Wireframe2({ geometry: customGeometry, ...props }) { if (customGeometry) { return React115.createElement(WireframeWithCustomGeo, _extends({ geometry: customGeometry }, props)); } return React115.createElement(WireframeWithoutCustomGeo, props); } // node_modules/@react-three/drei/core/ShadowAlpha.js var React116 = __toESM(require_react()); function ShadowAlpha({ opacity, alphaMap }) { const depthMaterialRef = React116.useRef(null); const distanceMaterialRef = React116.useRef(null); const uShadowOpacity = React116.useRef({ value: 1 }); const uAlphaMap = React116.useRef({ value: null }); const uHasAlphaMap = React116.useRef({ value: false }); React116.useLayoutEffect(() => { depthMaterialRef.current.onBeforeCompile = distanceMaterialRef.current.onBeforeCompile = (shader) => { const mainLineStart = shader.fragmentShader.indexOf("void main"); let mainLine = ""; let ch3; let i4 = mainLineStart; while (ch3 !== "\n" && i4 < mainLineStart + 100) { ch3 = shader.fragmentShader.charAt(i4); mainLine += ch3; i4++; } mainLine = mainLine.trim(); shader.vertexShader = shader.vertexShader.replace("void main() {", ` varying vec2 custom_vUv; void main() { custom_vUv = uv; `); shader.fragmentShader = shader.fragmentShader.replace(mainLine, ` uniform float uShadowOpacity; uniform sampler2D uAlphaMap; uniform bool uHasAlphaMap; varying vec2 custom_vUv; float bayerDither2x2( vec2 v ) { return mod( 3.0 * v.y + 2.0 * v.x, 4.0 ); } float bayerDither4x4( vec2 v ) { vec2 P1 = mod( v, 2.0 ); vec2 P2 = mod( floor( 0.5 * v ), 2.0 ); return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 ); } void main() { float alpha = uHasAlphaMap ? uShadowOpacity * texture2D(uAlphaMap, custom_vUv).x : uShadowOpacity; if( ( bayerDither4x4( floor( mod( gl_FragCoord.xy, 4.0 ) ) ) ) / 16.0 >= alpha ) discard; `); shader.uniforms["uShadowOpacity"] = uShadowOpacity.current; shader.uniforms["uAlphaMap"] = uAlphaMap.current; shader.uniforms["uHasAlphaMap"] = uHasAlphaMap.current; }; }, []); useFrame(() => { var _r3f; const parent = (_r3f = depthMaterialRef.current.__r3f) == null || (_r3f = _r3f.parent) == null ? void 0 : _r3f.object; if (parent) { const parentMainMaterial = parent.material; if (parentMainMaterial) { uShadowOpacity.current.value = opacity !== null && opacity !== void 0 ? opacity : parentMainMaterial.opacity; if (alphaMap === false) { uAlphaMap.current.value = null; uHasAlphaMap.current.value = false; } else { uAlphaMap.current.value = alphaMap || parentMainMaterial.alphaMap; uHasAlphaMap.current.value = !!uAlphaMap.current.value; } } } }); return React116.createElement(React116.Fragment, null, React116.createElement("meshDepthMaterial", { ref: depthMaterialRef, attach: "customDepthMaterial", depthPacking: RGBADepthPacking }), React116.createElement("meshDistanceMaterial", { ref: distanceMaterialRef, attach: "customDistanceMaterial" })); } // node_modules/@react-three/drei/core/Points.js var React117 = __toESM(require_react()); var _inverseMatrix = new Matrix4(); var _ray4 = new Ray(); var _sphere4 = new Sphere(); var _position4 = new Vector3(); var PositionPoint = class extends Group { constructor() { super(); this.size = 0; this.color = new Color("white"); this.instance = { current: void 0 }; this.instanceKey = { current: void 0 }; } // This will allow the virtual instance have bounds get geometry() { var _this$instance$curren; return (_this$instance$curren = this.instance.current) == null ? void 0 : _this$instance$curren.geometry; } raycast(raycaster, intersects) { var _raycaster$params$Poi, _raycaster$params$Poi2; const parent = this.instance.current; if (!parent || !parent.geometry) return; const instanceId = parent.userData.instances.indexOf(this.instanceKey); if (instanceId === -1 || instanceId > parent.geometry.drawRange.count) return; const threshold = (_raycaster$params$Poi = (_raycaster$params$Poi2 = raycaster.params.Points) == null ? void 0 : _raycaster$params$Poi2.threshold) !== null && _raycaster$params$Poi !== void 0 ? _raycaster$params$Poi : 1; _sphere4.set(this.getWorldPosition(_position4), threshold); if (raycaster.ray.intersectsSphere(_sphere4) === false) return; _inverseMatrix.copy(parent.matrixWorld).invert(); _ray4.copy(raycaster.ray).applyMatrix4(_inverseMatrix); const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); const localThresholdSq = localThreshold * localThreshold; const rayPointDistanceSq = _ray4.distanceSqToPoint(this.position); if (rayPointDistanceSq < localThresholdSq) { const intersectPoint = new Vector3(); _ray4.closestPointToPoint(this.position, intersectPoint); intersectPoint.applyMatrix4(this.matrixWorld); const distance3 = raycaster.ray.origin.distanceTo(intersectPoint); if (distance3 < raycaster.near || distance3 > raycaster.far) return; intersects.push({ distance: distance3, distanceToRay: Math.sqrt(rayPointDistanceSq), point: intersectPoint, index: instanceId, face: null, object: this }); } } }; var i3; var positionRef; var context8 = React117.createContext(null); var parentMatrix3 = new Matrix4(); var position = new Vector3(); var PointsInstances = React117.forwardRef(({ children, range, limit = 1e3, ...props }, ref) => { const parentRef = React117.useRef(null); React117.useImperativeHandle(ref, () => parentRef.current, []); const [refs, setRefs] = React117.useState([]); const [[positions, colors2, sizes]] = React117.useState(() => [new Float32Array(limit * 3), Float32Array.from({ length: limit * 3 }, () => 1), Float32Array.from({ length: limit }, () => 1)]); React117.useEffect(() => { parentRef.current.geometry.attributes.position.needsUpdate = true; }); useFrame(() => { parentRef.current.updateMatrix(); parentRef.current.updateMatrixWorld(); parentMatrix3.copy(parentRef.current.matrixWorld).invert(); parentRef.current.geometry.drawRange.count = Math.min(limit, range !== void 0 ? range : limit, refs.length); for (i3 = 0; i3 < refs.length; i3++) { positionRef = refs[i3].current; positionRef.getWorldPosition(position).applyMatrix4(parentMatrix3); position.toArray(positions, i3 * 3); parentRef.current.geometry.attributes.position.needsUpdate = true; positionRef.matrixWorldNeedsUpdate = true; positionRef.color.toArray(colors2, i3 * 3); parentRef.current.geometry.attributes.color.needsUpdate = true; sizes.set([positionRef.size], i3); parentRef.current.geometry.attributes.size.needsUpdate = true; } }); const api = React117.useMemo(() => ({ getParent: () => parentRef, subscribe: (ref2) => { setRefs((refs2) => [...refs2, ref2]); return () => setRefs((refs2) => refs2.filter((item) => item.current !== ref2.current)); } }), []); return React117.createElement("points", _extends({ userData: { instances: refs }, matrixAutoUpdate: false, ref: parentRef, raycast: () => null }, props), React117.createElement("bufferGeometry", null, React117.createElement("bufferAttribute", { attach: "attributes-position", args: [positions, 3], usage: DynamicDrawUsage }), React117.createElement("bufferAttribute", { attach: "attributes-color", args: [colors2, 3], usage: DynamicDrawUsage }), React117.createElement("bufferAttribute", { attach: "attributes-size", args: [sizes, 1], usage: DynamicDrawUsage })), React117.createElement(context8.Provider, { value: api }, children)); }); var Point = React117.forwardRef(({ children, ...props }, ref) => { React117.useMemo(() => extend({ PositionPoint }), []); const group = React117.useRef(null); React117.useImperativeHandle(ref, () => group.current, []); const { subscribe, getParent } = React117.useContext(context8); React117.useLayoutEffect(() => subscribe(group), []); return React117.createElement("positionPoint", _extends({ instance: getParent(), instanceKey: group, ref: group }, props), children); }); var PointsBuffer = React117.forwardRef(({ children, positions, colors: colors2, sizes, stride = 3, ...props }, forwardedRef) => { const pointsRef = React117.useRef(null); React117.useImperativeHandle(forwardedRef, () => pointsRef.current, []); useFrame(() => { const attr = pointsRef.current.geometry.attributes; attr.position.needsUpdate = true; if (colors2) attr.color.needsUpdate = true; if (sizes) attr.size.needsUpdate = true; }); return React117.createElement("points", _extends({ ref: pointsRef }, props), React117.createElement("bufferGeometry", null, React117.createElement("bufferAttribute", { attach: "attributes-position", args: [positions, stride], usage: DynamicDrawUsage }), colors2 && React117.createElement("bufferAttribute", { attach: "attributes-color", args: [colors2, stride], count: colors2.length / stride, usage: DynamicDrawUsage }), sizes && React117.createElement("bufferAttribute", { attach: "attributes-size", args: [sizes, 1], count: sizes.length / stride, usage: DynamicDrawUsage })), children); }); var Points2 = React117.forwardRef((props, forwardedRef) => { if (props.positions instanceof Float32Array) { return React117.createElement(PointsBuffer, _extends({}, props, { ref: forwardedRef })); } else return React117.createElement(PointsInstances, _extends({}, props, { ref: forwardedRef })); }); // node_modules/@react-three/drei/core/Segments.js var React118 = __toESM(require_react()); var context9 = React118.createContext(null); var Segments = React118.forwardRef((props, forwardedRef) => { React118.useMemo(() => extend({ SegmentObject }), []); const { limit = 1e3, lineWidth = 1, children, ...rest } = props; const [segments, setSegments] = React118.useState([]); const [line] = React118.useState(() => new Line2()); const [material] = React118.useState(() => new LineMaterial()); const [geometry3] = React118.useState(() => new LineSegmentsGeometry()); const [resolution] = React118.useState(() => new Vector2(512, 512)); const [positions] = React118.useState(() => Array(limit * 6).fill(0)); const [colors2] = React118.useState(() => Array(limit * 6).fill(0)); const api = React118.useMemo(() => ({ subscribe: (ref) => { setSegments((segments2) => [...segments2, ref]); return () => setSegments((segments2) => segments2.filter((item) => item.current !== ref.current)); } }), []); useFrame(() => { for (let i4 = 0; i4 < limit; i4++) { var _segments$i; const segment = (_segments$i = segments[i4]) == null ? void 0 : _segments$i.current; if (segment) { positions[i4 * 6 + 0] = segment.start.x; positions[i4 * 6 + 1] = segment.start.y; positions[i4 * 6 + 2] = segment.start.z; positions[i4 * 6 + 3] = segment.end.x; positions[i4 * 6 + 4] = segment.end.y; positions[i4 * 6 + 5] = segment.end.z; colors2[i4 * 6 + 0] = segment.color.r; colors2[i4 * 6 + 1] = segment.color.g; colors2[i4 * 6 + 2] = segment.color.b; colors2[i4 * 6 + 3] = segment.color.r; colors2[i4 * 6 + 4] = segment.color.g; colors2[i4 * 6 + 5] = segment.color.b; } } geometry3.setColors(colors2); geometry3.setPositions(positions); line.computeLineDistances(); }); return React118.createElement("primitive", { object: line, ref: forwardedRef }, React118.createElement("primitive", { object: geometry3, attach: "geometry" }), React118.createElement("primitive", _extends({ object: material, attach: "material", vertexColors: true, resolution, linewidth: lineWidth }, rest)), React118.createElement(context9.Provider, { value: api }, children)); }); var SegmentObject = class { constructor() { this.color = new Color("white"); this.start = new Vector3(0, 0, 0); this.end = new Vector3(0, 0, 0); } }; var normPos = (pos) => pos instanceof Vector3 ? pos : new Vector3(...typeof pos === "number" ? [pos, pos, pos] : pos); var Segment = React118.forwardRef(({ color, start, end }, forwardedRef) => { const api = React118.useContext(context9); if (!api) throw "Segment must used inside Segments component."; const ref = React118.useRef(null); React118.useImperativeHandle(forwardedRef, () => ref.current, []); React118.useLayoutEffect(() => api.subscribe(ref), []); return React118.createElement("segmentObject", { ref, color, start: normPos(start), end: normPos(end) }); }); // node_modules/@react-three/drei/core/Detailed.js var React119 = __toESM(require_react()); var Detailed = React119.forwardRef(({ children, hysteresis = 0, distances, ...props }, ref) => { const lodRef = React119.useRef(null); React119.useImperativeHandle(ref, () => lodRef.current, []); React119.useLayoutEffect(() => { const { current: lod } = lodRef; lod.levels.length = 0; lod.children.forEach((object, index2) => lod.levels.push({ object, hysteresis, distance: distances[index2] })); }); useFrame((state) => { var _lodRef$current; return (_lodRef$current = lodRef.current) == null ? void 0 : _lodRef$current.update(state.camera); }); return React119.createElement("lOD", _extends({ ref: lodRef }, props), children); }); // node_modules/@react-three/drei/core/Preload.js var React120 = __toESM(require_react()); function Preload({ all, scene, camera }) { const gl = useThree(({ gl: gl2 }) => gl2); const dCamera = useThree(({ camera: camera2 }) => camera2); const dScene = useThree(({ scene: scene2 }) => scene2); React120.useLayoutEffect(() => { const invisible = []; if (all) { (scene || dScene).traverse((object) => { if (object.visible === false) { invisible.push(object); object.visible = true; } }); } gl.compile(scene || dScene, camera || dCamera); const cubeRenderTarget = new WebGLCubeRenderTarget(128); const cubeCamera = new CubeCamera(0.01, 1e5, cubeRenderTarget); cubeCamera.update(gl, scene || dScene); cubeRenderTarget.dispose(); invisible.forEach((object) => object.visible = false); }, []); return null; } // node_modules/@react-three/drei/core/BakeShadows.js var import_react19 = __toESM(require_react()); function BakeShadows() { const gl = useThree((state) => state.gl); (0, import_react19.useEffect)(() => { gl.shadowMap.autoUpdate = false; gl.shadowMap.needsUpdate = true; return () => { gl.shadowMap.autoUpdate = gl.shadowMap.needsUpdate = true; }; }, [gl.shadowMap]); return null; } // node_modules/@react-three/drei/core/meshBounds.js var _inverseMatrix2 = new Matrix4(); var _ray5 = new Ray(); var _sphere5 = new Sphere(); var _vA3 = new Vector3(); function meshBounds(raycaster, intersects) { const geometry3 = this.geometry; const material = this.material; const matrixWorld = this.matrixWorld; if (material === void 0) return; if (geometry3.boundingSphere === null) geometry3.computeBoundingSphere(); _sphere5.copy(geometry3.boundingSphere); _sphere5.applyMatrix4(matrixWorld); if (raycaster.ray.intersectsSphere(_sphere5) === false) return; _inverseMatrix2.copy(matrixWorld).invert(); _ray5.copy(raycaster.ray).applyMatrix4(_inverseMatrix2); if (geometry3.boundingBox !== null && _ray5.intersectBox(geometry3.boundingBox, _vA3) === null) return; intersects.push({ distance: _vA3.distanceTo(raycaster.ray.origin), point: _vA3.clone(), object: this }); } // node_modules/@react-three/drei/core/AdaptiveDpr.js var React121 = __toESM(require_react()); function AdaptiveDpr({ pixelated }) { const gl = useThree((state) => state.gl); const active = useThree((state) => state.internal.active); const current = useThree((state) => state.performance.current); const initialDpr = useThree((state) => state.viewport.initialDpr); const setDpr = useThree((state) => state.setDpr); React121.useEffect(() => { const domElement = gl.domElement; return () => { if (active) setDpr(initialDpr); if (pixelated && domElement) domElement.style.imageRendering = "auto"; }; }, []); React121.useEffect(() => { setDpr(current * initialDpr); if (pixelated && gl.domElement) gl.domElement.style.imageRendering = current === 1 ? "auto" : "pixelated"; }, [current]); return null; } // node_modules/@react-three/drei/core/AdaptiveEvents.js var React122 = __toESM(require_react()); function AdaptiveEvents() { const get = useThree((state) => state.get); const setEvents = useThree((state) => state.setEvents); const current = useThree((state) => state.performance.current); React122.useEffect(() => { const enabled = get().events.enabled; return () => setEvents({ enabled }); }, []); React122.useEffect(() => setEvents({ enabled: current === 1 }), [current]); return null; } // node_modules/@react-three/drei/core/PerformanceMonitor.js var React123 = __toESM(require_react()); var import_react20 = __toESM(require_react()); var context10 = (0, import_react20.createContext)(null); function PerformanceMonitor({ iterations = 10, ms = 250, threshold = 0.75, step = 0.1, factor: _factor = 0.5, flipflops = Infinity, bounds = (refreshrate) => refreshrate > 100 ? [60, 100] : [40, 60], onIncline, onDecline, onChange, onFallback, children }) { const decimalPlacesRatio = Math.pow(10, 0); const [api, _] = (0, import_react20.useState)(() => ({ fps: 0, index: 0, factor: _factor, flipped: 0, refreshrate: 0, fallback: false, frames: [], averages: [], subscriptions: /* @__PURE__ */ new Map(), subscribe: (ref) => { const key = /* @__PURE__ */ Symbol(); api.subscriptions.set(key, ref.current); return () => void api.subscriptions.delete(key); } })); let lastFactor = 0; useFrame(() => { const { frames, averages } = api; if (api.fallback) return; if (averages.length < iterations) { frames.push(performance.now()); const msPassed = frames[frames.length - 1] - frames[0]; if (msPassed >= ms) { api.fps = Math.round(frames.length / msPassed * 1e3 * decimalPlacesRatio) / decimalPlacesRatio; api.refreshrate = Math.max(api.refreshrate, api.fps); averages[api.index++ % iterations] = api.fps; if (averages.length === iterations) { const [lower, upper] = bounds(api.refreshrate); const upperBounds = averages.filter((value) => value >= upper); const lowerBounds = averages.filter((value) => value < lower); if (upperBounds.length > iterations * threshold) { api.factor = Math.min(1, api.factor + step); api.flipped++; if (onIncline) onIncline(api); api.subscriptions.forEach((value) => value.onIncline && value.onIncline(api)); } if (lowerBounds.length > iterations * threshold) { api.factor = Math.max(0, api.factor - step); api.flipped++; if (onDecline) onDecline(api); api.subscriptions.forEach((value) => value.onDecline && value.onDecline(api)); } if (lastFactor !== api.factor) { lastFactor = api.factor; if (onChange) onChange(api); api.subscriptions.forEach((value) => value.onChange && value.onChange(api)); } if (api.flipped > flipflops && !api.fallback) { api.fallback = true; if (onFallback) onFallback(api); api.subscriptions.forEach((value) => value.onFallback && value.onFallback(api)); } api.averages = []; } api.frames = []; } } }); return React123.createElement(context10.Provider, { value: api }, children); } function usePerformanceMonitor({ onIncline, onDecline, onChange, onFallback }) { const api = (0, import_react20.useContext)(context10); const ref = (0, import_react20.useRef)({ onIncline, onDecline, onChange, onFallback }); (0, import_react20.useLayoutEffect)(() => { ref.current.onIncline = onIncline; ref.current.onDecline = onDecline; ref.current.onChange = onChange; ref.current.onFallback = onFallback; }, [onIncline, onDecline, onChange, onFallback]); (0, import_react20.useLayoutEffect)(() => api.subscribe(ref), [api]); } // node_modules/@react-three/drei/core/RenderTexture.js var React124 = __toESM(require_react()); var RenderTexture = React124.forwardRef(({ children, compute, width, height, samples = 8, renderPriority = 0, eventPriority = 0, frames = Infinity, stencilBuffer = false, depthBuffer = true, generateMipmaps = false, ...props }, forwardRef82) => { const { size: size2, viewport } = useThree(); const fbo = useFBO((width || size2.width) * viewport.dpr, (height || size2.height) * viewport.dpr, { samples, stencilBuffer, depthBuffer, generateMipmaps }); const [vScene] = React124.useState(() => new Scene()); const uvCompute = React124.useCallback((event, state, previous) => { var _fbo$texture, _previous$previousRoo; let parent = (_fbo$texture = fbo.texture) == null || (_fbo$texture = _fbo$texture.__r3f.parent) == null ? void 0 : _fbo$texture.object; while (parent && !(parent instanceof Object3D)) { var _parent$__r3f$parent; parent = (_parent$__r3f$parent = parent.__r3f.parent) == null ? void 0 : _parent$__r3f$parent.object; } if (!parent) return false; if (!previous.raycaster.camera) previous.events.compute(event, previous, (_previous$previousRoo = previous.previousRoot) == null ? void 0 : _previous$previousRoo.getState()); const [intersection3] = previous.raycaster.intersectObject(parent); if (!intersection3) return false; const uv = intersection3.uv; if (!uv) return false; state.raycaster.setFromCamera(state.pointer.set(uv.x * 2 - 1, uv.y * 2 - 1), state.camera); }, []); React124.useImperativeHandle(forwardRef82, () => fbo.texture, [fbo]); return React124.createElement(React124.Fragment, null, createPortal(React124.createElement(Container, { renderPriority, frames, fbo }, children, React124.createElement("group", { onPointerOver: () => null })), vScene, { events: { compute: compute || uvCompute, priority: eventPriority } }), React124.createElement("primitive", _extends({ object: fbo.texture }, props))); }); function Container({ frames, renderPriority, children, fbo }) { let count = 0; let oldAutoClear; let oldXrEnabled; let oldRenderTarget; let oldIsPresenting; useFrame((state) => { if (frames === Infinity || count < frames) { oldAutoClear = state.gl.autoClear; oldXrEnabled = state.gl.xr.enabled; oldRenderTarget = state.gl.getRenderTarget(); oldIsPresenting = state.gl.xr.isPresenting; state.gl.autoClear = true; state.gl.xr.enabled = false; state.gl.xr.isPresenting = false; state.gl.setRenderTarget(fbo); state.gl.render(state.scene, state.camera); state.gl.setRenderTarget(oldRenderTarget); state.gl.autoClear = oldAutoClear; state.gl.xr.enabled = oldXrEnabled; state.gl.xr.isPresenting = oldIsPresenting; count++; } }, renderPriority); return React124.createElement(React124.Fragment, null, children); } // node_modules/@react-three/drei/core/RenderCubeTexture.js var React125 = __toESM(require_react()); var RenderCubeTexture = React125.forwardRef(({ children, compute, renderPriority = -1, eventPriority = 0, frames = Infinity, stencilBuffer = false, depthBuffer = true, generateMipmaps = false, resolution = 896, near = 0.1, far = 1e3, flip = false, position: position2, rotation: rotation3, scale: scale5, quaternion, matrix: matrix6, matrixAutoUpdate, ...props }, forwardRef82) => { const { size: size2, viewport } = useThree(); const camera = React125.useRef(null); const fbo = React125.useMemo(() => { const fbo2 = new WebGLCubeRenderTarget(Math.max((resolution || size2.width) * viewport.dpr, (resolution || size2.height) * viewport.dpr), { stencilBuffer, depthBuffer, generateMipmaps }); fbo2.texture.isRenderTargetTexture = !flip; fbo2.texture.flipY = true; fbo2.texture.type = HalfFloatType; return fbo2; }, [resolution, flip]); React125.useEffect(() => { return () => fbo.dispose(); }, [fbo]); const [vScene] = React125.useState(() => new Scene()); React125.useImperativeHandle(forwardRef82, () => ({ scene: vScene, fbo, camera: camera.current }), [fbo]); return React125.createElement(React125.Fragment, null, createPortal(React125.createElement(Container2, { renderPriority, frames, camera }, children, React125.createElement("group", { onPointerOver: () => null })), vScene, { events: { compute, priority: eventPriority } }), React125.createElement("primitive", _extends({ object: fbo.texture }, props)), React125.createElement("cubeCamera", { ref: camera, args: [near, far, fbo], position: position2, rotation: rotation3, scale: scale5, quaternion, matrix: matrix6, matrixAutoUpdate })); }); function Container2({ frames, renderPriority, children, camera }) { let count = 0; useFrame((state) => { if (frames === Infinity || count < frames) { camera.current.update(state.gl, state.scene); count++; } }, renderPriority); return React125.createElement(React125.Fragment, null, children); } // node_modules/@react-three/drei/core/Mask.js var React126 = __toESM(require_react()); var Mask = React126.forwardRef(({ id = 1, colorWrite = false, depthWrite = false, ...props }, fref) => { const ref = React126.useRef(null); const spread = React126.useMemo(() => ({ colorWrite, depthWrite, stencilWrite: true, stencilRef: id, stencilFunc: AlwaysStencilFunc, stencilFail: ReplaceStencilOp, stencilZFail: ReplaceStencilOp, stencilZPass: ReplaceStencilOp }), [id, colorWrite, depthWrite]); React126.useLayoutEffect(() => { Object.assign(ref.current.material, spread); }); React126.useImperativeHandle(fref, () => ref.current, []); return React126.createElement("mesh", _extends({ ref, renderOrder: -id }, props)); }); function useMask(id, inverse2 = false) { return { stencilWrite: true, stencilRef: id, stencilFunc: inverse2 ? NotEqualStencilFunc : EqualStencilFunc, stencilFail: KeepStencilOp, stencilZFail: KeepStencilOp, stencilZPass: KeepStencilOp }; } // node_modules/@react-three/drei/core/Fisheye.js var React127 = __toESM(require_react()); function Fisheye({ renderPriority = 1, zoom = 0, segments = 64, children, resolution = 896, ...props }) { const sphere = React127.useRef(null); const cubeApi = React127.useRef(null); const { width, height } = useThree((state) => state.size); const [orthoC] = React127.useState(() => new OrthographicCamera()); React127.useLayoutEffect(() => { orthoC.position.set(0, 0, 100); orthoC.zoom = 100; orthoC.left = width / -2; orthoC.right = width / 2; orthoC.top = height / 2; orthoC.bottom = height / -2; orthoC.updateProjectionMatrix(); }, [width, height]); const radius = Math.sqrt(width * width + height * height) / 100 * (0.5 + zoom / 2); const normal2 = new Vector3(); const sph = new Sphere(new Vector3(), radius); const normalMatrix = new Matrix3(); const compute = React127.useCallback((event, state, prev) => { state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1); state.raycaster.setFromCamera(state.pointer, orthoC); if (!state.raycaster.ray.intersectSphere(sph, normal2)) return; else normal2.normalize(); normalMatrix.getNormalMatrix(cubeApi.current.camera.matrixWorld); cubeApi.current.camera.getWorldPosition(state.raycaster.ray.origin); state.raycaster.ray.direction.set(0, 0, 1).reflect(normal2); state.raycaster.ray.direction.x *= -1; state.raycaster.ray.direction.applyNormalMatrix(normalMatrix).multiplyScalar(-1); return void 0; }, []); useFrame((state) => { if (renderPriority) state.gl.render(sphere.current, orthoC); }, renderPriority); return React127.createElement(React127.Fragment, null, React127.createElement("mesh", _extends({ ref: sphere }, props, { scale: radius }), React127.createElement("sphereGeometry", { args: [1, segments, segments] }), React127.createElement("meshBasicMaterial", null, React127.createElement(RenderCubeTexture, { compute, attach: "envMap", flip: true, resolution, ref: cubeApi }, children, React127.createElement(UpdateCubeCamera, { api: cubeApi }))))); } function UpdateCubeCamera({ api }) { const t3 = new Vector3(); const r2 = new Quaternion(); const s2 = new Vector3(); const e2 = new Euler(0, Math.PI, 0); useFrame((state) => { state.camera.matrixWorld.decompose(t3, r2, s2); api.current.camera.position.copy(t3); api.current.camera.quaternion.setFromEuler(e2).premultiply(r2); }); return null; } // node_modules/@react-three/drei/core/MeshPortalMaterial.js var React128 = __toESM(require_react()); var PortalMaterialImpl = shaderMaterial({ blur: 0, map: null, sdf: null, blend: 0, size: 0, resolution: new Vector2() }, `varying vec2 vUv; void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); vUv = uv; }`, `uniform sampler2D sdf; uniform sampler2D map; uniform float blur; uniform float size; uniform float time; uniform vec2 resolution; varying vec2 vUv; #include void main() { vec2 uv = gl_FragCoord.xy / resolution.xy; vec4 t = texture2D(map, uv); float k = blur; float d = texture2D(sdf, vUv).r/size; float alpha = 1.0 - smoothstep(0.0, 1.0, clamp(d/k + 1.0, 0.0, 1.0)); gl_FragColor = vec4(t.rgb, blur == 0.0 ? t.a : t.a * alpha); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }`); var MeshPortalMaterial = React128.forwardRef(({ children, events = void 0, blur = 0, eventPriority = 0, renderPriority = 0, worldUnits = false, resolution = 512, ...props }, fref) => { extend({ PortalMaterialImpl }); const ref = React128.useRef(null); const { scene, gl, size: size2, viewport, setEvents } = useThree(); const maskRenderTarget = useFBO(resolution, resolution); const [priority, setPriority] = React128.useState(0); useFrame(() => { const p2 = ref.current.blend > 0 ? Math.max(1, renderPriority) : 0; if (priority !== p2) setPriority(p2); }); React128.useEffect(() => { if (events !== void 0) setEvents({ enabled: !events }); }, [events]); const [visible, setVisible] = React128.useState(true); const parent = useIntersect(setVisible); React128.useLayoutEffect(() => { var _ref$current; parent.current = (_ref$current = ref.current) == null || (_ref$current = _ref$current.__r3f.parent) == null ? void 0 : _ref$current.object; }, []); React128.useLayoutEffect(() => { if (!parent.current) return; if (blur && ref.current.sdf === null) { const tempMesh = new Mesh(parent.current.geometry, new MeshBasicMaterial()); const boundingBox5 = new Box3().setFromBufferAttribute(tempMesh.geometry.attributes.position); const orthoCam = new OrthographicCamera(boundingBox5.min.x * (1 + 2 / resolution), boundingBox5.max.x * (1 + 2 / resolution), boundingBox5.max.y * (1 + 2 / resolution), boundingBox5.min.y * (1 + 2 / resolution), 0.1, 1e3); orthoCam.position.set(0, 0, 1); orthoCam.lookAt(0, 0, 0); gl.setRenderTarget(maskRenderTarget); gl.render(tempMesh, orthoCam); const sg = makeSDFGenerator(resolution, resolution, gl); const sdf = sg(maskRenderTarget.texture); const readSdf = new Float32Array(resolution * resolution); gl.readRenderTargetPixels(sdf, 0, 0, resolution, resolution, readSdf); let min = Infinity; for (let i4 = 0; i4 < readSdf.length; i4++) { if (readSdf[i4] < min) min = readSdf[i4]; } min = -min; ref.current.size = min; ref.current.sdf = sdf.texture; gl.setRenderTarget(null); } }, [resolution, blur]); React128.useImperativeHandle(fref, () => ref.current); const compute = React128.useCallback((event, state, previous) => { var _ref$current2; if (!parent.current) return false; state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1); state.raycaster.setFromCamera(state.pointer, state.camera); if (((_ref$current2 = ref.current) == null ? void 0 : _ref$current2.blend) === 0) { const [intersection3] = state.raycaster.intersectObject(parent.current); if (!intersection3) { state.raycaster.camera = void 0; return false; } } }, []); return React128.createElement("portalMaterialImpl", _extends({ ref, blur, blend: 0, resolution: [size2.width * viewport.dpr, size2.height * viewport.dpr], attach: "material" }, props), React128.createElement(RenderTexture, { attach: "map", frames: visible ? Infinity : 0, eventPriority, renderPriority, compute }, children, React128.createElement(ManagePortalScene, { events, rootScene: scene, priority, material: ref, worldUnits }))); }); function ManagePortalScene({ events = void 0, rootScene, material, priority, worldUnits }) { const scene = useThree((state) => state.scene); const setEvents = useThree((state) => state.setEvents); const buffer1 = useFBO(); const buffer2 = useFBO(); React128.useLayoutEffect(() => { scene.matrixAutoUpdate = false; }, []); React128.useEffect(() => { if (events !== void 0) setEvents({ enabled: events }); }, [events]); const [quad, blend] = React128.useMemo(() => { const blend2 = { value: 0 }; const quad2 = new FullScreenQuad(new ShaderMaterial({ uniforms: { a: { value: buffer1.texture }, b: { value: buffer2.texture }, blend: blend2 }, vertexShader: ( /*glsl*/ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /*glsl*/ ` uniform sampler2D a; uniform sampler2D b; uniform float blend; varying vec2 vUv; #include void main() { vec4 ta = texture2D(a, vUv); vec4 tb = texture2D(b, vUv); gl_FragColor = mix(tb, ta, blend); #include #include <${version2 >= 154 ? "colorspace_fragment" : "encodings_fragment"}> }` ) })); return [quad2, blend2]; }, []); useFrame((state) => { var _material$current; let parent = material == null || (_material$current = material.current) == null || (_material$current = _material$current.__r3f.parent) == null ? void 0 : _material$current.object; if (parent) { if (!worldUnits) { var _material$current2; if (priority && ((_material$current2 = material.current) == null ? void 0 : _material$current2.blend) === 1) parent.updateWorldMatrix(true, false); scene.matrixWorld.copy(parent.matrixWorld); } else scene.matrixWorld.identity(); if (priority) { var _material$current3, _material$current4, _material$current5; if (((_material$current3 = material.current) == null ? void 0 : _material$current3.blend) > 0 && ((_material$current4 = material.current) == null ? void 0 : _material$current4.blend) < 1) { blend.value = material.current.blend; state.gl.setRenderTarget(buffer1); state.gl.render(scene, state.camera); state.gl.setRenderTarget(buffer2); state.gl.render(rootScene, state.camera); state.gl.setRenderTarget(null); quad.render(state.gl); } else if (((_material$current5 = material.current) == null ? void 0 : _material$current5.blend) === 1) { state.gl.render(scene, state.camera); } } } }, priority); return React128.createElement(React128.Fragment, null); } var makeSDFGenerator = (clientWidth, clientHeight, renderer) => { let finalTarget = new WebGLRenderTarget(clientWidth, clientHeight, { minFilter: LinearMipmapLinearFilter, magFilter: LinearFilter, type: FloatType, format: RedFormat, generateMipmaps: true }); let outsideRenderTarget = new WebGLRenderTarget(clientWidth, clientHeight, { minFilter: NearestFilter, magFilter: NearestFilter }); let insideRenderTarget = new WebGLRenderTarget(clientWidth, clientHeight, { minFilter: NearestFilter, magFilter: NearestFilter }); let outsideRenderTarget2 = new WebGLRenderTarget(clientWidth, clientHeight, { minFilter: NearestFilter, magFilter: NearestFilter }); let insideRenderTarget2 = new WebGLRenderTarget(clientWidth, clientHeight, { minFilter: NearestFilter, magFilter: NearestFilter }); let outsideRenderTargetFinal = new WebGLRenderTarget(clientWidth, clientHeight, { minFilter: NearestFilter, magFilter: NearestFilter, type: FloatType, format: RedFormat }); let insideRenderTargetFinal = new WebGLRenderTarget(clientWidth, clientHeight, { minFilter: NearestFilter, magFilter: NearestFilter, type: FloatType, format: RedFormat }); const uvRender = new FullScreenQuad(new ShaderMaterial({ uniforms: { tex: { value: null } }, vertexShader: ( /*glsl*/ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /*glsl*/ ` uniform sampler2D tex; varying vec2 vUv; #include void main() { gl_FragColor = pack2HalfToRGBA(vUv * (round(texture2D(tex, vUv).x))); }` ) })); const uvRenderInside = new FullScreenQuad(new ShaderMaterial({ uniforms: { tex: { value: null } }, vertexShader: ( /*glsl*/ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /*glsl*/ ` uniform sampler2D tex; varying vec2 vUv; #include void main() { gl_FragColor = pack2HalfToRGBA(vUv * (1.0 - round(texture2D(tex, vUv).x))); }` ) })); const jumpFloodRender = new FullScreenQuad(new ShaderMaterial({ uniforms: { tex: { value: null }, offset: { value: 0 }, level: { value: 0 }, maxSteps: { 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 tex; uniform float offset; uniform float level; uniform float maxSteps; #include void main() { float closestDist = 9999999.9; vec2 closestPos = vec2(0.0); for (float x = -1.0; x <= 1.0; x += 1.0) { for (float y = -1.0; y <= 1.0; y += 1.0) { vec2 voffset = vUv; voffset += vec2(x, y) * vec2(${1 / clientWidth}, ${1 / clientHeight}) * offset; vec2 pos = unpackRGBATo2Half(texture2D(tex, voffset)); float dist = distance(pos.xy, vUv); if(pos.x != 0.0 && pos.y != 0.0 && dist < closestDist) { closestDist = dist; closestPos = pos; } } } gl_FragColor = pack2HalfToRGBA(closestPos); }` ) })); const distanceFieldRender = new FullScreenQuad(new ShaderMaterial({ uniforms: { tex: { value: null }, size: { value: new Vector2(clientWidth, clientHeight) } }, vertexShader: ( /*glsl*/ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /*glsl*/ ` varying vec2 vUv; uniform sampler2D tex; uniform vec2 size; #include void main() { gl_FragColor = vec4(distance(size * unpackRGBATo2Half(texture2D(tex, vUv)), size * vUv), 0.0, 0.0, 0.0); }` ) })); const compositeRender = new FullScreenQuad(new ShaderMaterial({ uniforms: { inside: { value: insideRenderTargetFinal.texture }, outside: { value: outsideRenderTargetFinal.texture }, tex: { 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 inside; uniform sampler2D outside; uniform sampler2D tex; #include void main() { float i = texture2D(inside, vUv).x; float o =texture2D(outside, vUv).x; if (texture2D(tex, vUv).x == 0.0) { gl_FragColor = vec4(o, 0.0, 0.0, 0.0); } else { gl_FragColor = vec4(-i, 0.0, 0.0, 0.0); } }` ) })); return (image) => { let ft = finalTarget; image.minFilter = NearestFilter; image.magFilter = NearestFilter; uvRender.material.uniforms.tex.value = image; renderer.setRenderTarget(outsideRenderTarget); uvRender.render(renderer); const passes = Math.ceil(Math.log(Math.max(clientWidth, clientHeight)) / Math.log(2)); let lastTarget = outsideRenderTarget; let target2 = null; for (let i4 = 0; i4 < passes; i4++) { const offset = Math.pow(2, passes - i4 - 1); target2 = lastTarget === outsideRenderTarget ? outsideRenderTarget2 : outsideRenderTarget; jumpFloodRender.material.uniforms.level.value = i4; jumpFloodRender.material.uniforms.maxSteps.value = passes; jumpFloodRender.material.uniforms.offset.value = offset; jumpFloodRender.material.uniforms.tex.value = lastTarget.texture; renderer.setRenderTarget(target2); jumpFloodRender.render(renderer); lastTarget = target2; } renderer.setRenderTarget(outsideRenderTargetFinal); distanceFieldRender.material.uniforms.tex.value = target2.texture; distanceFieldRender.render(renderer); uvRenderInside.material.uniforms.tex.value = image; renderer.setRenderTarget(insideRenderTarget); uvRenderInside.render(renderer); lastTarget = insideRenderTarget; for (let i4 = 0; i4 < passes; i4++) { const offset = Math.pow(2, passes - i4 - 1); target2 = lastTarget === insideRenderTarget ? insideRenderTarget2 : insideRenderTarget; jumpFloodRender.material.uniforms.level.value = i4; jumpFloodRender.material.uniforms.maxSteps.value = passes; jumpFloodRender.material.uniforms.offset.value = offset; jumpFloodRender.material.uniforms.tex.value = lastTarget.texture; renderer.setRenderTarget(target2); jumpFloodRender.render(renderer); lastTarget = target2; } renderer.setRenderTarget(insideRenderTargetFinal); distanceFieldRender.material.uniforms.tex.value = target2.texture; distanceFieldRender.render(renderer); renderer.setRenderTarget(ft); compositeRender.material.uniforms.tex.value = image; compositeRender.render(renderer); renderer.setRenderTarget(null); return ft; }; }; // node_modules/@react-three/drei/web/View.js var React130 = __toESM(require_react()); // node_modules/tunnel-rat/dist/index.js var import_react22 = __toESM(require_react()); // node_modules/tunnel-rat/node_modules/zustand/esm/vanilla.mjs var createStoreImpl = (createState) => { let state; const listeners = /* @__PURE__ */ new Set(); const setState = (partial, replace) => { const nextState = typeof partial === "function" ? partial(state) : partial; if (!Object.is(nextState, state)) { const previousState = state; state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState); listeners.forEach((listener) => listener(state, previousState)); } }; const getState = () => state; const getInitialState = () => initialState; const subscribe = (listener) => { listeners.add(listener); return () => listeners.delete(listener); }; const destroy = () => { if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") { console.warn( "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected." ); } listeners.clear(); }; const api = { setState, getState, getInitialState, subscribe, destroy }; const initialState = state = createState(setState, getState, api); return api; }; var createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl; // node_modules/tunnel-rat/node_modules/zustand/esm/index.mjs var import_react21 = __toESM(require_react(), 1); var import_with_selector = __toESM(require_with_selector(), 1); var { useDebugValue } = import_react21.default; var { useSyncExternalStoreWithSelector } = import_with_selector.default; var didWarnAboutEqualityFn = false; var identity2 = (arg) => arg; function useStore(api, selector = identity2, equalityFn) { if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && equalityFn && !didWarnAboutEqualityFn) { console.warn( "[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937" ); didWarnAboutEqualityFn = true; } const slice2 = useSyncExternalStoreWithSelector( api.subscribe, api.getState, api.getServerState || api.getInitialState, selector, equalityFn ); useDebugValue(slice2); return slice2; } var createImpl = (createState) => { if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && typeof createState !== "function") { console.warn( "[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`." ); } const api = typeof createState === "function" ? createStore(createState) : createState; const useBoundStore = (selector, equalityFn) => useStore(api, selector, equalityFn); Object.assign(useBoundStore, api); return useBoundStore; }; var create3 = (createState) => createState ? createImpl(createState) : createImpl; // node_modules/tunnel-rat/dist/index.js var _window$document; var _window$navigator; var useIsomorphicLayoutEffect = typeof window !== "undefined" && ((_window$document = window.document) != null && _window$document.createElement || ((_window$navigator = window.navigator) == null ? void 0 : _window$navigator.product) === "ReactNative") ? import_react22.default.useLayoutEffect : import_react22.default.useEffect; function tunnel() { const useStore2 = create3((set) => ({ current: new Array(), version: 0, set })); return { In: ({ children }) => { const set = useStore2((state) => state.set); const version4 = useStore2((state) => state.version); useIsomorphicLayoutEffect(() => { set((state) => ({ version: state.version + 1 })); }, []); useIsomorphicLayoutEffect(() => { set(({ current }) => ({ current: [...current, children] })); return () => set(({ current }) => ({ current: current.filter((c2) => c2 !== children) })); }, [children, version4]); return null; }, Out: () => { const current = useStore2((state) => state.current); return import_react22.default.createElement(import_react22.default.Fragment, null, current); } }; } // node_modules/@react-three/drei/web/View.js var isOrthographicCamera2 = (def) => def && def.isOrthographicCamera; var col2 = new Color(); var tracked = tunnel(); function computeContainerPosition(canvasSize, trackRect) { const { right, top, left: trackLeft, bottom: trackBottom, width, height } = trackRect; const isOffscreen = trackRect.bottom < 0 || top > canvasSize.height || right < 0 || trackRect.left > canvasSize.width; const canvasBottom = canvasSize.top + canvasSize.height; const bottom = canvasBottom - trackBottom; const left = trackLeft - canvasSize.left; return { position: { width, height, left, top, bottom, right }, isOffscreen }; } function prepareSkissor(state, { left, bottom, width, height }) { let autoClear; const aspect = width / height; if (isOrthographicCamera2(state.camera)) { if (!state.camera.manual) { if (state.camera.left !== width / -2 || state.camera.right !== width / 2 || state.camera.top !== height / 2 || state.camera.bottom !== height / -2) { Object.assign(state.camera, { left: width / -2, right: width / 2, top: height / 2, bottom: height / -2 }); state.camera.updateProjectionMatrix(); } } else { state.camera.updateProjectionMatrix(); } } else if (state.camera.aspect !== aspect) { state.camera.aspect = aspect; state.camera.updateProjectionMatrix(); } autoClear = state.gl.autoClear; state.gl.autoClear = false; state.gl.setViewport(left, bottom, width, height); state.gl.setScissor(left, bottom, width, height); state.gl.setScissorTest(true); return autoClear; } function finishSkissor(state, autoClear) { state.gl.setScissorTest(false); state.gl.autoClear = autoClear; } function clear2(state) { state.gl.getClearColor(col2); state.gl.setClearColor(col2, state.gl.getClearAlpha()); state.gl.clear(true, true); } function Container3({ visible = true, canvasSize, scene, index: index2, children, frames, rect, track }) { const rootState = useThree(); const [isOffscreen, setOffscreen] = React130.useState(false); let frameCount = 0; useFrame((state) => { if (frames === Infinity || frameCount <= frames) { var _track$current; if (track) rect.current = (_track$current = track.current) == null ? void 0 : _track$current.getBoundingClientRect(); frameCount++; } if (rect.current) { const { position: position2, isOffscreen: _isOffscreen } = computeContainerPosition(canvasSize, rect.current); if (isOffscreen !== _isOffscreen) setOffscreen(_isOffscreen); if (visible && !isOffscreen && rect.current) { const autoClear = prepareSkissor(state, position2); state.gl.render(children ? state.scene : scene, state.camera); finishSkissor(state, autoClear); } } }, index2); React130.useLayoutEffect(() => { const curRect = rect.current; if (curRect && (!visible || !isOffscreen)) { const { position: position2 } = computeContainerPosition(canvasSize, curRect); const autoClear = prepareSkissor(rootState, position2); clear2(rootState); finishSkissor(rootState, autoClear); } }, [visible, isOffscreen]); React130.useEffect(() => { if (!track) return; const curRect = rect.current; const old = rootState.get().events.connected; rootState.setEvents({ connected: track.current }); return () => { if (curRect) { const { position: position2 } = computeContainerPosition(canvasSize, curRect); const autoClear = prepareSkissor(rootState, position2); clear2(rootState); finishSkissor(rootState, autoClear); } rootState.setEvents({ connected: old }); }; }, [track]); return React130.createElement(React130.Fragment, null, children, React130.createElement("group", { onPointerOver: () => null })); } var CanvasView = React130.forwardRef(({ track, visible = true, index: index2 = 1, id, style, className, frames = Infinity, children, ...props }, fref) => { var _rect$current, _rect$current2, _rect$current3, _rect$current4; const rect = React130.useRef(null); const { size: size2, scene } = useThree(); const [virtualScene] = React130.useState(() => new Scene()); const [ready, toggle] = React130.useReducer(() => true, false); const compute = React130.useCallback((event, state) => { if (rect.current && track && track.current && event.target === track.current) { const { width, height, left, top } = rect.current; const x = event.clientX - left; const y = event.clientY - top; state.pointer.set(x / width * 2 - 1, -(y / height) * 2 + 1); state.raycaster.setFromCamera(state.pointer, state.camera); } }, [rect, track]); React130.useEffect(() => { var _track$current2; if (track) rect.current = (_track$current2 = track.current) == null ? void 0 : _track$current2.getBoundingClientRect(); toggle(); }, [track]); return React130.createElement("group", _extends({ ref: fref }, props), ready && createPortal(React130.createElement(Container3, { visible, canvasSize: size2, frames, scene, track, rect, index: index2 }, children), virtualScene, { events: { compute, priority: index2 }, size: { width: (_rect$current = rect.current) == null ? void 0 : _rect$current.width, height: (_rect$current2 = rect.current) == null ? void 0 : _rect$current2.height, // @ts-ignore top: (_rect$current3 = rect.current) == null ? void 0 : _rect$current3.top, // @ts-ignore left: (_rect$current4 = rect.current) == null ? void 0 : _rect$current4.left } })); }); var HtmlView = React130.forwardRef(({ as: El = "div", id, visible, className, style, index: index2 = 1, track, frames = Infinity, children, ...props }, fref) => { const uuid = React130.useId(); const ref = React130.useRef(null); React130.useImperativeHandle(fref, () => ref.current); return React130.createElement(React130.Fragment, null, React130.createElement(El, _extends({ ref, id, className, style }, props)), React130.createElement(tracked.In, null, React130.createElement(CanvasView, { visible, key: uuid, track: ref, frames, index: index2 }, children))); }); var View = (() => { const _View = React130.forwardRef((props, fref) => { const store = React130.useContext(context); if (!store) return React130.createElement(HtmlView, _extends({ ref: fref }, props)); else return React130.createElement(CanvasView, _extends({ ref: fref }, props)); }); _View.Port = () => React130.createElement(tracked.Out, null); return _View; })(); // node_modules/@react-three/drei/web/pivotControls/index.js var React136 = __toESM(require_react()); // node_modules/@react-three/drei/web/pivotControls/AxisArrow.js var React132 = __toESM(require_react()); // node_modules/@react-three/drei/web/pivotControls/context.js var React131 = __toESM(require_react()); var context11 = React131.createContext(null); // node_modules/@react-three/drei/web/pivotControls/AxisArrow.js var vec1 = new Vector3(); var vec2 = new Vector3(); var calculateOffset = (clickPoint, normal2, rayStart, rayDir) => { const e1 = normal2.dot(normal2); const e2 = normal2.dot(clickPoint) - normal2.dot(rayStart); const e3 = normal2.dot(rayDir); if (e3 === 0) { return -e2 / e1; } vec1.copy(rayDir).multiplyScalar(e1 / e3).sub(normal2); vec2.copy(rayDir).multiplyScalar(e2 / e3).add(rayStart).sub(clickPoint); const offset = -vec1.dot(vec2) / vec1.dot(vec1); return offset; }; var upV = new Vector3(0, 1, 0); var offsetMatrix = new Matrix4(); var AxisArrow = ({ direction: direction2, axis }) => { const { translation: translation3, translationLimits, annotations, annotationsClass, depthTest, scale: scale5, lineWidth, fixed, axisColors, hoveredColor, opacity, renderOrder, onDragStart, onDrag, onDragEnd, userData } = React132.useContext(context11); const camControls = useThree((state) => state.controls); const divRef = React132.useRef(null); const objRef = React132.useRef(null); const clickInfo = React132.useRef(null); const offset0 = React132.useRef(0); const [isHovered, setIsHovered] = React132.useState(false); const onPointerDown = React132.useCallback((e2) => { if (annotations) { divRef.current.innerText = `${translation3.current[axis].toFixed(2)}`; divRef.current.style.display = "block"; } e2.stopPropagation(); const rotation3 = new Matrix4().extractRotation(objRef.current.matrixWorld); const clickPoint = e2.point.clone(); const origin2 = new Vector3().setFromMatrixPosition(objRef.current.matrixWorld); const dir = direction2.clone().applyMatrix4(rotation3).normalize(); clickInfo.current = { clickPoint, dir }; offset0.current = translation3.current[axis]; onDragStart({ component: "Arrow", axis, origin: origin2, directions: [dir] }); camControls && (camControls.enabled = false); e2.target.setPointerCapture(e2.pointerId); }, [annotations, direction2, camControls, onDragStart, translation3, axis]); const onPointerMove = React132.useCallback((e2) => { e2.stopPropagation(); if (!isHovered) setIsHovered(true); if (clickInfo.current) { const { clickPoint, dir } = clickInfo.current; const [min, max2] = (translationLimits == null ? void 0 : translationLimits[axis]) || [void 0, void 0]; let offset = calculateOffset(clickPoint, dir, e2.ray.origin, e2.ray.direction); if (min !== void 0) { offset = Math.max(offset, min - offset0.current); } if (max2 !== void 0) { offset = Math.min(offset, max2 - offset0.current); } translation3.current[axis] = offset0.current + offset; if (annotations) { divRef.current.innerText = `${translation3.current[axis].toFixed(2)}`; } offsetMatrix.makeTranslation(dir.x * offset, dir.y * offset, dir.z * offset); onDrag(offsetMatrix); } }, [annotations, onDrag, isHovered, translation3, translationLimits, axis]); const onPointerUp = React132.useCallback((e2) => { if (annotations) { divRef.current.style.display = "none"; } e2.stopPropagation(); clickInfo.current = null; onDragEnd(); camControls && (camControls.enabled = true); e2.target.releasePointerCapture(e2.pointerId); }, [annotations, camControls, onDragEnd]); const onPointerOut = React132.useCallback((e2) => { e2.stopPropagation(); setIsHovered(false); }, []); const { cylinderLength, coneWidth, coneLength, matrixL } = React132.useMemo(() => { const coneWidth2 = fixed ? lineWidth / scale5 * 1.6 : scale5 / 20; const coneLength2 = fixed ? 0.2 : scale5 / 5; const cylinderLength2 = fixed ? 1 - coneLength2 : scale5 - coneLength2; const quaternion = new Quaternion().setFromUnitVectors(upV, direction2.clone().normalize()); const matrixL2 = new Matrix4().makeRotationFromQuaternion(quaternion); return { cylinderLength: cylinderLength2, coneWidth: coneWidth2, coneLength: coneLength2, matrixL: matrixL2 }; }, [direction2, scale5, lineWidth, fixed]); const color_ = isHovered ? hoveredColor : axisColors[axis]; return React132.createElement("group", { ref: objRef }, React132.createElement("group", { matrix: matrixL, matrixAutoUpdate: false, onPointerDown, onPointerMove, onPointerUp, onPointerOut }, annotations && React132.createElement(Html, { position: [0, -coneLength, 0] }, React132.createElement("div", { style: { display: "none", background: "#151520", color: "white", padding: "6px 8px", borderRadius: 7, whiteSpace: "nowrap" }, className: annotationsClass, ref: divRef })), React132.createElement("mesh", { visible: false, position: [0, (cylinderLength + coneLength) / 2, 0], userData }, React132.createElement("cylinderGeometry", { args: [coneWidth * 1.4, coneWidth * 1.4, cylinderLength + coneLength, 8, 1] })), React132.createElement(Line4, { transparent: true, raycast: () => null, depthTest, points: [0, 0, 0, 0, cylinderLength, 0], lineWidth, side: DoubleSide, color: color_, opacity, polygonOffset: true, renderOrder, polygonOffsetFactor: -10, fog: false }), React132.createElement("mesh", { raycast: () => null, position: [0, cylinderLength + coneLength / 2, 0], renderOrder }, React132.createElement("coneGeometry", { args: [coneWidth, coneLength, 24, 1] }), React132.createElement("meshBasicMaterial", { transparent: true, depthTest, color: color_, opacity, polygonOffset: true, polygonOffsetFactor: -10, fog: false })))); }; // node_modules/@react-three/drei/web/pivotControls/AxisRotator.js var React133 = __toESM(require_react()); var clickDir = new Vector3(); var intersectionDir = new Vector3(); var toDegrees = (radians) => radians * 180 / Math.PI; var toRadians = (degrees) => degrees * Math.PI / 180; var calculateAngle = (clickPoint, intersectionPoint, origin2, e1, e2) => { clickDir.copy(clickPoint).sub(origin2); intersectionDir.copy(intersectionPoint).sub(origin2); const dote1e1 = e1.dot(e1); const dote2e2 = e2.dot(e2); const uClick = clickDir.dot(e1) / dote1e1; const vClick = clickDir.dot(e2) / dote2e2; const uIntersection = intersectionDir.dot(e1) / dote1e1; const vIntersection = intersectionDir.dot(e2) / dote2e2; const angleClick = Math.atan2(vClick, uClick); const angleIntersection = Math.atan2(vIntersection, uIntersection); return angleIntersection - angleClick; }; var fmod = (num, denom) => { let k = Math.floor(num / denom); k = k < 0 ? k + 1 : k; return num - k * denom; }; var minimizeAngle = (angle) => { let result = fmod(angle, 2 * Math.PI); if (Math.abs(result) < 1e-6) { return 0; } if (result < 0) { result += 2 * Math.PI; } return result; }; var rotMatrix = new Matrix4(); var posNew = new Vector3(); var ray2 = new Ray(); var intersection = new Vector3(); var AxisRotator = ({ dir1, dir2, axis }) => { const { rotationLimits, annotations, annotationsClass, depthTest, scale: scale5, lineWidth, fixed, axisColors, hoveredColor, renderOrder, opacity, onDragStart, onDrag, onDragEnd, userData } = React133.useContext(context11); const camControls = useThree((state) => state.controls); const divRef = React133.useRef(null); const objRef = React133.useRef(null); const angle0 = React133.useRef(0); const angle = React133.useRef(0); const clickInfo = React133.useRef(null); const [isHovered, setIsHovered] = React133.useState(false); const onPointerDown = React133.useCallback((e2) => { if (annotations) { divRef.current.innerText = `${toDegrees(angle.current).toFixed(0)}º`; divRef.current.style.display = "block"; } e2.stopPropagation(); const clickPoint = e2.point.clone(); const origin2 = new Vector3().setFromMatrixPosition(objRef.current.matrixWorld); const e1 = new Vector3().setFromMatrixColumn(objRef.current.matrixWorld, 0).normalize(); const e22 = new Vector3().setFromMatrixColumn(objRef.current.matrixWorld, 1).normalize(); const normal2 = new Vector3().setFromMatrixColumn(objRef.current.matrixWorld, 2).normalize(); const plane = new Plane().setFromNormalAndCoplanarPoint(normal2, origin2); clickInfo.current = { clickPoint, origin: origin2, e1, e2: e22, normal: normal2, plane }; onDragStart({ component: "Rotator", axis, origin: origin2, directions: [e1, e22, normal2] }); camControls && (camControls.enabled = false); e2.target.setPointerCapture(e2.pointerId); }, [annotations, camControls, onDragStart, axis]); const onPointerMove = React133.useCallback((e2) => { e2.stopPropagation(); if (!isHovered) setIsHovered(true); if (clickInfo.current) { const { clickPoint, origin: origin2, e1, e2: e22, normal: normal2, plane } = clickInfo.current; const [min, max2] = (rotationLimits == null ? void 0 : rotationLimits[axis]) || [void 0, void 0]; ray2.copy(e2.ray); ray2.intersectPlane(plane, intersection); ray2.direction.negate(); ray2.intersectPlane(plane, intersection); let deltaAngle2 = calculateAngle(clickPoint, intersection, origin2, e1, e22); let degrees = toDegrees(deltaAngle2); if (e2.shiftKey) { degrees = Math.round(degrees / 10) * 10; deltaAngle2 = toRadians(degrees); } if (min !== void 0 && max2 !== void 0 && max2 - min < 2 * Math.PI) { deltaAngle2 = minimizeAngle(deltaAngle2); deltaAngle2 = deltaAngle2 > Math.PI ? deltaAngle2 - 2 * Math.PI : deltaAngle2; deltaAngle2 = MathUtils.clamp(deltaAngle2, min - angle0.current, max2 - angle0.current); angle.current = angle0.current + deltaAngle2; } else { angle.current = minimizeAngle(angle0.current + deltaAngle2); angle.current = angle.current > Math.PI ? angle.current - 2 * Math.PI : angle.current; } if (annotations) { degrees = toDegrees(angle.current); divRef.current.innerText = `${degrees.toFixed(0)}º`; } rotMatrix.makeRotationAxis(normal2, deltaAngle2); posNew.copy(origin2).applyMatrix4(rotMatrix).sub(origin2).negate(); rotMatrix.setPosition(posNew); onDrag(rotMatrix); } }, [annotations, onDrag, isHovered, rotationLimits, axis]); const onPointerUp = React133.useCallback((e2) => { if (annotations) { divRef.current.style.display = "none"; } e2.stopPropagation(); angle0.current = angle.current; clickInfo.current = null; onDragEnd(); camControls && (camControls.enabled = true); e2.target.releasePointerCapture(e2.pointerId); }, [annotations, camControls, onDragEnd]); const onPointerOut = React133.useCallback((e2) => { e2.stopPropagation(); setIsHovered(false); }, []); const matrixL = React133.useMemo(() => { const dir1N = dir1.clone().normalize(); const dir2N = dir2.clone().normalize(); return new Matrix4().makeBasis(dir1N, dir2N, dir1N.clone().cross(dir2N)); }, [dir1, dir2]); const r2 = fixed ? 0.65 : scale5 * 0.65; const arc = React133.useMemo(() => { const segments = 32; const points = []; for (let j = 0; j <= segments; j++) { const angle2 = j * (Math.PI / 2) / segments; points.push(new Vector3(Math.cos(angle2) * r2, Math.sin(angle2) * r2, 0)); } return points; }, [r2]); return React133.createElement("group", { ref: objRef, onPointerDown, onPointerMove, onPointerUp, onPointerOut, matrix: matrixL, matrixAutoUpdate: false }, annotations && React133.createElement(Html, { position: [r2, r2, 0] }, React133.createElement("div", { style: { display: "none", background: "#151520", color: "white", padding: "6px 8px", borderRadius: 7, whiteSpace: "nowrap" }, className: annotationsClass, ref: divRef })), React133.createElement(Line4, { points: arc, lineWidth: lineWidth * 4, visible: false, userData }), React133.createElement(Line4, { transparent: true, raycast: () => null, depthTest, points: arc, lineWidth, side: DoubleSide, color: isHovered ? hoveredColor : axisColors[axis], opacity, polygonOffset: true, polygonOffsetFactor: -10, renderOrder, fog: false })); }; // node_modules/@react-three/drei/web/pivotControls/PlaneSlider.js var React134 = __toESM(require_react()); var decomposeIntoBasis = (e1, e2, offset) => { const i1 = Math.abs(e1.x) >= Math.abs(e1.y) && Math.abs(e1.x) >= Math.abs(e1.z) ? 0 : Math.abs(e1.y) >= Math.abs(e1.x) && Math.abs(e1.y) >= Math.abs(e1.z) ? 1 : 2; const e2DegrowthOrder = [0, 1, 2].sort((a6, b5) => Math.abs(e2.getComponent(b5)) - Math.abs(e2.getComponent(a6))); const i22 = i1 === e2DegrowthOrder[0] ? e2DegrowthOrder[1] : e2DegrowthOrder[0]; const a1 = e1.getComponent(i1); const a22 = e1.getComponent(i22); const b1 = e2.getComponent(i1); const b23 = e2.getComponent(i22); const c1 = offset.getComponent(i1); const c2 = offset.getComponent(i22); const y = (c2 - c1 * (a22 / a1)) / (b23 - b1 * (a22 / a1)); const x = (c1 - y * b1) / a1; return [x, y]; }; var ray3 = new Ray(); var intersection2 = new Vector3(); var offsetMatrix2 = new Matrix4(); var PlaneSlider = ({ dir1, dir2, axis }) => { const { translation: translation3, translationLimits, annotations, annotationsClass, depthTest, scale: scale5, lineWidth, fixed, axisColors, hoveredColor, opacity, renderOrder, onDragStart, onDrag, onDragEnd, userData } = React134.useContext(context11); const camControls = useThree((state) => state.controls); const divRef = React134.useRef(null); const objRef = React134.useRef(null); const clickInfo = React134.useRef(null); const offsetX0 = React134.useRef(0); const offsetY0 = React134.useRef(0); const [isHovered, setIsHovered] = React134.useState(false); const onPointerDown = React134.useCallback((e2) => { if (annotations) { divRef.current.innerText = `${translation3.current[(axis + 1) % 3].toFixed(2)}, ${translation3.current[(axis + 2) % 3].toFixed(2)}`; divRef.current.style.display = "block"; } e2.stopPropagation(); const clickPoint = e2.point.clone(); const origin2 = new Vector3().setFromMatrixPosition(objRef.current.matrixWorld); const e1 = new Vector3().setFromMatrixColumn(objRef.current.matrixWorld, 0).normalize(); const e22 = new Vector3().setFromMatrixColumn(objRef.current.matrixWorld, 1).normalize(); const normal2 = new Vector3().setFromMatrixColumn(objRef.current.matrixWorld, 2).normalize(); const plane = new Plane().setFromNormalAndCoplanarPoint(normal2, origin2); clickInfo.current = { clickPoint, e1, e2: e22, plane }; offsetX0.current = translation3.current[(axis + 1) % 3]; offsetY0.current = translation3.current[(axis + 2) % 3]; onDragStart({ component: "Slider", axis, origin: origin2, directions: [e1, e22, normal2] }); camControls && (camControls.enabled = false); e2.target.setPointerCapture(e2.pointerId); }, [annotations, camControls, onDragStart, axis]); const onPointerMove = React134.useCallback((e2) => { e2.stopPropagation(); if (!isHovered) setIsHovered(true); if (clickInfo.current) { const { clickPoint, e1, e2: e22, plane } = clickInfo.current; const [minX, maxX] = (translationLimits == null ? void 0 : translationLimits[(axis + 1) % 3]) || [void 0, void 0]; const [minY, maxY] = (translationLimits == null ? void 0 : translationLimits[(axis + 2) % 3]) || [void 0, void 0]; ray3.copy(e2.ray); ray3.intersectPlane(plane, intersection2); ray3.direction.negate(); ray3.intersectPlane(plane, intersection2); intersection2.sub(clickPoint); let [offsetX, offsetY] = decomposeIntoBasis(e1, e22, intersection2); if (minX !== void 0) { offsetX = Math.max(offsetX, minX - offsetX0.current); } if (maxX !== void 0) { offsetX = Math.min(offsetX, maxX - offsetX0.current); } if (minY !== void 0) { offsetY = Math.max(offsetY, minY - offsetY0.current); } if (maxY !== void 0) { offsetY = Math.min(offsetY, maxY - offsetY0.current); } translation3.current[(axis + 1) % 3] = offsetX0.current + offsetX; translation3.current[(axis + 2) % 3] = offsetY0.current + offsetY; if (annotations) { divRef.current.innerText = `${translation3.current[(axis + 1) % 3].toFixed(2)}, ${translation3.current[(axis + 2) % 3].toFixed(2)}`; } offsetMatrix2.makeTranslation(offsetX * e1.x + offsetY * e22.x, offsetX * e1.y + offsetY * e22.y, offsetX * e1.z + offsetY * e22.z); onDrag(offsetMatrix2); } }, [annotations, onDrag, isHovered, translation3, translationLimits, axis]); const onPointerUp = React134.useCallback((e2) => { if (annotations) { divRef.current.style.display = "none"; } e2.stopPropagation(); clickInfo.current = null; onDragEnd(); camControls && (camControls.enabled = true); e2.target.releasePointerCapture(e2.pointerId); }, [annotations, camControls, onDragEnd]); const onPointerOut = React134.useCallback((e2) => { e2.stopPropagation(); setIsHovered(false); }, []); const matrixL = React134.useMemo(() => { const dir1N = dir1.clone().normalize(); const dir2N = dir2.clone().normalize(); return new Matrix4().makeBasis(dir1N, dir2N, dir1N.clone().cross(dir2N)); }, [dir1, dir2]); const pos1 = fixed ? 1 / 7 : scale5 / 7; const length3 = fixed ? 0.225 : scale5 * 0.225; const color = isHovered ? hoveredColor : axisColors[axis]; const points = React134.useMemo(() => [new Vector3(0, 0, 0), new Vector3(0, length3, 0), new Vector3(length3, length3, 0), new Vector3(length3, 0, 0), new Vector3(0, 0, 0)], [length3]); return React134.createElement("group", { ref: objRef, matrix: matrixL, matrixAutoUpdate: false }, annotations && React134.createElement(Html, { position: [0, 0, 0] }, React134.createElement("div", { style: { display: "none", background: "#151520", color: "white", padding: "6px 8px", borderRadius: 7, whiteSpace: "nowrap" }, className: annotationsClass, ref: divRef })), React134.createElement("group", { position: [pos1 * 1.7, pos1 * 1.7, 0] }, React134.createElement("mesh", { visible: true, onPointerDown, onPointerMove, onPointerUp, onPointerOut, scale: length3, userData, renderOrder }, React134.createElement("planeGeometry", null), React134.createElement("meshBasicMaterial", { transparent: true, depthTest, color, polygonOffset: true, polygonOffsetFactor: -10, side: DoubleSide, fog: false })), React134.createElement(Line4, { position: [-length3 / 2, -length3 / 2, 0], transparent: true, depthTest, points, lineWidth, color, opacity, polygonOffset: true, polygonOffsetFactor: -10, userData, fog: false, renderOrder }))); }; // node_modules/@react-three/drei/web/pivotControls/ScalingSphere.js var React135 = __toESM(require_react()); var vec12 = new Vector3(); var vec22 = new Vector3(); var calculateOffset2 = (clickPoint, normal2, rayStart, rayDir) => { const e1 = normal2.dot(normal2); const e2 = normal2.dot(clickPoint) - normal2.dot(rayStart); const e3 = normal2.dot(rayDir); if (e3 === 0) { return -e2 / e1; } vec12.copy(rayDir).multiplyScalar(e1 / e3).sub(normal2); vec22.copy(rayDir).multiplyScalar(e2 / e3).add(rayStart).sub(clickPoint); const offset = -vec12.dot(vec22) / vec12.dot(vec12); return offset; }; var upV2 = new Vector3(0, 1, 0); var scaleV = new Vector3(); var scaleMatrix = new Matrix4(); var ScalingSphere = ({ direction: direction2, axis }) => { const { scaleLimits, annotations, annotationsClass, depthTest, scale: scale5, lineWidth, fixed, axisColors, hoveredColor, opacity, renderOrder, onDragStart, onDrag, onDragEnd, userData } = React135.useContext(context11); const size2 = useThree((state) => state.size); const camControls = useThree((state) => state.controls); const divRef = React135.useRef(null); const objRef = React135.useRef(null); const meshRef = React135.useRef(null); const scale0 = React135.useRef(1); const scaleCur = React135.useRef(1); const clickInfo = React135.useRef(null); const [isHovered, setIsHovered] = React135.useState(false); const position2 = fixed ? 1.2 : 1.2 * scale5; const onPointerDown = React135.useCallback((e2) => { if (annotations) { divRef.current.innerText = `${scaleCur.current.toFixed(2)}`; divRef.current.style.display = "block"; } e2.stopPropagation(); const rotation3 = new Matrix4().extractRotation(objRef.current.matrixWorld); const clickPoint = e2.point.clone(); const origin2 = new Vector3().setFromMatrixPosition(objRef.current.matrixWorld); const dir = direction2.clone().applyMatrix4(rotation3).normalize(); const mPLG = objRef.current.matrixWorld.clone(); const mPLGInv = mPLG.clone().invert(); const offsetMultiplier = fixed ? 1 / calculateScaleFactor(objRef.current.getWorldPosition(vec12), scale5, e2.camera, size2) : 1; clickInfo.current = { clickPoint, dir, mPLG, mPLGInv, offsetMultiplier }; onDragStart({ component: "Sphere", axis, origin: origin2, directions: [dir] }); camControls && (camControls.enabled = false); e2.target.setPointerCapture(e2.pointerId); }, [annotations, camControls, direction2, onDragStart, axis, fixed, scale5, size2]); const onPointerMove = React135.useCallback((e2) => { e2.stopPropagation(); if (!isHovered) setIsHovered(true); if (clickInfo.current) { const { clickPoint, dir, mPLG, mPLGInv, offsetMultiplier } = clickInfo.current; const [min, max2] = (scaleLimits == null ? void 0 : scaleLimits[axis]) || [1e-5, void 0]; const offsetW = calculateOffset2(clickPoint, dir, e2.ray.origin, e2.ray.direction); const offsetL = offsetW * offsetMultiplier; const offsetH = fixed ? offsetL : offsetL / scale5; let upscale = Math.pow(2, offsetH * 0.2); if (e2.shiftKey) { upscale = Math.round(upscale * 10) / 10; } upscale = Math.max(upscale, min / scale0.current); if (max2 !== void 0) { upscale = Math.min(upscale, max2 / scale0.current); } scaleCur.current = scale0.current * upscale; meshRef.current.position.set(0, position2 + offsetL, 0); if (annotations) { divRef.current.innerText = `${scaleCur.current.toFixed(2)}`; } scaleV.set(1, 1, 1); scaleV.setComponent(axis, upscale); scaleMatrix.makeScale(scaleV.x, scaleV.y, scaleV.z).premultiply(mPLG).multiply(mPLGInv); onDrag(scaleMatrix); } }, [annotations, position2, onDrag, isHovered, scaleLimits, axis]); const onPointerUp = React135.useCallback((e2) => { if (annotations) { divRef.current.style.display = "none"; } e2.stopPropagation(); scale0.current = scaleCur.current; clickInfo.current = null; meshRef.current.position.set(0, position2, 0); onDragEnd(); camControls && (camControls.enabled = true); e2.target.releasePointerCapture(e2.pointerId); }, [annotations, camControls, onDragEnd, position2]); const onPointerOut = React135.useCallback((e2) => { e2.stopPropagation(); setIsHovered(false); }, []); const { radius, matrixL } = React135.useMemo(() => { const radius2 = fixed ? lineWidth / scale5 * 1.8 : scale5 / 22.5; const quaternion = new Quaternion().setFromUnitVectors(upV2, direction2.clone().normalize()); const matrixL2 = new Matrix4().makeRotationFromQuaternion(quaternion); return { radius: radius2, matrixL: matrixL2 }; }, [direction2, scale5, lineWidth, fixed]); const color = isHovered ? hoveredColor : axisColors[axis]; return React135.createElement("group", { ref: objRef }, React135.createElement("group", { matrix: matrixL, matrixAutoUpdate: false, onPointerDown, onPointerMove, onPointerUp, onPointerOut }, annotations && React135.createElement(Html, { position: [0, position2 / 2, 0] }, React135.createElement("div", { style: { display: "none", background: "#151520", color: "white", padding: "6px 8px", borderRadius: 7, whiteSpace: "nowrap" }, className: annotationsClass, ref: divRef })), React135.createElement("mesh", { ref: meshRef, position: [0, position2, 0], renderOrder, userData }, React135.createElement("sphereGeometry", { args: [radius, 12, 12] }), React135.createElement("meshBasicMaterial", { transparent: true, depthTest, color, opacity, polygonOffset: true, polygonOffsetFactor: -10 })))); }; // node_modules/@react-three/drei/web/pivotControls/index.js var mL0 = new Matrix4(); var mW0 = new Matrix4(); var mP = new Matrix4(); var mPInv = new Matrix4(); var mW = new Matrix4(); var mL = new Matrix4(); var mL0Inv = new Matrix4(); var mdL = new Matrix4(); var mG = new Matrix4(); var bb = new Box3(); var bbObj = new Box3(); var vCenter = new Vector3(); var vSize = new Vector3(); var vAnchorOffset = new Vector3(); var vPosition = new Vector3(); var vScale = new Vector3(); var xDir = new Vector3(1, 0, 0); var yDir = new Vector3(0, 1, 0); var zDir = new Vector3(0, 0, 1); var PivotControls = React136.forwardRef(({ enabled = true, matrix: matrix6, onDragStart, onDrag, onDragEnd, autoTransform = true, anchor, disableAxes = false, disableSliders = false, disableRotations = false, disableScaling = false, activeAxes = [true, true, true], offset = [0, 0, 0], rotation: rotation3 = [0, 0, 0], scale: scale5 = 1, lineWidth = 4, fixed = false, translationLimits, rotationLimits, scaleLimits, depthTest = true, renderOrder = 500, axisColors = ["#ff2060", "#20df80", "#2080ff"], hoveredColor = "#ffff40", annotations = false, annotationsClass, opacity = 1, visible = true, userData, children, ...props }, fRef) => { const invalidate = useThree((state) => state.invalidate); const parentRef = React136.useRef(null); const ref = React136.useRef(null); const gizmoRef = React136.useRef(null); const childrenRef = React136.useRef(null); const translation3 = React136.useRef([0, 0, 0]); const cameraScale = React136.useRef(new Vector3(1, 1, 1)); const gizmoScale = React136.useRef(new Vector3(1, 1, 1)); React136.useLayoutEffect(() => { if (!anchor) return; childrenRef.current.updateWorldMatrix(true, true); mPInv.copy(childrenRef.current.matrixWorld).invert(); bb.makeEmpty(); childrenRef.current.traverse((obj) => { if (!obj.geometry) return; if (!obj.geometry.boundingBox) obj.geometry.computeBoundingBox(); mL.copy(obj.matrixWorld).premultiply(mPInv); bbObj.copy(obj.geometry.boundingBox); bbObj.applyMatrix4(mL); bb.union(bbObj); }); vCenter.copy(bb.max).add(bb.min).multiplyScalar(0.5); vSize.copy(bb.max).sub(bb.min).multiplyScalar(0.5); vAnchorOffset.copy(vSize).multiply(new Vector3(...anchor)).add(vCenter); vPosition.set(...offset).add(vAnchorOffset); gizmoRef.current.position.copy(vPosition); invalidate(); }); const config = React136.useMemo(() => ({ onDragStart: (props2) => { mL0.copy(ref.current.matrix); mW0.copy(ref.current.matrixWorld); onDragStart && onDragStart(props2); invalidate(); }, onDrag: (mdW) => { mP.copy(parentRef.current.matrixWorld); mPInv.copy(mP).invert(); mW.copy(mW0).premultiply(mdW); mL.copy(mW).premultiply(mPInv); mL0Inv.copy(mL0).invert(); mdL.copy(mL).multiply(mL0Inv); if (autoTransform) { ref.current.matrix.copy(mL); } onDrag && onDrag(mL, mdL, mW, mdW); invalidate(); }, onDragEnd: () => { if (onDragEnd) onDragEnd(); invalidate(); }, translation: translation3, translationLimits, rotationLimits, axisColors, hoveredColor, opacity, scale: scale5, lineWidth, fixed, depthTest, renderOrder, userData, annotations, annotationsClass }), [onDragStart, onDrag, onDragEnd, translation3, translationLimits, rotationLimits, scaleLimits, depthTest, scale5, lineWidth, fixed, ...axisColors, hoveredColor, opacity, userData, autoTransform, annotations, annotationsClass]); const vec = new Vector3(); useFrame((state) => { if (fixed) { const sf = calculateScaleFactor(gizmoRef.current.getWorldPosition(vec), scale5, state.camera, state.size); cameraScale.current.setScalar(sf); } if (matrix6 && matrix6 instanceof Matrix4) { ref.current.matrix = matrix6; } ref.current.updateWorldMatrix(true, true); mG.makeRotationFromEuler(gizmoRef.current.rotation).setPosition(gizmoRef.current.position).premultiply(ref.current.matrixWorld); gizmoScale.current.setFromMatrixScale(mG); vScale.copy(cameraScale.current).divide(gizmoScale.current); if (Math.abs(gizmoRef.current.scale.x - vScale.x) > 1e-4 || Math.abs(gizmoRef.current.scale.y - vScale.y) > 1e-4 || Math.abs(gizmoRef.current.scale.z - vScale.z) > 1e-4) { gizmoRef.current.scale.copy(vScale); state.invalidate(); } }); React136.useImperativeHandle(fRef, () => ref.current, []); return React136.createElement(context11.Provider, { value: config }, React136.createElement("group", { ref: parentRef }, React136.createElement("group", _extends({ ref, matrix: matrix6, matrixAutoUpdate: false }, props), React136.createElement("group", { visible, ref: gizmoRef, position: offset, rotation: rotation3 }, enabled && React136.createElement(React136.Fragment, null, !disableAxes && activeAxes[0] && React136.createElement(AxisArrow, { axis: 0, direction: xDir }), !disableAxes && activeAxes[1] && React136.createElement(AxisArrow, { axis: 1, direction: yDir }), !disableAxes && activeAxes[2] && React136.createElement(AxisArrow, { axis: 2, direction: zDir }), !disableSliders && activeAxes[0] && activeAxes[1] && React136.createElement(PlaneSlider, { axis: 2, dir1: xDir, dir2: yDir }), !disableSliders && activeAxes[0] && activeAxes[2] && React136.createElement(PlaneSlider, { axis: 1, dir1: zDir, dir2: xDir }), !disableSliders && activeAxes[2] && activeAxes[1] && React136.createElement(PlaneSlider, { axis: 0, dir1: yDir, dir2: zDir }), !disableRotations && activeAxes[0] && activeAxes[1] && React136.createElement(AxisRotator, { axis: 2, dir1: xDir, dir2: yDir }), !disableRotations && activeAxes[0] && activeAxes[2] && React136.createElement(AxisRotator, { axis: 1, dir1: zDir, dir2: xDir }), !disableRotations && activeAxes[2] && activeAxes[1] && React136.createElement(AxisRotator, { axis: 0, dir1: yDir, dir2: zDir }), !disableScaling && activeAxes[0] && React136.createElement(ScalingSphere, { axis: 0, direction: xDir }), !disableScaling && activeAxes[1] && React136.createElement(ScalingSphere, { axis: 1, direction: yDir }), !disableScaling && activeAxes[2] && React136.createElement(ScalingSphere, { axis: 2, direction: zDir }))), React136.createElement("group", { ref: childrenRef }, children)))); }); // node_modules/@react-three/drei/web/ScreenVideoTexture.js var React137 = __toESM(require_react()); var import_react23 = __toESM(require_react()); var ScreenVideoTexture = (0, import_react23.forwardRef)(({ options = { video: true }, ...props }, fref) => { const mediaStream = suspend(() => navigator.mediaDevices.getDisplayMedia(options), []); (0, import_react23.useEffect)(() => { return () => { mediaStream == null || mediaStream.getTracks().forEach((track) => track.stop()); clear([]); }; }, [mediaStream]); return React137.createElement(VideoTexture2, _extends({ ref: fref }, props, { src: mediaStream })); }); // node_modules/@react-three/drei/web/WebcamVideoTexture.js var React138 = __toESM(require_react()); var import_react24 = __toESM(require_react()); var WebcamVideoTexture = (0, import_react24.forwardRef)(({ constraints = { audio: false, video: { facingMode: "user" } }, ...props }, fref) => { const mediaStream = suspend(() => navigator.mediaDevices.getUserMedia(constraints), []); (0, import_react24.useEffect)(() => { return () => { mediaStream == null || mediaStream.getTracks().forEach((track) => track.stop()); clear([]); }; }, [mediaStream]); return React138.createElement(VideoTexture2, _extends({ ref: fref }, props, { src: mediaStream })); }); // node_modules/@react-three/drei/web/FaceControls.js var React141 = __toESM(require_react()); var import_react26 = __toESM(require_react()); // node_modules/@react-three/drei/web/Facemesh.js var React139 = __toESM(require_react()); var defaultLookAt = new Vector3(0, 0, -1); var normal = (function() { const a6 = new Vector3(); const b5 = new Vector3(); const c2 = new Vector3(); const ab2 = new Vector3(); const ac = new Vector3(); return function(v13, v22, v32, v5) { a6.copy(v13); b5.copy(v22); c2.copy(v32); ab2.copy(b5).sub(a6); ac.copy(c2).sub(a6); return v5.crossVectors(ac, ab2).normalize(); }; })(); function mean(v13, v22) { return v13.clone().add(v22).multiplyScalar(0.5); } var Facemesh = React139.forwardRef(({ points = FacemeshDatas.SAMPLE_FACELANDMARKER_RESULT.faceLandmarks[0], face, facialTransformationMatrix, faceBlendshapes, offset, offsetScalar = 80, width, height, depth = 1, verticalTri = [159, 386, 152], origin: origin2, eyes = true, eyesAsOrigin = false, debug = false, children, ...props }, fref) => { var _meshRef$current3; if (face) { points = face.keypoints; console.warn("Facemesh `face` prop is deprecated: use `points` instead"); } const offsetRef = React139.useRef(null); const scaleRef = React139.useRef(null); const originRef = React139.useRef(null); const outerRef = React139.useRef(null); const meshRef = React139.useRef(null); const eyeRightRef = React139.useRef(null); const eyeLeftRef = React139.useRef(null); const [sightDir] = React139.useState(() => new Vector3()); const [transform] = React139.useState(() => new Object3D()); const [sightDirQuaternion] = React139.useState(() => new Quaternion()); const [_origin] = React139.useState(() => new Vector3()); const { invalidate } = useThree(); React139.useEffect(() => { var _meshRef$current; (_meshRef$current = meshRef.current) == null || _meshRef$current.geometry.setIndex(FacemeshDatas.TRIANGULATION); }, []); const [bboxSize] = React139.useState(() => new Vector3()); React139.useEffect(() => { var _meshRef$current2, _outerRef$current; const faceGeometry = (_meshRef$current2 = meshRef.current) == null ? void 0 : _meshRef$current2.geometry; if (!faceGeometry) return; faceGeometry.setFromPoints(points); faceGeometry.setDrawRange(0, FacemeshDatas.TRIANGULATION.length); if (facialTransformationMatrix) { transform.matrix.fromArray(facialTransformationMatrix.data); transform.matrix.decompose(transform.position, transform.quaternion, transform.scale); transform.rotation.y *= -1; transform.rotation.z *= -1; sightDirQuaternion.setFromEuler(transform.rotation); if (offset) { var _offsetRef$current; transform.position.y *= -1; transform.position.z *= -1; (_offsetRef$current = offsetRef.current) == null || _offsetRef$current.position.copy(transform.position.divideScalar(offsetScalar)); } else { var _offsetRef$current2; (_offsetRef$current2 = offsetRef.current) == null || _offsetRef$current2.position.set(0, 0, 0); } } else { normal(points[verticalTri[0]], points[verticalTri[1]], points[verticalTri[2]], sightDir); sightDirQuaternion.setFromUnitVectors(defaultLookAt, sightDir); } const sightDirQuaternionInverse = sightDirQuaternion.clone().invert(); faceGeometry.computeBoundingBox(); if (debug) invalidate(); faceGeometry.center(); faceGeometry.applyQuaternion(sightDirQuaternionInverse); (_outerRef$current = outerRef.current) == null || _outerRef$current.setRotationFromQuaternion(sightDirQuaternion); if (eyes) { if (!faceBlendshapes) { console.warn("Facemesh `eyes` option only works if `faceBlendshapes` is provided: skipping."); } else { if (eyeRightRef.current && eyeLeftRef.current && originRef.current) { if (eyesAsOrigin) { const eyeRightSphere = eyeRightRef.current._computeSphere(faceGeometry); const eyeLeftSphere = eyeLeftRef.current._computeSphere(faceGeometry); const eyesCenter = mean(eyeRightSphere.center, eyeLeftSphere.center); origin2 = eyesCenter.negate(); eyeRightRef.current._update(faceGeometry, faceBlendshapes, eyeRightSphere); eyeLeftRef.current._update(faceGeometry, faceBlendshapes, eyeLeftSphere); } else { eyeRightRef.current._update(faceGeometry, faceBlendshapes); eyeLeftRef.current._update(faceGeometry, faceBlendshapes); } } } } if (originRef.current) { if (origin2 !== void 0) { if (typeof origin2 === "number") { const position2 = faceGeometry.getAttribute("position"); _origin.set(-position2.getX(origin2), -position2.getY(origin2), -position2.getZ(origin2)); } else if (origin2.isVector3) { _origin.copy(origin2); } } else { _origin.setScalar(0); } originRef.current.position.copy(_origin); } if (scaleRef.current) { let scale5 = 1; if (width || height || depth) { faceGeometry.boundingBox.getSize(bboxSize); if (width) scale5 = width / bboxSize.x; if (height) scale5 = height / bboxSize.y; if (depth) scale5 = depth / bboxSize.z; } scaleRef.current.scale.setScalar(scale5 !== 1 ? scale5 : 1); } faceGeometry.computeVertexNormals(); faceGeometry.attributes.position.needsUpdate = true; }, [points, facialTransformationMatrix, faceBlendshapes, transform, offset, offsetScalar, width, height, depth, verticalTri, origin2, eyes, debug, invalidate, sightDir, sightDirQuaternion, bboxSize, _origin]); const api = React139.useMemo(() => ({ outerRef, meshRef, eyeRightRef, eyeLeftRef }), []); React139.useImperativeHandle(fref, () => api, [api]); const [meshBboxSize] = React139.useState(() => new Vector3()); const bbox = (_meshRef$current3 = meshRef.current) == null ? void 0 : _meshRef$current3.geometry.boundingBox; const one3 = (bbox == null ? void 0 : bbox.getSize(meshBboxSize).z) || 1; return React139.createElement("group", props, React139.createElement("group", { ref: offsetRef }, React139.createElement("group", { ref: outerRef }, React139.createElement("group", { ref: scaleRef }, debug ? React139.createElement(React139.Fragment, null, React139.createElement("axesHelper", { args: [one3] }), React139.createElement(Line4, { points: [[0, 0, 0], [0, 0, -one3]], color: 65535 })) : null, React139.createElement("group", { ref: originRef }, eyes && faceBlendshapes && React139.createElement("group", { name: "eyes" }, React139.createElement(FacemeshEye, { side: "left", ref: eyeRightRef, debug }), React139.createElement(FacemeshEye, { side: "right", ref: eyeLeftRef, debug })), React139.createElement("mesh", { ref: meshRef, name: "face" }, children, debug ? React139.createElement(React139.Fragment, null, bbox && React139.createElement("box3Helper", { args: [bbox] })) : null)))))); }); var FacemeshEyeDefaults = { contourLandmarks: { right: [33, 133, 159, 145, 153], left: [263, 362, 386, 374, 380] }, blendshapes: { right: [14, 16, 18, 12], // lookIn,lookOut, lookUp,lookDown left: [13, 15, 17, 11] // lookIn,lookOut, lookUp,lookDown }, color: { right: "red", left: "#00ff00" }, fov: { horizontal: 100, vertical: 90 } }; var FacemeshEye = React139.forwardRef(({ side, debug = true }, fref) => { const eyeMeshRef = React139.useRef(null); const irisDirRef = React139.useRef(null); const [sphere] = React139.useState(() => new Sphere()); const _computeSphere = React139.useCallback((faceGeometry) => { const position2 = faceGeometry.getAttribute("position"); const eyeContourLandmarks = FacemeshEyeDefaults.contourLandmarks[side]; const eyeContourPoints = eyeContourLandmarks.map((i4) => new Vector3(position2.getX(i4), position2.getY(i4), position2.getZ(i4))); sphere.center.set(0, 0, 0); eyeContourPoints.forEach((v5) => sphere.center.add(v5)); sphere.center.divideScalar(eyeContourPoints.length); sphere.radius = eyeContourPoints[0].sub(eyeContourPoints[1]).length() / 2; return sphere; }, [sphere, side]); const [rotation3] = React139.useState(() => new Euler()); const _update = React139.useCallback((faceGeometry, faceBlendshapes, sphere2) => { if (eyeMeshRef.current) { var _sphere6; (_sphere6 = sphere2) !== null && _sphere6 !== void 0 ? _sphere6 : sphere2 = _computeSphere(faceGeometry); eyeMeshRef.current.position.copy(sphere2.center); eyeMeshRef.current.scale.setScalar(sphere2.radius); } if (faceBlendshapes && irisDirRef.current) { const blendshapes = FacemeshEyeDefaults.blendshapes[side]; const lookIn = faceBlendshapes.categories[blendshapes[0]].score; const lookOut = faceBlendshapes.categories[blendshapes[1]].score; const lookUp = faceBlendshapes.categories[blendshapes[2]].score; const lookDown = faceBlendshapes.categories[blendshapes[3]].score; const hfov = FacemeshEyeDefaults.fov.horizontal * MathUtils.DEG2RAD; const vfov = FacemeshEyeDefaults.fov.vertical * MathUtils.DEG2RAD; const rx = hfov * 0.5 * (lookDown - lookUp); const ry = vfov * 0.5 * (lookIn - lookOut) * (side === "left" ? 1 : -1); rotation3.set(rx, ry, 0); irisDirRef.current.setRotationFromEuler(rotation3); } }, [_computeSphere, side, rotation3]); const api = React139.useMemo(() => ({ eyeMeshRef, irisDirRef, _computeSphere, _update }), [_computeSphere, _update]); React139.useImperativeHandle(fref, () => api, [api]); const color = FacemeshEyeDefaults.color[side]; return React139.createElement("group", null, React139.createElement("group", { ref: eyeMeshRef }, debug && React139.createElement("axesHelper", null), React139.createElement("group", { ref: irisDirRef }, React139.createElement(React139.Fragment, null, debug && React139.createElement(Line4, { points: [[0, 0, 0], [0, 0, -2]], lineWidth: 1, color }))))); }); var FacemeshDatas = { // Extracted from: https://github.com/tensorflow/tfjs-models/blob/a8f500809f5afe38feea27870c77e7ba03a6ece4/face-landmarks-detection/demos/shared/triangulation.js // prettier-ignore TRIANGULATION: [127, 34, 139, 11, 0, 37, 232, 231, 120, 72, 37, 39, 128, 121, 47, 232, 121, 128, 104, 69, 67, 175, 171, 148, 157, 154, 155, 118, 50, 101, 73, 39, 40, 9, 151, 108, 48, 115, 131, 194, 204, 211, 74, 40, 185, 80, 42, 183, 40, 92, 186, 230, 229, 118, 202, 212, 214, 83, 18, 17, 76, 61, 146, 160, 29, 30, 56, 157, 173, 106, 204, 194, 135, 214, 192, 203, 165, 98, 21, 71, 68, 51, 45, 4, 144, 24, 23, 77, 146, 91, 205, 50, 187, 201, 200, 18, 91, 106, 182, 90, 91, 181, 85, 84, 17, 206, 203, 36, 148, 171, 140, 92, 40, 39, 193, 189, 244, 159, 158, 28, 247, 246, 161, 236, 3, 196, 54, 68, 104, 193, 168, 8, 117, 228, 31, 189, 193, 55, 98, 97, 99, 126, 47, 100, 166, 79, 218, 155, 154, 26, 209, 49, 131, 135, 136, 150, 47, 126, 217, 223, 52, 53, 45, 51, 134, 211, 170, 140, 67, 69, 108, 43, 106, 91, 230, 119, 120, 226, 130, 247, 63, 53, 52, 238, 20, 242, 46, 70, 156, 78, 62, 96, 46, 53, 63, 143, 34, 227, 173, 155, 133, 123, 117, 111, 44, 125, 19, 236, 134, 51, 216, 206, 205, 154, 153, 22, 39, 37, 167, 200, 201, 208, 36, 142, 100, 57, 212, 202, 20, 60, 99, 28, 158, 157, 35, 226, 113, 160, 159, 27, 204, 202, 210, 113, 225, 46, 43, 202, 204, 62, 76, 77, 137, 123, 116, 41, 38, 72, 203, 129, 142, 64, 98, 240, 49, 102, 64, 41, 73, 74, 212, 216, 207, 42, 74, 184, 169, 170, 211, 170, 149, 176, 105, 66, 69, 122, 6, 168, 123, 147, 187, 96, 77, 90, 65, 55, 107, 89, 90, 180, 101, 100, 120, 63, 105, 104, 93, 137, 227, 15, 86, 85, 129, 102, 49, 14, 87, 86, 55, 8, 9, 100, 47, 121, 145, 23, 22, 88, 89, 179, 6, 122, 196, 88, 95, 96, 138, 172, 136, 215, 58, 172, 115, 48, 219, 42, 80, 81, 195, 3, 51, 43, 146, 61, 171, 175, 199, 81, 82, 38, 53, 46, 225, 144, 163, 110, 246, 33, 7, 52, 65, 66, 229, 228, 117, 34, 127, 234, 107, 108, 69, 109, 108, 151, 48, 64, 235, 62, 78, 191, 129, 209, 126, 111, 35, 143, 163, 161, 246, 117, 123, 50, 222, 65, 52, 19, 125, 141, 221, 55, 65, 3, 195, 197, 25, 7, 33, 220, 237, 44, 70, 71, 139, 122, 193, 245, 247, 130, 33, 71, 21, 162, 153, 158, 159, 170, 169, 150, 188, 174, 196, 216, 186, 92, 144, 160, 161, 2, 97, 167, 141, 125, 241, 164, 167, 37, 72, 38, 12, 145, 159, 160, 38, 82, 13, 63, 68, 71, 226, 35, 111, 158, 153, 154, 101, 50, 205, 206, 92, 165, 209, 198, 217, 165, 167, 97, 220, 115, 218, 133, 112, 243, 239, 238, 241, 214, 135, 169, 190, 173, 133, 171, 208, 32, 125, 44, 237, 86, 87, 178, 85, 86, 179, 84, 85, 180, 83, 84, 181, 201, 83, 182, 137, 93, 132, 76, 62, 183, 61, 76, 184, 57, 61, 185, 212, 57, 186, 214, 207, 187, 34, 143, 156, 79, 239, 237, 123, 137, 177, 44, 1, 4, 201, 194, 32, 64, 102, 129, 213, 215, 138, 59, 166, 219, 242, 99, 97, 2, 94, 141, 75, 59, 235, 24, 110, 228, 25, 130, 226, 23, 24, 229, 22, 23, 230, 26, 22, 231, 112, 26, 232, 189, 190, 243, 221, 56, 190, 28, 56, 221, 27, 28, 222, 29, 27, 223, 30, 29, 224, 247, 30, 225, 238, 79, 20, 166, 59, 75, 60, 75, 240, 147, 177, 215, 20, 79, 166, 187, 147, 213, 112, 233, 244, 233, 128, 245, 128, 114, 188, 114, 217, 174, 131, 115, 220, 217, 198, 236, 198, 131, 134, 177, 132, 58, 143, 35, 124, 110, 163, 7, 228, 110, 25, 356, 389, 368, 11, 302, 267, 452, 350, 349, 302, 303, 269, 357, 343, 277, 452, 453, 357, 333, 332, 297, 175, 152, 377, 384, 398, 382, 347, 348, 330, 303, 304, 270, 9, 336, 337, 278, 279, 360, 418, 262, 431, 304, 408, 409, 310, 415, 407, 270, 409, 410, 450, 348, 347, 422, 430, 434, 313, 314, 17, 306, 307, 375, 387, 388, 260, 286, 414, 398, 335, 406, 418, 364, 367, 416, 423, 358, 327, 251, 284, 298, 281, 5, 4, 373, 374, 253, 307, 320, 321, 425, 427, 411, 421, 313, 18, 321, 405, 406, 320, 404, 405, 315, 16, 17, 426, 425, 266, 377, 400, 369, 322, 391, 269, 417, 465, 464, 386, 257, 258, 466, 260, 388, 456, 399, 419, 284, 332, 333, 417, 285, 8, 346, 340, 261, 413, 441, 285, 327, 460, 328, 355, 371, 329, 392, 439, 438, 382, 341, 256, 429, 420, 360, 364, 394, 379, 277, 343, 437, 443, 444, 283, 275, 440, 363, 431, 262, 369, 297, 338, 337, 273, 375, 321, 450, 451, 349, 446, 342, 467, 293, 334, 282, 458, 461, 462, 276, 353, 383, 308, 324, 325, 276, 300, 293, 372, 345, 447, 382, 398, 362, 352, 345, 340, 274, 1, 19, 456, 248, 281, 436, 427, 425, 381, 256, 252, 269, 391, 393, 200, 199, 428, 266, 330, 329, 287, 273, 422, 250, 462, 328, 258, 286, 384, 265, 353, 342, 387, 259, 257, 424, 431, 430, 342, 353, 276, 273, 335, 424, 292, 325, 307, 366, 447, 345, 271, 303, 302, 423, 266, 371, 294, 455, 460, 279, 278, 294, 271, 272, 304, 432, 434, 427, 272, 407, 408, 394, 430, 431, 395, 369, 400, 334, 333, 299, 351, 417, 168, 352, 280, 411, 325, 319, 320, 295, 296, 336, 319, 403, 404, 330, 348, 349, 293, 298, 333, 323, 454, 447, 15, 16, 315, 358, 429, 279, 14, 15, 316, 285, 336, 9, 329, 349, 350, 374, 380, 252, 318, 402, 403, 6, 197, 419, 318, 319, 325, 367, 364, 365, 435, 367, 397, 344, 438, 439, 272, 271, 311, 195, 5, 281, 273, 287, 291, 396, 428, 199, 311, 271, 268, 283, 444, 445, 373, 254, 339, 263, 466, 249, 282, 334, 296, 449, 347, 346, 264, 447, 454, 336, 296, 299, 338, 10, 151, 278, 439, 455, 292, 407, 415, 358, 371, 355, 340, 345, 372, 390, 249, 466, 346, 347, 280, 442, 443, 282, 19, 94, 370, 441, 442, 295, 248, 419, 197, 263, 255, 359, 440, 275, 274, 300, 383, 368, 351, 412, 465, 263, 467, 466, 301, 368, 389, 380, 374, 386, 395, 378, 379, 412, 351, 419, 436, 426, 322, 373, 390, 388, 2, 164, 393, 370, 462, 461, 164, 0, 267, 302, 11, 12, 374, 373, 387, 268, 12, 13, 293, 300, 301, 446, 261, 340, 385, 384, 381, 330, 266, 425, 426, 423, 391, 429, 355, 437, 391, 327, 326, 440, 457, 438, 341, 382, 362, 459, 457, 461, 434, 430, 394, 414, 463, 362, 396, 369, 262, 354, 461, 457, 316, 403, 402, 315, 404, 403, 314, 405, 404, 313, 406, 405, 421, 418, 406, 366, 401, 361, 306, 408, 407, 291, 409, 408, 287, 410, 409, 432, 436, 410, 434, 416, 411, 264, 368, 383, 309, 438, 457, 352, 376, 401, 274, 275, 4, 421, 428, 262, 294, 327, 358, 433, 416, 367, 289, 455, 439, 462, 370, 326, 2, 326, 370, 305, 460, 455, 254, 449, 448, 255, 261, 446, 253, 450, 449, 252, 451, 450, 256, 452, 451, 341, 453, 452, 413, 464, 463, 441, 413, 414, 258, 442, 441, 257, 443, 442, 259, 444, 443, 260, 445, 444, 467, 342, 445, 459, 458, 250, 289, 392, 290, 290, 328, 460, 376, 433, 435, 250, 290, 392, 411, 416, 433, 341, 463, 464, 453, 464, 465, 357, 465, 412, 343, 412, 399, 360, 363, 440, 437, 399, 456, 420, 456, 363, 401, 435, 288, 372, 383, 353, 339, 255, 249, 448, 261, 255, 133, 243, 190, 133, 155, 112, 33, 246, 247, 33, 130, 25, 398, 384, 286, 362, 398, 414, 362, 463, 341, 263, 359, 467, 263, 249, 255, 466, 467, 260, 75, 60, 166, 238, 239, 79, 162, 127, 139, 72, 11, 37, 121, 232, 120, 73, 72, 39, 114, 128, 47, 233, 232, 128, 103, 104, 67, 152, 175, 148, 173, 157, 155, 119, 118, 101, 74, 73, 40, 107, 9, 108, 49, 48, 131, 32, 194, 211, 184, 74, 185, 191, 80, 183, 185, 40, 186, 119, 230, 118, 210, 202, 214, 84, 83, 17, 77, 76, 146, 161, 160, 30, 190, 56, 173, 182, 106, 194, 138, 135, 192, 129, 203, 98, 54, 21, 68, 5, 51, 4, 145, 144, 23, 90, 77, 91, 207, 205, 187, 83, 201, 18, 181, 91, 182, 180, 90, 181, 16, 85, 17, 205, 206, 36, 176, 148, 140, 165, 92, 39, 245, 193, 244, 27, 159, 28, 30, 247, 161, 174, 236, 196, 103, 54, 104, 55, 193, 8, 111, 117, 31, 221, 189, 55, 240, 98, 99, 142, 126, 100, 219, 166, 218, 112, 155, 26, 198, 209, 131, 169, 135, 150, 114, 47, 217, 224, 223, 53, 220, 45, 134, 32, 211, 140, 109, 67, 108, 146, 43, 91, 231, 230, 120, 113, 226, 247, 105, 63, 52, 241, 238, 242, 124, 46, 156, 95, 78, 96, 70, 46, 63, 116, 143, 227, 116, 123, 111, 1, 44, 19, 3, 236, 51, 207, 216, 205, 26, 154, 22, 165, 39, 167, 199, 200, 208, 101, 36, 100, 43, 57, 202, 242, 20, 99, 56, 28, 157, 124, 35, 113, 29, 160, 27, 211, 204, 210, 124, 113, 46, 106, 43, 204, 96, 62, 77, 227, 137, 116, 73, 41, 72, 36, 203, 142, 235, 64, 240, 48, 49, 64, 42, 41, 74, 214, 212, 207, 183, 42, 184, 210, 169, 211, 140, 170, 176, 104, 105, 69, 193, 122, 168, 50, 123, 187, 89, 96, 90, 66, 65, 107, 179, 89, 180, 119, 101, 120, 68, 63, 104, 234, 93, 227, 16, 15, 85, 209, 129, 49, 15, 14, 86, 107, 55, 9, 120, 100, 121, 153, 145, 22, 178, 88, 179, 197, 6, 196, 89, 88, 96, 135, 138, 136, 138, 215, 172, 218, 115, 219, 41, 42, 81, 5, 195, 51, 57, 43, 61, 208, 171, 199, 41, 81, 38, 224, 53, 225, 24, 144, 110, 105, 52, 66, 118, 229, 117, 227, 34, 234, 66, 107, 69, 10, 109, 151, 219, 48, 235, 183, 62, 191, 142, 129, 126, 116, 111, 143, 7, 163, 246, 118, 117, 50, 223, 222, 52, 94, 19, 141, 222, 221, 65, 196, 3, 197, 45, 220, 44, 156, 70, 139, 188, 122, 245, 139, 71, 162, 145, 153, 159, 149, 170, 150, 122, 188, 196, 206, 216, 92, 163, 144, 161, 164, 2, 167, 242, 141, 241, 0, 164, 37, 11, 72, 12, 144, 145, 160, 12, 38, 13, 70, 63, 71, 31, 226, 111, 157, 158, 154, 36, 101, 205, 203, 206, 165, 126, 209, 217, 98, 165, 97, 237, 220, 218, 237, 239, 241, 210, 214, 169, 140, 171, 32, 241, 125, 237, 179, 86, 178, 180, 85, 179, 181, 84, 180, 182, 83, 181, 194, 201, 182, 177, 137, 132, 184, 76, 183, 185, 61, 184, 186, 57, 185, 216, 212, 186, 192, 214, 187, 139, 34, 156, 218, 79, 237, 147, 123, 177, 45, 44, 4, 208, 201, 32, 98, 64, 129, 192, 213, 138, 235, 59, 219, 141, 242, 97, 97, 2, 141, 240, 75, 235, 229, 24, 228, 31, 25, 226, 230, 23, 229, 231, 22, 230, 232, 26, 231, 233, 112, 232, 244, 189, 243, 189, 221, 190, 222, 28, 221, 223, 27, 222, 224, 29, 223, 225, 30, 224, 113, 247, 225, 99, 60, 240, 213, 147, 215, 60, 20, 166, 192, 187, 213, 243, 112, 244, 244, 233, 245, 245, 128, 188, 188, 114, 174, 134, 131, 220, 174, 217, 236, 236, 198, 134, 215, 177, 58, 156, 143, 124, 25, 110, 7, 31, 228, 25, 264, 356, 368, 0, 11, 267, 451, 452, 349, 267, 302, 269, 350, 357, 277, 350, 452, 357, 299, 333, 297, 396, 175, 377, 381, 384, 382, 280, 347, 330, 269, 303, 270, 151, 9, 337, 344, 278, 360, 424, 418, 431, 270, 304, 409, 272, 310, 407, 322, 270, 410, 449, 450, 347, 432, 422, 434, 18, 313, 17, 291, 306, 375, 259, 387, 260, 424, 335, 418, 434, 364, 416, 391, 423, 327, 301, 251, 298, 275, 281, 4, 254, 373, 253, 375, 307, 321, 280, 425, 411, 200, 421, 18, 335, 321, 406, 321, 320, 405, 314, 315, 17, 423, 426, 266, 396, 377, 369, 270, 322, 269, 413, 417, 464, 385, 386, 258, 248, 456, 419, 298, 284, 333, 168, 417, 8, 448, 346, 261, 417, 413, 285, 326, 327, 328, 277, 355, 329, 309, 392, 438, 381, 382, 256, 279, 429, 360, 365, 364, 379, 355, 277, 437, 282, 443, 283, 281, 275, 363, 395, 431, 369, 299, 297, 337, 335, 273, 321, 348, 450, 349, 359, 446, 467, 283, 293, 282, 250, 458, 462, 300, 276, 383, 292, 308, 325, 283, 276, 293, 264, 372, 447, 346, 352, 340, 354, 274, 19, 363, 456, 281, 426, 436, 425, 380, 381, 252, 267, 269, 393, 421, 200, 428, 371, 266, 329, 432, 287, 422, 290, 250, 328, 385, 258, 384, 446, 265, 342, 386, 387, 257, 422, 424, 430, 445, 342, 276, 422, 273, 424, 306, 292, 307, 352, 366, 345, 268, 271, 302, 358, 423, 371, 327, 294, 460, 331, 279, 294, 303, 271, 304, 436, 432, 427, 304, 272, 408, 395, 394, 431, 378, 395, 400, 296, 334, 299, 6, 351, 168, 376, 352, 411, 307, 325, 320, 285, 295, 336, 320, 319, 404, 329, 330, 349, 334, 293, 333, 366, 323, 447, 316, 15, 315, 331, 358, 279, 317, 14, 316, 8, 285, 9, 277, 329, 350, 253, 374, 252, 319, 318, 403, 351, 6, 419, 324, 318, 325, 397, 367, 365, 288, 435, 397, 278, 344, 439, 310, 272, 311, 248, 195, 281, 375, 273, 291, 175, 396, 199, 312, 311, 268, 276, 283, 445, 390, 373, 339, 295, 282, 296, 448, 449, 346, 356, 264, 454, 337, 336, 299, 337, 338, 151, 294, 278, 455, 308, 292, 415, 429, 358, 355, 265, 340, 372, 388, 390, 466, 352, 346, 280, 295, 442, 282, 354, 19, 370, 285, 441, 295, 195, 248, 197, 457, 440, 274, 301, 300, 368, 417, 351, 465, 251, 301, 389, 385, 380, 386, 394, 395, 379, 399, 412, 419, 410, 436, 322, 387, 373, 388, 326, 2, 393, 354, 370, 461, 393, 164, 267, 268, 302, 12, 386, 374, 387, 312, 268, 13, 298, 293, 301, 265, 446, 340, 380, 385, 381, 280, 330, 425, 322, 426, 391, 420, 429, 437, 393, 391, 326, 344, 440, 438, 458, 459, 461, 364, 434, 394, 428, 396, 262, 274, 354, 457, 317, 316, 402, 316, 315, 403, 315, 314, 404, 314, 313, 405, 313, 421, 406, 323, 366, 361, 292, 306, 407, 306, 291, 408, 291, 287, 409, 287, 432, 410, 427, 434, 411, 372, 264, 383, 459, 309, 457, 366, 352, 401, 1, 274, 4, 418, 421, 262, 331, 294, 358, 435, 433, 367, 392, 289, 439, 328, 462, 326, 94, 2, 370, 289, 305, 455, 339, 254, 448, 359, 255, 446, 254, 253, 449, 253, 252, 450, 252, 256, 451, 256, 341, 452, 414, 413, 463, 286, 441, 414, 286, 258, 441, 258, 257, 442, 257, 259, 443, 259, 260, 444, 260, 467, 445, 309, 459, 250, 305, 289, 290, 305, 290, 460, 401, 376, 435, 309, 250, 392, 376, 411, 433, 453, 341, 464, 357, 453, 465, 343, 357, 412, 437, 343, 399, 344, 360, 440, 420, 437, 456, 360, 420, 363, 361, 401, 288, 265, 372, 353, 390, 339, 249, 339, 448, 255], // My face as default (captured with a 640x480 webcam) // prettier-ignore SAMPLE_FACE: { "keypoints": [{ "x": 356.2804412841797, "y": 295.1960563659668, "z": -23.786449432373047, "name": "lips" }, { "x": 354.8859405517578, "y": 264.69520568847656, "z": -36.718435287475586 }, { "x": 355.2180862426758, "y": 275.3360366821289, "z": -21.183712482452393 }, { "x": 347.349853515625, "y": 242.4400234222412, "z": -25.093655586242676 }, { "x": 354.40135955810547, "y": 256.67933464050293, "z": -38.23572635650635 }, { "x": 353.7689971923828, "y": 247.54886627197266, "z": -34.5475435256958 }, { "x": 352.1288299560547, "y": 227.34312057495117, "z": -13.095386028289795 }, { "x": 303.5013198852539, "y": 234.67002868652344, "z": 12.500141859054565, "name": "rightEye" }, { "x": 351.09378814697266, "y": 211.87547206878662, "z": -6.413471698760986 }, { "x": 350.7115936279297, "y": 202.1251630783081, "z": -6.413471698760986 }, { "x": 348.33667755126953, "y": 168.7741756439209, "z": 6.483500003814697, "name": "faceOval" }, { "x": 356.4806365966797, "y": 299.2995357513428, "z": -23.144519329071045 }, { "x": 356.5511703491211, "y": 302.66146659851074, "z": -21.020312309265137 }, { "x": 356.6239547729492, "y": 304.1536331176758, "z": -18.137459754943848, "name": "lips" }, { "x": 356.5807342529297, "y": 305.1840591430664, "z": -18.767719268798828, "name": "lips" }, { "x": 356.8241500854492, "y": 308.25711250305176, "z": -20.16829490661621 }, { "x": 357.113037109375, "y": 312.26277351379395, "z": -22.10575819015503 }, { "x": 357.34962463378906, "y": 317.1123218536377, "z": -21.837315559387207, "name": "lips" }, { "x": 357.6658630371094, "y": 325.51036834716797, "z": -16.27002477645874 }, { "x": 355.0201416015625, "y": 269.36279296875, "z": -33.73054027557373 }, { "x": 348.5237503051758, "y": 270.33411026000977, "z": -24.93025302886963 }, { "x": 279.97331619262695, "y": 213.24176788330078, "z": 47.759642601013184, "name": "faceOval" }, { "x": 322.66529083251953, "y": 238.5027265548706, "z": 5.535193085670471 }, { "x": 316.0983657836914, "y": 239.94489669799805, "z": 5.777376294136047 }, { "x": 309.9431610107422, "y": 240.24518966674805, "z": 7.510589361190796 }, { "x": 301.31994247436523, "y": 237.86138534545898, "z": 13.118728399276733 }, { "x": 328.14266204833984, "y": 235.80496788024902, "z": 6.646900177001953 }, { "x": 313.7326431274414, "y": 222.11161136627197, "z": 3.9887237548828125 }, { "x": 320.45196533203125, "y": 221.87729358673096, "z": 4.601476192474365 }, { "x": 307.35679626464844, "y": 223.63793849945068, "z": 5.932023525238037 }, { "x": 303.0031204223633, "y": 226.3743782043457, "z": 8.479321002960205 }, { "x": 296.80023193359375, "y": 242.94299125671387, "z": 15.931552648544312 }, { "x": 332.2352981567383, "y": 340.77341079711914, "z": -10.165848731994629 }, { "x": 301.38587951660156, "y": 233.46447944641113, "z": 14.764405488967896, "name": "rightEye" }, { "x": 279.0147018432617, "y": 244.37155723571777, "z": 45.77549457550049 }, { "x": 289.60548400878906, "y": 239.1807460784912, "z": 23.191204071044922 }, { "x": 320.32257080078125, "y": 267.1292781829834, "z": -4.954537749290466 }, { "x": 347.64583587646484, "y": 294.4955062866211, "z": -23.062820434570312, "name": "lips" }, { "x": 349.28138732910156, "y": 303.1095886230469, "z": -20.238323211669922 }, { "x": 338.9453125, "y": 298.19186210632324, "z": -19.456336498260498, "name": "lips" }, { "x": 333.36788177490234, "y": 302.6706790924072, "z": -14.776077270507812, "name": "lips" }, { "x": 342.89188385009766, "y": 304.3561363220215, "z": -17.752301692962646 }, { "x": 337.7375030517578, "y": 306.0098361968994, "z": -13.410515785217285 }, { "x": 325.6159210205078, "y": 316.22995376586914, "z": -6.681914925575256 }, { "x": 349.0104675292969, "y": 264.9818515777588, "z": -36.274919509887695 }, { "x": 347.7138900756836, "y": 257.5664806365967, "z": -37.67549514770508 }, { "x": 291.79357528686523, "y": 218.88171672821045, "z": 11.578094959259033, "name": "rightEyebrow" }, { "x": 332.2689437866211, "y": 247.56946563720703, "z": -3.3730539679527283 }, { "x": 332.0074462890625, "y": 267.1201229095459, "z": -19.969879388809204 }, { "x": 331.27952575683594, "y": 263.6967658996582, "z": -17.47218608856201 }, { "x": 301.04373931884766, "y": 269.56552505493164, "z": 3.61815482378006 }, { "x": 347.4863815307617, "y": 249.0706443786621, "z": -32.633421421051025 }, { "x": 307.26118087768555, "y": 208.2646894454956, "z": 1.1591226607561111, "name": "rightEyebrow" }, { "x": 297.91919708251953, "y": 212.22604751586914, "z": 5.914516448974609, "name": "rightEyebrow" }, { "x": 285.1651382446289, "y": 197.98450469970703, "z": 36.391637325286865, "name": "faceOval" }, { "x": 337.04097747802734, "y": 211.25229835510254, "z": -4.548954665660858 }, { "x": 326.5912628173828, "y": 223.16698551177979, "z": 6.670243740081787 }, { "x": 320.05664825439453, "y": 309.5834255218506, "z": -4.055835008621216 }, { "x": 289.6866226196289, "y": 314.617395401001, "z": 53.875489234924316, "name": "faceOval" }, { "x": 337.4256896972656, "y": 270.8755302429199, "z": -17.67060160636902 }, { "x": 343.69922637939453, "y": 273.0000400543213, "z": -18.756048679351807 }, { "x": 327.4242401123047, "y": 309.22399520874023, "z": -4.703601002693176, "name": "lips" }, { "x": 330.37220001220703, "y": 308.3323001861572, "z": -6.442649960517883 }, { "x": 293.87027740478516, "y": 207.7961826324463, "z": 9.821539521217346, "name": "rightEyebrow" }, { "x": 332.11437225341797, "y": 271.22812271118164, "z": -16.64351224899292 }, { "x": 320.1197814941406, "y": 207.40366458892822, "z": -2.48164564371109, "name": "rightEyebrow" }, { "x": 318.59575271606445, "y": 201.07443809509277, "z": -3.110446035861969, "name": "rightEyebrow" }, { "x": 310.72303771972656, "y": 175.75075149536133, "z": 13.328815698623657, "name": "faceOval" }, { "x": 289.67578887939453, "y": 202.29835510253906, "z": 21.370456218719482 }, { "x": 315.30879974365234, "y": 187.35260009765625, "z": 5.0304025411605835 }, { "x": 287.8936767578125, "y": 216.54793739318848, "z": 17.81065821647644, "name": "rightEyebrow" }, { "x": 283.9391899108887, "y": 215.01142501831055, "z": 32.04984903335571 }, { "x": 348.35330963134766, "y": 299.4155788421631, "z": -22.47924566268921 }, { "x": 341.1790466308594, "y": 301.8221855163574, "z": -18.977805376052856 }, { "x": 335.69713592529297, "y": 304.4266891479492, "z": -14.682706594467163 }, { "x": 339.4615173339844, "y": 272.3654365539551, "z": -16.38674020767212 }, { "x": 328.99600982666016, "y": 308.86685371398926, "z": -5.616893768310547 }, { "x": 332.00313568115234, "y": 309.1875743865967, "z": -10.335084199905396 }, { "x": 331.0068130493164, "y": 307.9274368286133, "z": -6.681914925575256, "name": "lips" }, { "x": 341.13792419433594, "y": 266.4876937866211, "z": -26.56425952911377 }, { "x": 339.02950286865234, "y": 305.6663703918457, "z": -12.33674168586731, "name": "lips" }, { "x": 344.22935485839844, "y": 304.9452781677246, "z": -15.161235332489014, "name": "lips" }, { "x": 350.1844024658203, "y": 304.374303817749, "z": -17.5305438041687, "name": "lips" }, { "x": 348.52630615234375, "y": 325.9562301635742, "z": -16.164982318878174 }, { "x": 348.6581802368164, "y": 317.1624183654785, "z": -21.510512828826904, "name": "lips" }, { "x": 348.9766311645508, "y": 312.1923065185547, "z": -21.708929538726807 }, { "x": 349.2427444458008, "y": 308.0660820007324, "z": -19.643079042434692 }, { "x": 349.67491149902344, "y": 305.42747497558594, "z": -18.16080331802368, "name": "lips" }, { "x": 337.95589447021484, "y": 306.6535949707031, "z": -12.803598642349243, "name": "lips" }, { "x": 337.06878662109375, "y": 307.63169288635254, "z": -14.274203777313232 }, { "x": 335.77449798583984, "y": 309.8449516296387, "z": -15.698124170303345 }, { "x": 334.6099090576172, "y": 312.7997016906738, "z": -14.764405488967896, "name": "lips" }, { "x": 327.2330856323242, "y": 293.80866050720215, "z": -11.864047050476074 }, { "x": 280.97679138183594, "y": 279.79928970336914, "z": 68.90834331512451, "name": "faceOval" }, { "x": 355.13843536376953, "y": 271.7875671386719, "z": -25.350427627563477 }, { "x": 334.7235870361328, "y": 307.4656391143799, "z": -9.302158951759338, "name": "lips" }, { "x": 333.5293960571289, "y": 307.89782524108887, "z": -10.200862884521484 }, { "x": 346.29688262939453, "y": 276.4256286621094, "z": -19.748122692108154 }, { "x": 335.16246795654297, "y": 276.22097969055176, "z": -12.313398122787476 }, { "x": 345.09132385253906, "y": 274.7082996368408, "z": -19.304605722427368 }, { "x": 325.4267883300781, "y": 252.95130729675293, "z": -1.6661019623279572 }, { "x": 315.347843170166, "y": 259.05200958251953, "z": -0.25604281574487686 }, { "x": 330.44933319091797, "y": 267.7570152282715, "z": -14.017432928085327 }, { "x": 294.96768951416016, "y": 185.26001930236816, "z": 23.903164863586426, "name": "faceOval" }, { "x": 299.63531494140625, "y": 192.7913761138916, "z": 12.640198469161987 }, { "x": 304.5452117919922, "y": 202.4142837524414, "z": 3.244667649269104, "name": "rightEyebrow" }, { "x": 331.6915512084961, "y": 320.0467872619629, "z": -10.632705688476562 }, { "x": 334.5911407470703, "y": 201.27566814422607, "z": -6.133356094360352, "name": "rightEyebrow" }, { "x": 331.4815902709961, "y": 185.44180870056152, "z": 0.6627205014228821 }, { "x": 328.05816650390625, "y": 170.8385467529297, "z": 7.358860373497009, "name": "faceOval" }, { "x": 304.49764251708984, "y": 239.76297855377197, "z": 10.387605428695679 }, { "x": 290.6382179260254, "y": 248.85257720947266, "z": 19.03616428375244 }, { "x": 331.5682601928711, "y": 233.20727348327637, "z": 7.837390303611755 }, { "x": 295.5115509033203, "y": 228.9834451675415, "z": 14.41426157951355 }, { "x": 336.94332122802734, "y": 241.8259334564209, "z": -5.27842104434967 }, { "x": 336.2792205810547, "y": 262.7049922943115, "z": -26.12074375152588 }, { "x": 284.4102478027344, "y": 255.3262710571289, "z": 25.467140674591064 }, { "x": 295.1420593261719, "y": 253.02655220031738, "z": 12.430112361907959 }, { "x": 303.5196113586426, "y": 254.20703887939453, "z": 6.139191389083862 }, { "x": 315.73450088500977, "y": 251.64799690246582, "z": 3.3788898587226868 }, { "x": 324.69661712646484, "y": 247.56494522094727, "z": 2.3328344523906708 }, { "x": 331.57970428466797, "y": 243.02241325378418, "z": 1.1423448473215103 }, { "x": 345.6210708618164, "y": 229.9976634979248, "z": -10.825285911560059 }, { "x": 286.26644134521484, "y": 270.37991523742676, "z": 21.708929538726807 }, { "x": 290.2525520324707, "y": 228.4921360015869, "z": 17.71728754043579 }, { "x": 351.65367126464844, "y": 269.3400764465332, "z": -33.450424671173096 }, { "x": 333.1378936767578, "y": 253.88388633728027, "z": -7.230473756790161 }, { "x": 277.8318977355957, "y": 246.95331573486328, "z": 68.20805549621582, "name": "faceOval" }, { "x": 336.6680908203125, "y": 238.10003757476807, "z": 0.7688578963279724 }, { "x": 329.95800018310547, "y": 269.18323516845703, "z": -7.207130789756775 }, { "x": 299.17491912841797, "y": 234.13324356079102, "z": 15.95489501953125 }, { "x": 335.61729431152344, "y": 258.71752738952637, "z": -23.016133308410645 }, { "x": 284.1079330444336, "y": 297.0343494415283, "z": 63.25934886932373, "name": "faceOval" }, { "x": 331.44542694091797, "y": 230.6892442703247, "z": 9.92658257484436, "name": "rightEye" }, { "x": 341.41536712646484, "y": 253.01264762878418, "z": -29.038610458374023 }, { "x": 303.5472869873047, "y": 327.5896739959717, "z": 16.725212335586548 }, { "x": 304.7756576538086, "y": 337.4389457702637, "z": 27.38126277923584, "name": "faceOval" }, { "x": 280.80501556396484, "y": 275.32050132751465, "z": 45.0752067565918 }, { "x": 295.43582916259766, "y": 318.4501647949219, "z": 26.2608003616333 }, { "x": 281.4303207397461, "y": 228.7355661392212, "z": 40.94350814819336 }, { "x": 331.2549591064453, "y": 349.4216537475586, "z": -7.376367449760437 }, { "x": 352.4247741699219, "y": 271.7330074310303, "z": -24.953596591949463 }, { "x": 327.5672912597656, "y": 260.41900634765625, "z": -5.456410646438599 }, { "x": 284.5432472229004, "y": 241.7647933959961, "z": 29.668869972229004 }, { "x": 310, "y": 235.66174507141113, "z": 8.502663969993591, "name": "rightEye" }, { "x": 315.7071113586426, "y": 235.7572603225708, "z": 6.938687562942505, "name": "rightEye" }, { "x": 330.41088104248047, "y": 311.04143142700195, "z": -9.325502514839172, "name": "lips" }, { "x": 288.5377502441406, "y": 285.31983375549316, "z": 21.837315559387207 }, { "x": 344.55039978027344, "y": 359.4300842285156, "z": -6.705257892608643, "name": "faceOval" }, { "x": 323.41880798339844, "y": 351.67362213134766, "z": 7.802375555038452, "name": "faceOval" }, { "x": 314.64088439941406, "y": 346.11894607543945, "z": 16.36339783668518, "name": "faceOval" }, { "x": 349.4945526123047, "y": 184.8434829711914, "z": -0.21847527474164963 }, { "x": 359.24694061279297, "y": 359.8348903656006, "z": -8.403456211090088, "name": "faceOval" }, { "x": 321.26182556152344, "y": 234.64492321014404, "z": 6.90950870513916, "name": "rightEye" }, { "x": 326.318359375, "y": 232.90250301361084, "z": 8.029969334602356, "name": "rightEye" }, { "x": 329.6211624145508, "y": 231.6195774078369, "z": 9.722331762313843, "name": "rightEye" }, { "x": 285.9398078918457, "y": 228.2351303100586, "z": 24.650139808654785 }, { "x": 325.79288482666016, "y": 227.88007736206055, "z": 7.469738721847534, "name": "rightEye" }, { "x": 320.1699447631836, "y": 227.5934886932373, "z": 6.168370842933655, "name": "rightEye" }, { "x": 314.85408782958984, "y": 227.85282611846924, "z": 6.2675780057907104, "name": "rightEye" }, { "x": 309.3084907531738, "y": 229.1516876220703, "z": 7.7031683921813965, "name": "rightEye" }, { "x": 305.5621337890625, "y": 230.92366218566895, "z": 9.722331762313843, "name": "rightEye" }, { "x": 277.8681945800781, "y": 228.5354232788086, "z": 59.71122741699219, "name": "faceOval" }, { "x": 306.1444664001465, "y": 235.1954698562622, "z": 10.603528022766113, "name": "rightEye" }, { "x": 355.4478454589844, "y": 281.96210861206055, "z": -20.565123558044434 }, { "x": 333.02661895751953, "y": 288.0105400085449, "z": -14.72939133644104 }, { "x": 337.15728759765625, "y": 269.2059516906738, "z": -19.8414945602417 }, { "x": 345.9898376464844, "y": 283.5453128814697, "z": -20.4834246635437 }, { "x": 351.48963928222656, "y": 219.98916149139404, "z": -7.0378947257995605 }, { "x": 312.39574432373047, "y": 336.50628089904785, "z": 8.671900033950806 }, { "x": 321.32152557373047, "y": 343.1755256652832, "z": 0.9067271649837494 }, { "x": 343.78379821777344, "y": 353.2975959777832, "z": -14.355905055999756 }, { "x": 296.8791389465332, "y": 327.91497230529785, "z": 41.01353645324707, "name": "faceOval" }, { "x": 329.6939468383789, "y": 229.27897453308105, "z": 8.934508562088013, "name": "rightEye" }, { "x": 341.6905212402344, "y": 241.4073657989502, "z": -14.589333534240723 }, { "x": 359.03079986572266, "y": 353.48859786987305, "z": -15.803166627883911 }, { "x": 333.1861877441406, "y": 356.43213272094727, "z": -1.0234417766332626, "name": "faceOval" }, { "x": 283.97483825683594, "y": 291.4318656921387, "z": 41.94725513458252 }, { "x": 343.33770751953125, "y": 305.830135345459, "z": -15.756480693817139, "name": "lips" }, { "x": 342.40283966064453, "y": 307.7453899383545, "z": -17.4021577835083 }, { "x": 341.53621673583984, "y": 311.0595703125, "z": -19.047834873199463 }, { "x": 340.9107208251953, "y": 315.4837703704834, "z": -18.5576331615448, "name": "lips" }, { "x": 339.1478729248047, "y": 323.42233657836914, "z": -14.367576837539673 }, { "x": 333.3201599121094, "y": 307.4406337738037, "z": -9.617288708686829 }, { "x": 331.2411117553711, "y": 306.9811820983887, "z": -9.669809937477112 }, { "x": 329.23255920410156, "y": 306.0508346557617, "z": -9.582273960113525, "name": "lips" }, { "x": 322.4586486816406, "y": 301.33323669433594, "z": -7.720675468444824 }, { "x": 297.1712112426758, "y": 286.9552803039551, "z": 8.240055441856384 }, { "x": 341.3060760498047, "y": 235.4432201385498, "z": -7.504753470420837 }, { "x": 336.9318389892578, "y": 224.3451976776123, "z": 5.829898118972778 }, { "x": 332.65323638916016, "y": 226.70403957366943, "z": 8.105834126472473 }, { "x": 334.67357635498047, "y": 306.4397621154785, "z": -8.981193900108337, "name": "lips" }, { "x": 297.4601936340332, "y": 306.29210472106934, "z": 15.476365089416504 }, { "x": 342.9119110107422, "y": 222.37077713012695, "z": -2.754466235637665 }, { "x": 335.4629898071289, "y": 332.20250129699707, "z": -11.823196411132812 }, { "x": 353.2412338256836, "y": 240.56339263916016, "z": -27.147831916809082 }, { "x": 346.3080596923828, "y": 236.41446590423584, "z": -18.452589511871338 }, { "x": 352.6475143432617, "y": 234.1420555114746, "z": -19.748122692108154 }, { "x": 337.3209762573242, "y": 253.39937210083008, "z": -16.024924516677856 }, { "x": 358.6122131347656, "y": 344.90861892700195, "z": -18.592647314071655 }, { "x": 358.1117248535156, "y": 334.64990615844727, "z": -17.49552845954895 }, { "x": 346.4450454711914, "y": 335.0321102142334, "z": -16.32838249206543 }, { "x": 319.17640686035156, "y": 320.2833938598633, "z": -3.276764452457428 }, { "x": 325.2540588378906, "y": 276.2369728088379, "z": -6.460157036781311 }, { "x": 326.7214584350586, "y": 327.3939514160156, "z": -7.417217493057251 }, { "x": 310.7190132141113, "y": 277.2265148162842, "z": -3.5452082753181458 }, { "x": 319.78355407714844, "y": 284.8238182067871, "z": -6.4543211460113525 }, { "x": 305.773983001709, "y": 290.83580017089844, "z": 0.06907138042151928 }, { "x": 344.4001770019531, "y": 344.85408782958984, "z": -16.946970224380493 }, { "x": 333.1879425048828, "y": 258.74256134033203, "z": -11.90489649772644 }, { "x": 313.80598068237305, "y": 327.08919525146484, "z": 2.2277912497520447 }, { "x": 322.9637908935547, "y": 334.6819496154785, "z": -3.3643004298210144 }, { "x": 313.4055519104004, "y": 311.2166690826416, "z": -1.1175429821014404 }, { "x": 291.0865783691406, "y": 298.2831001281738, "z": 22.467575073242188 }, { "x": 305.6580924987793, "y": 313.3707904815674, "z": 5.561453700065613 }, { "x": 288.23760986328125, "y": 305.9941864013672, "z": 36.765122413635254 }, { "x": 315.10692596435547, "y": 296.26991271972656, "z": -4.604393839836121 }, { "x": 337.50518798828125, "y": 247.5944423675537, "z": -10.597691535949707 }, { "x": 338.8450622558594, "y": 265.47778129577637, "z": -27.778091430664062 }, { "x": 334.25254821777344, "y": 269.0671920776367, "z": -20.938611030578613 }, { "x": 341.64512634277344, "y": 259.6387195587158, "z": -32.189905643463135 }, { "x": 331.44081115722656, "y": 219.0976095199585, "z": 4.207563698291779 }, { "x": 320.56339263916016, "y": 216.49658203125, "z": 2.930997312068939 }, { "x": 311.21912002563477, "y": 216.57853603363037, "z": 2.9674705862998962 }, { "x": 303.46256256103516, "y": 218.54614734649658, "z": 5.357203483581543 }, { "x": 297.99999237060547, "y": 222.505202293396, "z": 9.325502514839172 }, { "x": 294.93839263916016, "y": 236.39654159545898, "z": 18.534289598464966 }, { "x": 278.87489318847656, "y": 259.7095584869385, "z": 45.68212032318115 }, { "x": 300.3782653808594, "y": 245.38593292236328, "z": 12.278382778167725 }, { "x": 307.06348419189453, "y": 246.36857986450195, "z": 8.164191246032715 }, { "x": 315.5229187011719, "y": 245.3949737548828, "z": 5.503097176551819 }, { "x": 323.71395111083984, "y": 242.75178909301758, "z": 4.6335723996162415 }, { "x": 330.2785873413086, "y": 239.34658527374268, "z": 4.937030673027039 }, { "x": 334.6982192993164, "y": 236.0460376739502, "z": 4.823233783245087 }, { "x": 279.3412208557129, "y": 263.5196113586426, "z": 70.91583728790283, "name": "faceOval" }, { "x": 334.65972900390625, "y": 271.6648578643799, "z": -17.775644063949585 }, { "x": 342.05677032470703, "y": 246.99846267700195, "z": -20.84523916244507 }, { "x": 344.0357971191406, "y": 264.5701503753662, "z": -32.936880588531494 }, { "x": 348.25531005859375, "y": 268.6645030975342, "z": -30.695960521697998 }, { "x": 344.12227630615234, "y": 266.34212493896484, "z": -29.808926582336426 }, { "x": 337.12318420410156, "y": 274.2556858062744, "z": -15.768152475357056 }, { "x": 349.49047088623047, "y": 269.071683883667, "z": -32.51670837402344 }, { "x": 350.1683044433594, "y": 271.4691352844238, "z": -24.93025302886963 }, { "x": 333.9634704589844, "y": 230.56639194488525, "z": 8.89949381351471 }, { "x": 338.2147979736328, "y": 231.4807891845703, "z": 4.6715047955513 }, { "x": 340.4712677001953, "y": 231.74463272094727, "z": -0.34996166825294495 }, { "x": 303.28975677490234, "y": 232.24980354309082, "z": 11.916568279266357, "name": "rightEye" }, { "x": 299.4649124145508, "y": 229.53842639923096, "z": 12.325069904327393 }, { "x": 359.09618377685547, "y": 241.77349090576172, "z": -24.650139808654785 }, { "x": 399.46216583251953, "y": 229.89503860473633, "z": 15.919880867004395, "name": "leftEye" }, { "x": 361.38919830322266, "y": 269.6129894256592, "z": -24.510080814361572 }, { "x": 416.9973373413086, "y": 206.0895538330078, "z": 53.26857566833496, "name": "faceOval" }, { "x": 381.32179260253906, "y": 235.5476474761963, "z": 7.6214683055877686 }, { "x": 387.8068542480469, "y": 236.25958442687988, "z": 8.345099091529846 }, { "x": 393.95751953125, "y": 235.8660364151001, "z": 10.475142002105713 }, { "x": 401.84600830078125, "y": 232.77019500732422, "z": 16.760226488113403 }, { "x": 375.70568084716797, "y": 233.48456382751465, "z": 8.234220147132874 }, { "x": 388.17752838134766, "y": 218.94717693328857, "z": 6.810300946235657 }, { "x": 381.64928436279297, "y": 219.2656660079956, "z": 6.711093783378601 }, { "x": 394.4760513305664, "y": 219.66821193695068, "z": 9.173773527145386 }, { "x": 398.8843536376953, "y": 221.8837022781372, "z": 12.03328251838684 }, { "x": 406.5454864501953, "y": 237.12156772613525, "z": 19.7131085395813 }, { "x": 383.87447357177734, "y": 337.6932907104492, "z": -8.631049990653992 }, { "x": 401.2682342529297, "y": 228.5916566848755, "z": 18.359217643737793, "name": "leftEye" }, { "x": 422.0449447631836, "y": 236.73934936523438, "z": 51.16771221160889 }, { "x": 412.69153594970703, "y": 232.80198097229004, "z": 27.52131938934326 }, { "x": 387.3497772216797, "y": 263.298397064209, "z": -2.8609684109687805 }, { "x": 364.5124053955078, "y": 293.39221000671387, "z": -22.397546768188477, "name": "lips" }, { "x": 363.62987518310547, "y": 302.1291446685791, "z": -19.643079042434692 }, { "x": 373.2334518432617, "y": 295.8647060394287, "z": -18.125789165496826, "name": "lips" }, { "x": 378.83365631103516, "y": 299.5177745819092, "z": -13.153743743896484, "name": "lips" }, { "x": 369.91477966308594, "y": 302.5704002380371, "z": -16.65518283843994 }, { "x": 374.9167251586914, "y": 303.5416603088379, "z": -11.963253021240234 }, { "x": 387.58888244628906, "y": 312.2716999053955, "z": -4.680258631706238 }, { "x": 360.6635284423828, "y": 264.31986808776855, "z": -35.94811677932739 }, { "x": 361.04564666748047, "y": 256.8225860595703, "z": -37.278664112091064 }, { "x": 408.3855438232422, "y": 213.52088928222656, "z": 15.756480693817139, "name": "leftEyebrow" }, { "x": 373.2946014404297, "y": 245.38101196289062, "z": -1.9316278398036957 }, { "x": 376.83860778808594, "y": 264.3721103668213, "z": -18.510947227478027 }, { "x": 376.9546127319336, "y": 261.0010528564453, "z": -15.989909172058105 }, { "x": 406.1498260498047, "y": 263.5030174255371, "z": 7.072908878326416 }, { "x": 360.07205963134766, "y": 248.3631706237793, "z": -32.16656446456909 }, { "x": 393.11119079589844, "y": 205.10473251342773, "z": 3.7786373496055603, "name": "leftEyebrow" }, { "x": 402.12791442871094, "y": 207.89000988006592, "z": 9.383859634399414, "name": "leftEyebrow" }, { "x": 410.8693313598633, "y": 191.6182279586792, "z": 41.27030849456787, "name": "faceOval" }, { "x": 364.9509811401367, "y": 210.40483474731445, "z": -3.758212625980377 }, { "x": 375.94444274902344, "y": 221.1331844329834, "z": 8.368442058563232 }, { "x": 392.1904754638672, "y": 305.0360298156738, "z": -1.752179116010666 }, { "x": 419.50225830078125, "y": 307.25592613220215, "z": 58.96425247192383, "name": "faceOval" }, { "x": 372.0027160644531, "y": 268.7212657928467, "z": -16.631840467453003 }, { "x": 366.1614227294922, "y": 271.6237449645996, "z": -18.219159841537476 }, { "x": 385.00938415527344, "y": 305.3863334655762, "z": -2.567722797393799 }, { "x": 381.99771881103516, "y": 304.9723720550537, "z": -4.575215280056 }, { "x": 405.078125, "y": 203.21216583251953, "z": 13.713973760604858, "name": "leftEyebrow" }, { "x": 377.13207244873047, "y": 268.4710121154785, "z": -15.266278982162476 }, { "x": 380.9713363647461, "y": 205.36980628967285, "z": -0.7250899076461792, "name": "leftEyebrow" }, { "x": 381.7788314819336, "y": 198.9268398284912, "z": -1.184653863310814, "name": "leftEyebrow" }, { "x": 385.5204772949219, "y": 172.1484375, "z": 16.04826807975769, "name": "faceOval" }, { "x": 407.94189453125, "y": 196.76236152648926, "z": 25.723915100097656 }, { "x": 383.03890228271484, "y": 184.5157527923584, "z": 7.393874526023865 }, { "x": 411.61781311035156, "y": 210.79241752624512, "z": 22.315845489501953, "name": "leftEyebrow" }, { "x": 414.30870056152344, "y": 208.4643030166626, "z": 37.021894454956055 }, { "x": 364.28722381591797, "y": 298.35777282714844, "z": -21.86065673828125 }, { "x": 371.3682556152344, "y": 299.78848457336426, "z": -17.834001779556274 }, { "x": 376.88201904296875, "y": 301.6696071624756, "z": -13.153743743896484 }, { "x": 370.2193832397461, "y": 270.49095153808594, "z": -15.569736957550049 }, { "x": 383.5081100463867, "y": 305.2726364135742, "z": -3.673594295978546 }, { "x": 380.73760986328125, "y": 305.96869468688965, "z": -8.660228252410889 }, { "x": 381.2334442138672, "y": 304.63574409484863, "z": -4.820316135883331, "name": "lips" }, { "x": 368.1698989868164, "y": 264.8884963989258, "z": -25.653886795043945 }, { "x": 373.5087203979492, "y": 303.4233856201172, "z": -10.95950722694397, "name": "lips" }, { "x": 368.4544372558594, "y": 303.29601287841797, "z": -14.169161319732666, "name": "lips" }, { "x": 362.76554107666016, "y": 303.5735607147217, "z": -16.911956071853638, "name": "lips" }, { "x": 366.60980224609375, "y": 324.8870658874512, "z": -15.616422891616821 }, { "x": 365.7067108154297, "y": 315.95678329467773, "z": -20.903596878051758, "name": "lips" }, { "x": 365.0083923339844, "y": 311.2232208251953, "z": -21.066999435424805 }, { "x": 364.1508102416992, "y": 307.0583438873291, "z": -18.907777070999146 }, { "x": 363.37512969970703, "y": 304.5721435546875, "z": -17.42550015449524, "name": "lips" }, { "x": 374.580078125, "y": 304.3059539794922, "z": -11.40302300453186, "name": "lips" }, { "x": 375.55362701416016, "y": 305.0998020172119, "z": -12.861957550048828 }, { "x": 377.2437286376953, "y": 307.1674346923828, "z": -14.215847253799438 }, { "x": 378.68587493896484, "y": 309.9015712738037, "z": -13.223772048950195, "name": "lips" }, { "x": 383.8992691040039, "y": 290.29629707336426, "z": -9.97326910495758 }, { "x": 423.3871841430664, "y": 271.91688537597656, "z": 74.37058925628662, "name": "faceOval" }, { "x": 377.68043518066406, "y": 304.62209701538086, "z": -7.603961229324341, "name": "lips" }, { "x": 379.00428771972656, "y": 304.9314594268799, "z": -8.57852816581726 }, { "x": 364.00279998779297, "y": 275.2813911437988, "z": -19.25792098045349 }, { "x": 374.68231201171875, "y": 273.82555961608887, "z": -11.28047227859497 }, { "x": 365.0354766845703, "y": 273.4548568725586, "z": -18.791062831878662 }, { "x": 380.61901092529297, "y": 249.8848056793213, "z": 0.15501167625188828 }, { "x": 391.14158630371094, "y": 254.7934627532959, "z": 2.0906515419483185 }, { "x": 378.1761169433594, "y": 264.9612236022949, "z": -12.605184316635132 }, { "x": 400.9540557861328, "y": 179.99592304229736, "z": 27.82477855682373, "name": "faceOval" }, { "x": 398.0038833618164, "y": 188.50656509399414, "z": 16.094952821731567 }, { "x": 394.8717498779297, "y": 199.0359592437744, "z": 6.226727366447449, "name": "leftEyebrow" }, { "x": 382.10926055908203, "y": 316.83926582336426, "z": -8.946179747581482 }, { "x": 366.51588439941406, "y": 200.32583713531494, "z": -5.24632453918457, "name": "leftEyebrow" }, { "x": 367.4893569946289, "y": 183.87210845947266, "z": 1.9039081037044525 }, { "x": 368.6243438720703, "y": 168.8127565383911, "z": 8.736093044281006, "name": "faceOval" }, { "x": 398.96175384521484, "y": 234.9675178527832, "z": 13.713973760604858 }, { "x": 412.9645538330078, "y": 242.23042488098145, "z": 23.272905349731445 }, { "x": 372.05257415771484, "y": 231.41919136047363, "z": 9.226294755935669 }, { "x": 406.0722351074219, "y": 223.58965873718262, "z": 18.370890617370605 }, { "x": 368.27442169189453, "y": 240.2039337158203, "z": -4.166713654994965 }, { "x": 372.3575210571289, "y": 260.66442489624023, "z": -24.976940155029297 }, { "x": 419.2244338989258, "y": 247.9079246520996, "z": 30.299127101898193 }, { "x": 409.43885803222656, "y": 246.60913467407227, "z": 16.398411989212036 }, { "x": 401.69139862060547, "y": 248.76328468322754, "z": 9.395531415939331 }, { "x": 389.7608184814453, "y": 247.56915092468262, "z": 5.841569304466248 }, { "x": 380.5461883544922, "y": 244.55984115600586, "z": 4.263003468513489 }, { "x": 373.25817108154297, "y": 240.80214500427246, "z": 2.5356262922286987 }, { "x": 358.77086639404297, "y": 229.35615062713623, "z": -10.387605428695679 }, { "x": 419.5793914794922, "y": 262.8478717803955, "z": 26.5175724029541 }, { "x": 410.8808898925781, "y": 222.51372814178467, "z": 22.199130058288574 }, { "x": 358.45714569091797, "y": 268.91467094421387, "z": -33.17030906677246 }, { "x": 373.4129333496094, "y": 251.6385841369629, "z": -5.771540403366089 }, { "x": 422.5408172607422, "y": 239.23919677734375, "z": 74.04378890991211, "name": "faceOval" }, { "x": 367.8171920776367, "y": 236.58040523529053, "z": 1.820748895406723 }, { "x": 378.51959228515625, "y": 266.2532329559326, "z": -5.74819803237915 }, { "x": 403.3472442626953, "y": 229.05112266540527, "z": 19.689764976501465 }, { "x": 372.34840393066406, "y": 256.6451168060303, "z": -21.872329711914062 }, { "x": 422.54566192626953, "y": 289.1587829589844, "z": 68.67491245269775, "name": "faceOval" }, { "x": 371.9297409057617, "y": 228.90116214752197, "z": 11.432201862335205, "name": "leftEye" }, { "x": 366.21360778808594, "y": 251.6158962249756, "z": -28.19826364517212 }, { "x": 409.1571807861328, "y": 321.3156223297119, "z": 20.2266526222229 }, { "x": 408.52943420410156, "y": 331.44238471984863, "z": 31.09278917312622, "name": "faceOval" }, { "x": 424.2788314819336, "y": 267.1992301940918, "z": 50.467424392700195 }, { "x": 415.60352325439453, "y": 311.6528606414795, "z": 30.579242706298828 }, { "x": 418.12793731689453, "y": 221.59927368164062, "z": 46.26569747924805 }, { "x": 385.68286895751953, "y": 346.0184955596924, "z": -5.70151150226593 }, { "x": 357.82936096191406, "y": 271.3758373260498, "z": -24.836881160736084 }, { "x": 379.588623046875, "y": 257.5071716308594, "z": -3.755294680595398 }, { "x": 417.4592590332031, "y": 234.71948146820068, "z": 34.5475435256958 }, { "x": 393.4684371948242, "y": 231.58967971801758, "z": 11.408859491348267, "name": "leftEye" }, { "x": 387.8864288330078, "y": 232.14245796203613, "z": 9.51808214187622, "name": "leftEye" }, { "x": 382.4981689453125, "y": 307.5654888153076, "z": -7.522260546684265, "name": "lips" }, { "x": 419.00169372558594, "y": 277.8332805633545, "z": 26.424202919006348 }, { "x": 373.62953186035156, "y": 357.6375102996826, "z": -5.75986921787262, "name": "faceOval" }, { "x": 392.8708267211914, "y": 347.72446632385254, "z": 10.154176950454712, "name": "faceOval" }, { "x": 400.3953552246094, "y": 341.0005187988281, "z": 19.39797878265381, "name": "faceOval" }, { "x": 382.25440979003906, "y": 231.66935920715332, "z": 8.998700976371765, "name": "leftEye" }, { "x": 377.14550018310547, "y": 230.4228687286377, "z": 9.804032444953918, "name": "leftEye" }, { "x": 373.8358688354492, "y": 229.64950561523438, "z": 11.292144060134888, "name": "leftEye" }, { "x": 414.5794677734375, "y": 221.67891025543213, "z": 29.412097930908203 }, { "x": 377.00672149658203, "y": 225.66201210021973, "z": 9.360517263412476, "name": "leftEye" }, { "x": 382.29530334472656, "y": 224.8431158065796, "z": 8.32175612449646, "name": "leftEye" }, { "x": 387.5133514404297, "y": 224.49507236480713, "z": 8.917000889778137, "name": "leftEye" }, { "x": 393.15906524658203, "y": 225.24795055389404, "z": 10.737749338150024, "name": "leftEye" }, { "x": 397.05554962158203, "y": 226.55359268188477, "z": 13.002015352249146, "name": "leftEye" }, { "x": 420.5299377441406, "y": 221.014666557312, "z": 65.40690422058105, "name": "faceOval" }, { "x": 397.06920623779297, "y": 230.6661558151245, "z": 13.807345628738403, "name": "leftEye" }, { "x": 377.94647216796875, "y": 285.1647090911865, "z": -13.305472135543823 }, { "x": 372.1118927001953, "y": 267.1267318725586, "z": -18.83774757385254 }, { "x": 364.9968719482422, "y": 282.24411964416504, "z": -19.818150997161865 }, { "x": 401.973876953125, "y": 331.20131492614746, "z": 11.566424369812012 }, { "x": 394.3083190917969, "y": 338.86693954467773, "z": 3.142542541027069 }, { "x": 373.9820861816406, "y": 351.4504623413086, "z": -13.50388765335083 }, { "x": 414.3888854980469, "y": 321.24735832214355, "z": 45.51872253417969, "name": "faceOval" }, { "x": 373.44234466552734, "y": 227.33163356781006, "z": 10.626870393753052, "name": "leftEye" }, { "x": 364.0731430053711, "y": 240.31539916992188, "z": -13.807345628738403 }, { "x": 384.2658233642578, "y": 353.3793067932129, "z": 0.7385850697755814, "name": "faceOval" }, { "x": 423.20526123046875, "y": 283.5176181793213, "z": 47.152724266052246 }, { "x": 369.42798614501953, "y": 304.0898895263672, "z": -14.647691249847412, "name": "lips" }, { "x": 370.63812255859375, "y": 305.90051651000977, "z": -16.211668252944946 }, { "x": 371.91192626953125, "y": 309.0167713165283, "z": -17.84567356109619 }, { "x": 373.0583953857422, "y": 313.3545398712158, "z": -17.378815412521362, "name": "lips" }, { "x": 375.39905548095703, "y": 321.09289169311523, "z": -13.118728399276733 }, { "x": 379.2567825317383, "y": 304.3582534790039, "z": -7.924926280975342 }, { "x": 381.18797302246094, "y": 303.7031364440918, "z": -7.843226194381714 }, { "x": 383.0918502807617, "y": 302.4884605407715, "z": -7.6506465673446655, "name": "lips" }, { "x": 389.09461975097656, "y": 297.1475315093994, "z": -5.5497825145721436 }, { "x": 411.6408920288086, "y": 280.24898529052734, "z": 12.02161192893982 }, { "x": 363.3110809326172, "y": 234.27620887756348, "z": -6.775286793708801 }, { "x": 366.0474395751953, "y": 223.29872131347656, "z": 6.827808618545532 }, { "x": 370.34427642822266, "y": 225.1457118988037, "z": 9.558931589126587 }, { "x": 377.5371551513672, "y": 303.60079765319824, "z": -7.358860373497009, "name": "lips" }, { "x": 412.9557800292969, "y": 299.53579902648926, "z": 19.39797878265381 }, { "x": 360.0810241699219, "y": 221.72012329101562, "z": -2.153385728597641 }, { "x": 379.82784271240234, "y": 329.47723388671875, "z": -10.48097848892212 }, { "x": 359.08477783203125, "y": 235.7911491394043, "z": -18.079102039337158 }, { "x": 369.6688461303711, "y": 251.5407943725586, "z": -14.962821006774902 }, { "x": 369.5555114746094, "y": 333.5307312011719, "z": -15.67478060722351 }, { "x": 394.0193176269531, "y": 315.6973171234131, "z": -0.9920747578144073 }, { "x": 383.78997802734375, "y": 272.7268695831299, "z": -4.689012169837952 }, { "x": 387.67765045166016, "y": 323.6722755432129, "z": -5.640236139297485 }, { "x": 397.8769302368164, "y": 272.1331214904785, "z": -0.9395531564950943 }, { "x": 389.87476348876953, "y": 280.5630111694336, "z": -4.29218202829361 }, { "x": 403.83888244628906, "y": 285.1167869567871, "z": 3.0229100584983826 }, { "x": 372.5467300415039, "y": 343.1070327758789, "z": -16.153310537338257 }, { "x": 374.1112518310547, "y": 256.3721466064453, "z": -10.574349164962769 }, { "x": 399.73785400390625, "y": 321.77515983581543, "z": 4.849494695663452 }, { "x": 392.03365325927734, "y": 330.56447982788086, "z": -1.3407598435878754 }, { "x": 398.59134674072266, "y": 305.93902587890625, "z": 1.517290621995926 }, { "x": 417.95997619628906, "y": 290.9716987609863, "z": 26.89105987548828 }, { "x": 406.04541778564453, "y": 307.35154151916504, "z": 8.666064143180847 }, { "x": 420.75328826904297, "y": 298.40752601623535, "z": 41.78385257720947 }, { "x": 395.4522705078125, "y": 291.4153575897217, "z": -2.1752697229385376 }, { "x": 368.6452102661133, "y": 245.8882999420166, "z": -9.453888535499573 }, { "x": 370.34900665283203, "y": 263.56690406799316, "z": -26.75100326538086 }, { "x": 374.98477935791016, "y": 266.6126346588135, "z": -19.77146625518799 }, { "x": 366.99840545654297, "y": 258.12140464782715, "z": -31.372904777526855 }, { "x": 371.00616455078125, "y": 217.63479709625244, "z": 5.60522198677063 }, { "x": 381.30577087402344, "y": 214.14087295532227, "z": 4.983716309070587 }, { "x": 390.1496124267578, "y": 213.38221549987793, "z": 5.593550801277161 }, { "x": 397.7696990966797, "y": 214.3659782409668, "z": 8.57852816581726 }, { "x": 403.1652069091797, "y": 217.65509605407715, "z": 13.013685941696167 }, { "x": 407.3551940917969, "y": 230.72525024414062, "z": 22.444231510162354 }, { "x": 424.0876770019531, "y": 251.7839241027832, "z": 51.16771221160889 }, { "x": 403.50196838378906, "y": 239.88757610321045, "z": 15.803166627883911 }, { "x": 397.31719970703125, "y": 241.49806022644043, "z": 11.233787536621094 }, { "x": 388.99425506591797, "y": 241.4366912841797, "z": 7.948269248008728 }, { "x": 380.7804489135742, "y": 239.78078842163086, "z": 6.600214838981628 }, { "x": 374.01336669921875, "y": 237.11946487426758, "z": 6.349278092384338 }, { "x": 369.39125061035156, "y": 234.35351371765137, "z": 5.987462401390076 }, { "x": 422.9730987548828, "y": 255.76455116271973, "z": 76.61150932312012, "name": "faceOval" }, { "x": 374.73915100097656, "y": 269.24214363098145, "z": -16.608498096466064 }, { "x": 364.61681365966797, "y": 245.71088790893555, "z": -20.02823829650879 }, { "x": 365.3834533691406, "y": 263.34174156188965, "z": -32.32996463775635 }, { "x": 361.58252716064453, "y": 267.8273677825928, "z": -30.345816612243652 }, { "x": 365.37208557128906, "y": 265.0249671936035, "z": -29.178667068481445 }, { "x": 372.72605895996094, "y": 272.05135345458984, "z": -14.834434986114502 }, { "x": 360.48614501953125, "y": 268.34827423095703, "z": -32.189905643463135 }, { "x": 359.9516296386719, "y": 270.8049201965332, "z": -24.650139808654785 }, { "x": 369.5049285888672, "y": 229.01945114135742, "z": 10.107489824295044 }, { "x": 365.5447769165039, "y": 230.24096488952637, "z": 5.593550801277161 }, { "x": 363.50669860839844, "y": 230.6208372116089, "z": 0.43622106313705444 }, { "x": 399.3529510498047, "y": 227.65677452087402, "z": 15.35965085029602, "name": "leftEye" }, { "x": 402.5693130493164, "y": 224.60190296173096, "z": 15.931552648544312 }], "box": { "xMin": 277.8318977355957, "yMin": 168.7741756439209, "xMax": 424.2788314819336, "yMax": 359.8348903656006, "width": 146.4469337463379, "height": 191.0607147216797 } }, // Tasks-vision: https://developers.google.com/mediapipe/solutions/vision/face_landmarker/web_js // prettier-ignore SAMPLE_FACELANDMARKER_RESULT: { "faceLandmarks": [[{ "x": 0.5760777592658997, "y": 0.8639070391654968, "z": -0.030997956171631813 }, { "x": 0.572094738483429, "y": 0.7886289358139038, "z": -0.07189624011516571 }, { "x": 0.5723551511764526, "y": 0.8075382709503174, "z": -0.03578168898820877 }, { "x": 0.5548420548439026, "y": 0.7188365459442139, "z": -0.057787876576185226 }, { "x": 0.5706077814102173, "y": 0.7674974799156189, "z": -0.07740399986505508 }, { "x": 0.5681378245353699, "y": 0.7387768030166626, "z": -0.07356284558773041 }, { "x": 0.5621535181999207, "y": 0.6681165099143982, "z": -0.04189874976873398 }, { "x": 0.46613582968711853, "y": 0.6679812073707581, "z": 0.011289681307971478 }, { "x": 0.5579932928085327, "y": 0.6174106597900391, "z": -0.03502821549773216 }, { "x": 0.5563451647758484, "y": 0.5905600190162659, "z": -0.03928658738732338 }, { "x": 0.5487832427024841, "y": 0.4900572597980499, "z": -0.029898937791585922 }, { "x": 0.5765544176101685, "y": 0.8692144751548767, "z": -0.02831427752971649 }, { "x": 0.5771114230155945, "y": 0.873644232749939, "z": -0.02345779910683632 }, { "x": 0.5771905779838562, "y": 0.877016007900238, "z": -0.016658689826726913 }, { "x": 0.5778058767318726, "y": 0.8770116567611694, "z": -0.014505492523312569 }, { "x": 0.5783766508102417, "y": 0.8835000991821289, "z": -0.015996402129530907 }, { "x": 0.5792440176010132, "y": 0.8913810849189758, "z": -0.01924579218029976 }, { "x": 0.5796768069267273, "y": 0.8996334671974182, "z": -0.018261712044477463 }, { "x": 0.5817288160324097, "y": 0.9255813956260681, "z": -0.007126849144697189 }, { "x": 0.5726592540740967, "y": 0.7992473244667053, "z": -0.0643521398305893 }, { "x": 0.5579419136047363, "y": 0.7996989488601685, "z": -0.04566684365272522 }, { "x": 0.4216199815273285, "y": 0.5958762764930725, "z": 0.06776496022939682 }, { "x": 0.5052269697189331, "y": 0.6796539425849915, "z": -0.0010737782577052712 }, { "x": 0.49243026971817017, "y": 0.6838865876197815, "z": -5227324436418712e-19 }, { "x": 0.4796970784664154, "y": 0.6856290102005005, "z": 0.002684245817363262 }, { "x": 0.4618356227874756, "y": 0.6764569878578186, "z": 0.013439622707664967 }, { "x": 0.5160380601882935, "y": 0.6737282276153564, "z": -17607348127057776e-21 }, { "x": 0.48070961236953735, "y": 0.6255870461463928, "z": -0.008339674212038517 }, { "x": 0.49719780683517456, "y": 0.6256808042526245, "z": -0.008027955889701843 }, { "x": 0.46674346923828125, "y": 0.6317623853683472, "z": -0.004460199736058712 }, { "x": 0.4582492709159851, "y": 0.641118049621582, "z": 0.0011905613355338573 }, { "x": 0.45408669114112854, "y": 0.6911458969116211, "z": 0.020514748990535736 }, { "x": 0.535312294960022, "y": 0.9619986414909363, "z": 0.012499462813138962 }, { "x": 0.4608460068702698, "y": 0.6628725528717041, "z": 0.01517564244568348 }, { "x": 0.4206731915473938, "y": 0.6828458309173584, "z": 0.07848648726940155 }, { "x": 0.4390624463558197, "y": 0.6796106696128845, "z": 0.03283142298460007 }, { "x": 0.5029968619346619, "y": 0.7701570391654968, "z": -0.009734481573104858 }, { "x": 0.5595027208328247, "y": 0.8607323169708252, "z": -0.030043255537748337 }, { "x": 0.5621269941329956, "y": 0.8738374710083008, "z": -0.021709579974412918 }, { "x": 0.5451499819755554, "y": 0.865527331829071, "z": -0.022014077752828598 }, { "x": 0.5351184010505676, "y": 0.8705098032951355, "z": -0.011602800339460373 }, { "x": 0.5495014190673828, "y": 0.8744956254959106, "z": -0.016490943729877472 }, { "x": 0.5395170450210571, "y": 0.8759440779685974, "z": -0.007333362940698862 }, { "x": 0.5183624029159546, "y": 0.8959754705429077, "z": 0.010520773939788342 }, { "x": 0.5604349374771118, "y": 0.7895449995994568, "z": -0.07082037627696991 }, { "x": 0.557381272315979, "y": 0.7687489986419678, "z": -0.07590588927268982 }, { "x": 0.4432901442050934, "y": 0.6308897733688354, "z": 0.0027153254486620426 }, { "x": 0.5258325338363647, "y": 0.7151225805282593, "z": -0.014676518738269806 }, { "x": 0.5271827578544617, "y": 0.7833116054534912, "z": -0.037643320858478546 }, { "x": 0.5257382988929749, "y": 0.7717816233634949, "z": -0.03401920944452286 }, { "x": 0.46516409516334534, "y": 0.7705106735229492, "z": 0.0065747760236263275 }, { "x": 0.5558893084526062, "y": 0.7420997619628906, "z": -0.0694495290517807 }, { "x": 0.4720408320426941, "y": 0.6066038608551025, "z": -0.021204356104135513 }, { "x": 0.45432573556900024, "y": 0.6158540844917297, "z": -0.011054684408009052 }, { "x": 0.4305151402950287, "y": 0.5608053803443909, "z": 0.0396830290555954 }, { "x": 0.5310865640640259, "y": 0.6157484650611877, "z": -0.03081176057457924 }, { "x": 0.5114666223526001, "y": 0.6329749226570129, "z": -0.00335998204536736 }, { "x": 0.506435751914978, "y": 0.8786543607711792, "z": 0.012980876490473747 }, { "x": 0.4480472207069397, "y": 0.8640613555908203, "z": 0.12569651007652283 }, { "x": 0.5372058153152466, "y": 0.7942581176757812, "z": -0.03168361634016037 }, { "x": 0.5488379597663879, "y": 0.8001630306243896, "z": -0.03280917927622795 }, { "x": 0.5213388204574585, "y": 0.8794381618499756, "z": 0.011892606504261494 }, { "x": 0.5242055654525757, "y": 0.8789222240447998, "z": 0.008370225317776203 }, { "x": 0.4477175176143646, "y": 0.6039950251579285, "z": -0.0050799972377717495 }, { "x": 0.526964008808136, "y": 0.7916748523712158, "z": -0.02968614175915718 }, { "x": 0.4971255660057068, "y": 0.6050706505775452, "z": -0.028175678104162216 }, { "x": 0.4938119053840637, "y": 0.5882453918457031, "z": -0.03210941329598427 }, { "x": 0.4757143557071686, "y": 0.5094879865646362, "z": -0.01300730835646391 }, { "x": 0.43947282433509827, "y": 0.5816648006439209, "z": 0.01415177434682846 }, { "x": 0.485664039850235, "y": 0.5477864146232605, "z": -0.023685332387685776 }, { "x": 0.43635931611061096, "y": 0.6226438283920288, "z": 0.013606148771941662 }, { "x": 0.42910251021385193, "y": 0.6102726459503174, "z": 0.03926564007997513 }, { "x": 0.5605402588844299, "y": 0.8680099248886108, "z": -0.027318159118294716 }, { "x": 0.5474816560745239, "y": 0.8702861070632935, "z": -0.019686367362737656 }, { "x": 0.5373021364212036, "y": 0.8728838562965393, "z": -0.010484928265213966 }, { "x": 0.540735125541687, "y": 0.7979167103767395, "z": -0.029073253273963928 }, { "x": 0.5228585004806519, "y": 0.87913578748703, "z": 0.009915109723806381 }, { "x": 0.530497670173645, "y": 0.8815253973007202, "z": 0.0020524784922599792 }, { "x": 0.5259912610054016, "y": 0.8790552616119385, "z": 0.007895970717072487 }, { "x": 0.5433906316757202, "y": 0.7882310748100281, "z": -0.05121905356645584 }, { "x": 0.541388213634491, "y": 0.8777219653129578, "z": -0.00466804439201951 }, { "x": 0.5515822172164917, "y": 0.8767023086547852, "z": -0.010475946590304375 }, { "x": 0.5637003779411316, "y": 0.877059817314148, "z": -0.015273625031113625 }, { "x": 0.5640299320220947, "y": 0.9263423085212708, "z": -0.00658724969252944 }, { "x": 0.5642300248146057, "y": 0.8993074893951416, "z": -0.017653480172157288 }, { "x": 0.5637336373329163, "y": 0.8910360932350159, "z": -0.01852807030081749 }, { "x": 0.5637134313583374, "y": 0.8837276697158813, "z": -0.01482592523097992 }, { "x": 0.564205527305603, "y": 0.8768964409828186, "z": -0.01331155002117157 }, { "x": 0.5419867634773254, "y": 0.8778373599052429, "z": -0.0037720394320786 }, { "x": 0.5404468774795532, "y": 0.880696177482605, "z": -0.005610354244709015 }, { "x": 0.5392338633537292, "y": 0.8845721483230591, "z": -0.007352025713771582 }, { "x": 0.538469672203064, "y": 0.8891173601150513, "z": -0.005154991988092661 }, { "x": 0.5189250111579895, "y": 0.8452741503715515, "z": -0.009755070321261883 }, { "x": 0.4258975088596344, "y": 0.7662280797958374, "z": 0.1387351155281067 }, { "x": 0.5725725293159485, "y": 0.8041572570800781, "z": -0.04583907872438431 }, { "x": 0.5342061519622803, "y": 0.8785833120346069, "z": 0.002659974154084921 }, { "x": 0.5324031114578247, "y": 0.8804071545600891, "z": 0.0017832003068178892 }, { "x": 0.5538818836212158, "y": 0.8078407645225525, "z": -0.03254539892077446 }, { "x": 0.5325431823730469, "y": 0.8026832938194275, "z": -0.019140373915433884 }, { "x": 0.5514076948165894, "y": 0.8043903112411499, "z": -0.03313535451889038 }, { "x": 0.5131856203079224, "y": 0.7284771800041199, "z": -0.009399853646755219 }, { "x": 0.49331504106521606, "y": 0.7443980574607849, "z": -0.005225230939686298 }, { "x": 0.5239617824554443, "y": 0.7807451486587524, "z": -0.025881027802824974 }, { "x": 0.4473606050014496, "y": 0.5315827131271362, "z": 0.011164786294102669 }, { "x": 0.45718759298324585, "y": 0.5604941248893738, "z": -0.005943301599472761 }, { "x": 0.4670005738735199, "y": 0.5909327268600464, "z": -0.019681761041283607 }, { "x": 0.5311570167541504, "y": 0.9076261520385742, "z": 0.00389476353302598 }, { "x": 0.5249923467636108, "y": 0.5893563628196716, "z": -0.037981919944286346 }, { "x": 0.5166932344436646, "y": 0.5429551005363464, "z": -0.03319704160094261 }, { "x": 0.5085030198097229, "y": 0.49676206707954407, "z": -0.02691275253891945 }, { "x": 0.4687720239162445, "y": 0.6834565997123718, "z": 0.008113506250083447 }, { "x": 0.4426414966583252, "y": 0.7069531679153442, "z": 0.028577271848917007 }, { "x": 0.5230373740196228, "y": 0.6675713658332825, "z": 0.001773772411979735 }, { "x": 0.4481240212917328, "y": 0.6527872085571289, "z": 0.012414850294589996 }, { "x": 0.5339856743812561, "y": 0.7012367844581604, "z": -0.020220188423991203 }, { "x": 0.5347223281860352, "y": 0.7761190533638, "z": -0.05141595005989075 }, { "x": 0.4315067231655121, "y": 0.7211957573890686, "z": 0.04381405934691429 }, { "x": 0.45203351974487305, "y": 0.7206180095672607, "z": 0.017288070172071457 }, { "x": 0.46892452239990234, "y": 0.7265436053276062, "z": 0.005602988880127668 }, { "x": 0.49314674735069275, "y": 0.7202282547950745, "z": -6408205372281373e-19 }, { "x": 0.5104925632476807, "y": 0.7091827392578125, "z": -0.00362918758764863 }, { "x": 0.5232142210006714, "y": 0.698553740978241, "z": -0.00787867046892643 }, { "x": 0.5497883558273315, "y": 0.6743605136871338, "z": -0.036349106580019 }, { "x": 0.43658503890037537, "y": 0.7627100348472595, "z": 0.042555369436740875 }, { "x": 0.4397648870944977, "y": 0.6528646349906921, "z": 0.017956094816327095 }, { "x": 0.5653332471847534, "y": 0.7992802858352661, "z": -0.06365057826042175 }, { "x": 0.5285563468933105, "y": 0.736810564994812, "z": -0.018836988136172295 }, { "x": 0.4180678725242615, "y": 0.6792560815811157, "z": 0.12284679710865021 }, { "x": 0.5328429937362671, "y": 0.6865872144699097, "z": -0.010484723374247551 }, { "x": 0.5230283141136169, "y": 0.7809416055679321, "z": -0.011922398582100868 }, { "x": 0.4551771283149719, "y": 0.6650775074958801, "z": 0.01774493046104908 }, { "x": 0.5337203741073608, "y": 0.7618928551673889, "z": -0.04697106033563614 }, { "x": 0.43463975191116333, "y": 0.8133478164672852, "z": 0.1354849934577942 }, { "x": 0.5225707292556763, "y": 0.6605283617973328, "z": 0.004980515688657761 }, { "x": 0.5441933870315552, "y": 0.7497199773788452, "z": -0.06091512367129326 }, { "x": 0.4774007797241211, "y": 0.9159183502197266, "z": 0.059622734785079956 }, { "x": 0.48068761825561523, "y": 0.9364941716194153, "z": 0.08404944837093353 }, { "x": 0.4268292486667633, "y": 0.7657528519630432, "z": 0.09051097184419632 }, { "x": 0.46051913499832153, "y": 0.8880485892295837, "z": 0.0738474428653717 }, { "x": 0.4243420660495758, "y": 0.6434382200241089, "z": 0.06230505183339119 }, { "x": 0.5342157483100891, "y": 0.9835634231567383, "z": 0.021662971004843712 }, { "x": 0.5668109655380249, "y": 0.8042187094688416, "z": -0.044937074184417725 }, { "x": 0.5176341533660889, "y": 0.7530587315559387, "z": -0.012967454269528389 }, { "x": 0.430206298828125, "y": 0.6835605502128601, "z": 0.04612284153699875 }, { "x": 0.4794231951236725, "y": 0.6732114553451538, "z": 0.003970044665038586 }, { "x": 0.49073347449302673, "y": 0.6722435355186462, "z": 8692514384165406e-19 }, { "x": 0.5294116139411926, "y": 0.884677529335022, "z": 0.004413890186697245 }, { "x": 0.4430122375488281, "y": 0.80235356092453, "z": 0.04987282305955887 }, { "x": 0.5603825449943542, "y": 1.0092442035675049, "z": 0.026417359709739685 }, { "x": 0.5186598300933838, "y": 0.9828659892082214, "z": 0.0513598807156086 }, { "x": 0.5010536909103394, "y": 0.9640932679176331, "z": 0.06591596454381943 }, { "x": 0.5524769425392151, "y": 0.539441704750061, "z": -0.035816047340631485 }, { "x": 0.5879997611045837, "y": 1.0091472864151, "z": 0.02285068854689598 }, { "x": 0.5016193985939026, "y": 0.6684437990188599, "z": 28415941051207483e-20 }, { "x": 0.511952817440033, "y": 0.6642197370529175, "z": 0.0021144719794392586 }, { "x": 0.5194343328475952, "y": 0.6623469591140747, "z": 0.004674181342124939 }, { "x": 0.4321230351924896, "y": 0.6496355533599854, "z": 0.03124697133898735 }, { "x": 0.508686363697052, "y": 0.6479565501213074, "z": -44765998609364033e-20 }, { "x": 0.4963986277580261, "y": 0.6431032419204712, "z": -0.0032507688738405704 }, { "x": 0.4845542013645172, "y": 0.6430778503417969, "z": -0.002903624437749386 }, { "x": 0.4733612537384033, "y": 0.647506833076477, "z": 23347247042693198e-20 }, { "x": 0.4668654501438141, "y": 0.653346598148346, "z": 0.004762572236359119 }, { "x": 0.41815051436424255, "y": 0.633708119392395, "z": 0.09809435904026031 }, { "x": 0.47159942984580994, "y": 0.6711485385894775, "z": 0.007849935442209244 }, { "x": 0.5734396576881409, "y": 0.8256140351295471, "z": -0.03155219927430153 }, { "x": 0.5306524038314819, "y": 0.8337990641593933, "z": -0.018351426348090172 }, { "x": 0.5371729135513306, "y": 0.7910830974578857, "z": -0.037286680191755295 }, { "x": 0.5549534559249878, "y": 0.8275275826454163, "z": -0.030664825811982155 }, { "x": 0.5597432255744934, "y": 0.6418541669845581, "z": -0.03318847343325615 }, { "x": 0.4958484172821045, "y": 0.9429569244384766, "z": 0.048340678215026855 }, { "x": 0.5140507817268372, "y": 0.9634028077125549, "z": 0.03589847311377525 }, { "x": 0.5587693452835083, "y": 0.9951097369194031, "z": 0.00908728688955307 }, { "x": 0.46411189436912537, "y": 0.9051855206489563, "z": 0.10601935535669327 }, { "x": 0.5181609392166138, "y": 0.6554316878318787, "z": 0.002546071307733655 }, { "x": 0.5436590909957886, "y": 0.7085841298103333, "z": -0.03844436630606651 }, { "x": 0.5872187614440918, "y": 0.9960382580757141, "z": 0.0063423276878893375 }, { "x": 0.5379653573036194, "y": 0.9989125728607178, "z": 0.03636329993605614 }, { "x": 0.4350326955318451, "y": 0.8088565468788147, "z": 0.09147704392671585 }, { "x": 0.5523084998130798, "y": 0.8773422837257385, "z": -0.009068487212061882 }, { "x": 0.5510149598121643, "y": 0.8816931843757629, "z": -0.011043853126466274 }, { "x": 0.5503793954849243, "y": 0.88776695728302, "z": -0.01348799467086792 }, { "x": 0.5501549243927002, "y": 0.8954370617866516, "z": -0.012142189778387547 }, { "x": 0.546072781085968, "y": 0.9192524552345276, "z": -0.003157563041895628 }, { "x": 0.5314661860466003, "y": 0.8771666884422302, "z": 5075141089037061e-19 }, { "x": 0.5293324589729309, "y": 0.8762547969818115, "z": 39177737198770046e-20 }, { "x": 0.5275698900222778, "y": 0.8750609755516052, "z": 47732755774632096e-21 }, { "x": 0.5104271173477173, "y": 0.8607332110404968, "z": 0.0012934643309563398 }, { "x": 0.45938700437545776, "y": 0.8134918212890625, "z": 0.023569690063595772 }, { "x": 0.5418947339057922, "y": 0.6864100694656372, "z": -0.027333909645676613 }, { "x": 0.531914234161377, "y": 0.6456130743026733, "z": -0.005434140563011169 }, { "x": 0.523697018623352, "y": 0.647885262966156, "z": -2466466394253075e-19 }, { "x": 0.5338191390037537, "y": 0.8783687353134155, "z": 0.002268768846988678 }, { "x": 0.46226605772972107, "y": 0.8610277771949768, "z": 0.04718952998518944 }, { "x": 0.5434442758560181, "y": 0.6456181406974792, "z": -0.02327350154519081 }, { "x": 0.5399754643440247, "y": 0.940219521522522, "z": 0.005075343884527683 }, { "x": 0.5661457777023315, "y": 0.71457839012146, "z": -0.06242101639509201 }, { "x": 0.5523148775100708, "y": 0.6974870562553406, "z": -0.04863070324063301 }, { "x": 0.5639959573745728, "y": 0.6923378109931946, "z": -0.05180761218070984 }, { "x": 0.5367592573165894, "y": 0.7423217296600342, "z": -0.03623027727007866 }, { "x": 0.5853689908981323, "y": 0.9752064943313599, "z": -0.002361974213272333 }, { "x": 0.5835235118865967, "y": 0.9493685960769653, "z": -0.003941743168979883 }, { "x": 0.5615018606185913, "y": 0.949194610118866, "z": -0.0015953965485095978 }, { "x": 0.5068561434745789, "y": 0.9048219323158264, "z": 0.01862684078514576 }, { "x": 0.5134067535400391, "y": 0.7971825003623962, "z": -0.008485661819577217 }, { "x": 0.5223897099494934, "y": 0.925589919090271, "z": 0.01249657291918993 }, { "x": 0.48500555753707886, "y": 0.7959478497505188, "z": -0.0032065745908766985 }, { "x": 0.5037734508514404, "y": 0.8184596300125122, "z": -0.004932103678584099 }, { "x": 0.4766361117362976, "y": 0.828806459903717, "z": 0.01027688942849636 }, { "x": 0.5589827299118042, "y": 0.974656343460083, "z": 9666886180639267e-19 }, { "x": 0.5294582843780518, "y": 0.7541216611862183, "z": -0.025603046640753746 }, { "x": 0.4973002076148987, "y": 0.9208990931510925, "z": 0.031931452453136444 }, { "x": 0.5163551568984985, "y": 0.9432790875434875, "z": 0.024321340024471283 }, { "x": 0.49399662017822266, "y": 0.8814862370491028, "z": 0.018687399104237556 }, { "x": 0.44948166608810425, "y": 0.836137592792511, "z": 0.05702034756541252 }, { "x": 0.47898444533348083, "y": 0.8836610913276672, "z": 0.03150695189833641 }, { "x": 0.4454479217529297, "y": 0.8499438166618347, "z": 0.08868525922298431 }, { "x": 0.49572959542274475, "y": 0.8452823758125305, "z": 0.0036111653316766024 }, { "x": 0.5362502336502075, "y": 0.7222585678100586, "z": -0.027912352234125137 }, { "x": 0.5393770337104797, "y": 0.7850722074508667, "z": -0.05415399745106697 }, { "x": 0.531399667263031, "y": 0.7898418307304382, "z": -0.03883346915245056 }, { "x": 0.5451627373695374, "y": 0.7717036604881287, "z": -0.06480253487825394 }, { "x": 0.5206395983695984, "y": 0.6287745833396912, "z": -0.010521138086915016 }, { "x": 0.4974782466888428, "y": 0.6191938519477844, "z": -0.014098240062594414 }, { "x": 0.4774145185947418, "y": 0.6193130612373352, "z": -0.013643337413668633 }, { "x": 0.4616098403930664, "y": 0.6259890198707581, "z": -0.008448202162981033 }, { "x": 0.4516478478908539, "y": 0.6368461847305298, "z": 9050309745362028e-20 }, { "x": 0.4485096037387848, "y": 0.6719120740890503, "z": 0.022984720766544342 }, { "x": 0.42177659273147583, "y": 0.7240667343139648, "z": 0.08511673659086227 }, { "x": 0.4616215229034424, "y": 0.6988231539726257, "z": 0.014238474890589714 }, { "x": 0.4755798876285553, "y": 0.7034608721733093, "z": 0.00625590980052948 }, { "x": 0.4924992024898529, "y": 0.7005885243415833, "z": 9391739731654525e-19 }, { "x": 0.5082254409790039, "y": 0.693384051322937, "z": -9464038303121924e-19 }, { "x": 0.5203112959861755, "y": 0.6849707961082458, "z": -0.0022114769089967012 }, { "x": 0.52867591381073, "y": 0.6779075860977173, "z": -0.002962538506835699 }, { "x": 0.4213953912258148, "y": 0.7219811677932739, "z": 0.1350894570350647 }, { "x": 0.5320829749107361, "y": 0.794858992099762, "z": -0.03181503340601921 }, { "x": 0.5452795028686523, "y": 0.7286570072174072, "z": -0.04771539941430092 }, { "x": 0.5496407747268677, "y": 0.7866933345794678, "z": -0.06452003121376038 }, { "x": 0.557040274143219, "y": 0.7962084412574768, "z": -0.05837344378232956 }, { "x": 0.549176812171936, "y": 0.7895247936248779, "z": -0.057761140167713165 }, { "x": 0.5362890362739563, "y": 0.8005836606025696, "z": -0.026903774589300156 }, { "x": 0.560200035572052, "y": 0.7983731031417847, "z": -0.06172555685043335 }, { "x": 0.5616944432258606, "y": 0.8022753596305847, "z": -0.045200999826192856 }, { "x": 0.5273328423500061, "y": 0.6611284017562866, "z": 0.0029021520167589188 }, { "x": 0.534850537776947, "y": 0.6660012006759644, "z": -0.005215510260313749 }, { "x": 0.5394860506057739, "y": 0.6701375246047974, "z": -0.014931917190551758 }, { "x": 0.4634307324886322, "y": 0.658291757106781, "z": 0.009295716881752014 }, { "x": 0.4538393020629883, "y": 0.6519932150840759, "z": 0.00930330716073513 }, { "x": 0.5776031613349915, "y": 0.7159298658370972, "z": -0.057365912944078445 }, { "x": 0.6504855155944824, "y": 0.6461779475212097, "z": 0.014184834435582161 }, { "x": 0.5860154032707214, "y": 0.7962266206741333, "z": -0.04522843658924103 }, { "x": 0.6842049360275269, "y": 0.5631637573242188, "z": 0.07207967340946198 }, { "x": 0.6152560710906982, "y": 0.6674962639808655, "z": 7529259892180562e-19 }, { "x": 0.6280948519706726, "y": 0.6684326529502869, "z": 0.0016892586136236787 }, { "x": 0.6408625245094299, "y": 0.6663892269134521, "z": 0.005331226624548435 }, { "x": 0.6557814478874207, "y": 0.6534678936004639, "z": 0.01646413467824459 }, { "x": 0.6035663485527039, "y": 0.6639701724052429, "z": 0.0013799630105495453 }, { "x": 0.6329053044319153, "y": 0.608010470867157, "z": -0.006195899099111557 }, { "x": 0.6167260408401489, "y": 0.6117533445358276, "z": -0.006319951266050339 }, { "x": 0.6471013426780701, "y": 0.6112449765205383, "z": -0.0017843559617176652 }, { "x": 0.6560901999473572, "y": 0.6185776591300964, "z": 0.004047257360070944 }, { "x": 0.6666946411132812, "y": 0.6651176810264587, "z": 0.023647578433156013 }, { "x": 0.6311345100402832, "y": 0.9495396018028259, "z": 0.014004078693687916 }, { "x": 0.6544655561447144, "y": 0.6397901773452759, "z": 0.01809609681367874 }, { "x": 0.6965808868408203, "y": 0.6482675075531006, "z": 0.08304904401302338 }, { "x": 0.679817259311676, "y": 0.650188148021698, "z": 0.03632688894867897 }, { "x": 0.6336516737937927, "y": 0.7541458010673523, "z": -0.007742783520370722 }, { "x": 0.5921701192855835, "y": 0.8567668199539185, "z": -0.029399123042821884 }, { "x": 0.591663658618927, "y": 0.870215654373169, "z": -0.02103729173541069 }, { "x": 0.6068367958068848, "y": 0.8584195375442505, "z": -0.020668085664510727 }, { "x": 0.6176617741584778, "y": 0.860965371131897, "z": -0.009790095500648022 }, { "x": 0.6040634512901306, "y": 0.8686612844467163, "z": -0.015289564616978168 }, { "x": 0.6143736839294434, "y": 0.8671170473098755, "z": -0.005712216719985008 }, { "x": 0.6373105049133301, "y": 0.8815656900405884, "z": 0.012672550976276398 }, { "x": 0.5832505822181702, "y": 0.7866312861442566, "z": -0.07051534950733185 }, { "x": 0.5836675763130188, "y": 0.7658692598342896, "z": -0.07566110789775848 }, { "x": 0.6709531545639038, "y": 0.604898989200592, "z": 0.005951565690338612 }, { "x": 0.6029891967773438, "y": 0.705652117729187, "z": -0.013388276100158691 }, { "x": 0.6131622195243835, "y": 0.7728396058082581, "z": -0.036248479038476944 }, { "x": 0.6123163104057312, "y": 0.7612020373344421, "z": -0.03264721855521202 }, { "x": 0.6696187853813171, "y": 0.744706928730011, "z": 0.009673702530562878 }, { "x": 0.5803102254867554, "y": 0.7385968565940857, "z": -0.0689152330160141 }, { "x": 0.6404349207878113, "y": 0.5877999663352966, "z": -0.01929756999015808 }, { "x": 0.6588467955589294, "y": 0.5929454565048218, "z": -0.008487257175147533 }, { "x": 0.6720337867736816, "y": 0.530631422996521, "z": 0.043437421321868896 }, { "x": 0.584305465221405, "y": 0.6099005341529846, "z": -0.030301367864012718 }, { "x": 0.6034283638000488, "y": 0.6217452883720398, "z": -0.001970183802768588 }, { "x": 0.6460927724838257, "y": 0.8608663082122803, "z": 0.015541625209152699 }, { "x": 0.6957815289497375, "y": 0.8326103091239929, "z": 0.13015234470367432 }, { "x": 0.6043362617492676, "y": 0.7861682772636414, "z": -0.030476901680231094 }, { "x": 0.594293475151062, "y": 0.7942103147506714, "z": -0.032218821346759796 }, { "x": 0.6324057579040527, "y": 0.8665139675140381, "z": 0.014255806803703308 }, { "x": 0.6296147704124451, "y": 0.8667733669281006, "z": 0.010388285852968693 }, { "x": 0.663644552230835, "y": 0.5798642635345459, "z": -0.0022301070857793093 }, { "x": 0.6140630841255188, "y": 0.7809288501739502, "z": -0.02835679054260254 }, { "x": 0.615908145904541, "y": 0.5921698212623596, "z": -0.026804860681295395 }, { "x": 0.617181122303009, "y": 0.5748661756515503, "z": -0.03060605563223362 }, { "x": 0.6222207546234131, "y": 0.49137672781944275, "z": -0.011151673272252083 }, { "x": 0.6669357419013977, "y": 0.5541607141494751, "z": 0.017466170713305473 }, { "x": 0.6182981729507446, "y": 0.5320425629615784, "z": -0.021793590858578682 }, { "x": 0.6760554313659668, "y": 0.595052182674408, "z": 0.017115700989961624 }, { "x": 0.6801463961601257, "y": 0.5800720453262329, "z": 0.043127160519361496 }, { "x": 0.5922210812568665, "y": 0.8644017577171326, "z": -0.02662893570959568 }, { "x": 0.6054555177688599, "y": 0.8637874722480774, "z": -0.018363753333687782 }, { "x": 0.6161889433860779, "y": 0.8641164898872375, "z": -0.008808949030935764 }, { "x": 0.6017249822616577, "y": 0.7901403307914734, "z": -0.028126630932092667 }, { "x": 0.631446123123169, "y": 0.8664817810058594, "z": 0.012112865224480629 }, { "x": 0.6249198913574219, "y": 0.8716511130332947, "z": 0.003882825840264559 }, { "x": 0.6281915903091431, "y": 0.867301881313324, "z": 0.009891441091895103 }, { "x": 0.5986843109130859, "y": 0.7813931703567505, "z": -0.050227612257003784 }, { "x": 0.6126407384872437, "y": 0.869275689125061, "z": -0.0031255714129656553 }, { "x": 0.6027271151542664, "y": 0.8711842894554138, "z": -0.009324162267148495 }, { "x": 0.59088134765625, "y": 0.8742044568061829, "z": -0.014608660712838173 }, { "x": 0.5984604358673096, "y": 0.9216185212135315, "z": -0.005981989670544863 }, { "x": 0.5950398445129395, "y": 0.8964707255363464, "z": -0.01703473925590515 }, { "x": 0.5941568613052368, "y": 0.8882410526275635, "z": -0.017784785479307175 }, { "x": 0.5928806662559509, "y": 0.8803883194923401, "z": -0.014153128489851952 }, { "x": 0.5909661054611206, "y": 0.8748103976249695, "z": -0.012609979137778282 }, { "x": 0.6128016710281372, "y": 0.8702545762062073, "z": -0.0022550546564161777 }, { "x": 0.6150846481323242, "y": 0.8726804256439209, "z": -0.00414019962772727 }, { "x": 0.6173093914985657, "y": 0.8770190477371216, "z": -0.005970994010567665 }, { "x": 0.619335412979126, "y": 0.8814800977706909, "z": -0.0036864024586975574 }, { "x": 0.6292637586593628, "y": 0.8314558267593384, "z": -0.007714875973761082 }, { "x": 0.702275276184082, "y": 0.7320667505264282, "z": 0.1433621346950531 }, { "x": 0.6204835176467896, "y": 0.8689177632331848, "z": 0.0044869170524179935 }, { "x": 0.6223508715629578, "y": 0.8704851269721985, "z": 0.00352082890458405 }, { "x": 0.590448260307312, "y": 0.8029727935791016, "z": -0.03200828656554222 }, { "x": 0.6097423434257507, "y": 0.7933741211891174, "z": -0.018042555078864098 }, { "x": 0.59229576587677, "y": 0.7993767261505127, "z": -0.032564569264650345 }, { "x": 0.6171364188194275, "y": 0.7153720259666443, "z": -0.007672437466681004 }, { "x": 0.6389747858047485, "y": 0.726390540599823, "z": -0.002999067772179842 }, { "x": 0.6151940226554871, "y": 0.769412100315094, "z": -0.024427521973848343 }, { "x": 0.6526776552200317, "y": 0.505868136882782, "z": 0.01412637997418642 }, { "x": 0.6475822329521179, "y": 0.5375454425811768, "z": -0.0033899128902703524 }, { "x": 0.6433356404304504, "y": 0.5714520215988159, "z": -0.017428796738386154 }, { "x": 0.626949667930603, "y": 0.8962116837501526, "z": 0.005602736957371235 }, { "x": 0.5868416428565979, "y": 0.5829002261161804, "z": -0.03727729618549347 }, { "x": 0.5877229571342468, "y": 0.5345035791397095, "z": -0.032396964728832245 }, { "x": 0.5887066125869751, "y": 0.48655083775520325, "z": -0.025856535881757736 }, { "x": 0.6507197618484497, "y": 0.6612282991409302, "z": 0.011114613153040409 }, { "x": 0.6803066730499268, "y": 0.677992045879364, "z": 0.032125361263751984 }, { "x": 0.5963194370269775, "y": 0.6598632335662842, "z": 0.002976928371936083 }, { "x": 0.667536199092865, "y": 0.6274255514144897, "z": 0.015618261881172657 }, { "x": 0.5930740833282471, "y": 0.6940041780471802, "z": -0.019217798486351967 }, { "x": 0.6053346395492554, "y": 0.7676517963409424, "z": -0.050308309495449066 }, { "x": 0.6934473514556885, "y": 0.6884298920631409, "z": 0.04794462397694588 }, { "x": 0.6738007664680481, "y": 0.6934011578559875, "z": 0.020697161555290222 }, { "x": 0.6588084697723389, "y": 0.7033141851425171, "z": 0.008462334051728249 }, { "x": 0.6346072554588318, "y": 0.7029502391815186, "z": 0.001542167621664703 }, { "x": 0.6157816648483276, "y": 0.6966525912284851, "z": -0.002009218093007803 }, { "x": 0.6015574336051941, "y": 0.688928484916687, "z": -0.006588225718587637 }, { "x": 0.5746836066246033, "y": 0.6711069345474243, "z": -0.03597589209675789 }, { "x": 0.6947521567344666, "y": 0.7309479117393494, "z": 0.046707939356565475 }, { "x": 0.6759101152420044, "y": 0.6249120831489563, "z": 0.021654341369867325 }, { "x": 0.5794773101806641, "y": 0.7971615195274353, "z": -0.06339326500892639 }, { "x": 0.6041849851608276, "y": 0.727514922618866, "z": -0.017512541264295578 }, { "x": 0.6968844532966614, "y": 0.6440950036048889, "z": 0.12727996706962585 }, { "x": 0.5910853147506714, "y": 0.679325520992279, "z": -0.009497715160250664 }, { "x": 0.6157375574111938, "y": 0.7695677280426025, "z": -0.010624290443956852 }, { "x": 0.6606494784355164, "y": 0.6410489678382874, "z": 0.0208158977329731 }, { "x": 0.6040687561035156, "y": 0.7531470656394958, "z": -0.045887019485235214 }, { "x": 0.7012156248092651, "y": 0.780247151851654, "z": 0.14028730988502502 }, { "x": 0.595149576663971, "y": 0.6527782678604126, "z": 0.006308757700026035 }, { "x": 0.5925500392913818, "y": 0.7436665892601013, "z": -0.060151755809783936 }, { "x": 0.6780198812484741, "y": 0.8905693888664246, "z": 0.0626060739159584 }, { "x": 0.676746666431427, "y": 0.9113880395889282, "z": 0.08726003766059875 }, { "x": 0.7030686140060425, "y": 0.7312687635421753, "z": 0.09529774636030197 }, { "x": 0.688987135887146, "y": 0.8588417172431946, "z": 0.07752864807844162 }, { "x": 0.6883691549301147, "y": 0.6109960675239563, "z": 0.06669612973928452 }, { "x": 0.6358906030654907, "y": 0.9702065587043762, "z": 0.023120900616049767 }, { "x": 0.5781539678573608, "y": 0.8023634552955627, "z": -0.044763918966054916 }, { "x": 0.6170316934585571, "y": 0.7408350706100464, "z": -0.011375460773706436 }, { "x": 0.688542366027832, "y": 0.6516284346580505, "z": 0.050206027925014496 }, { "x": 0.6385149359703064, "y": 0.6540714502334595, "z": 0.006462941411882639 }, { "x": 0.6279382109642029, "y": 0.6563615798950195, "z": 0.003062846139073372 }, { "x": 0.6268895268440247, "y": 0.8736732006072998, "z": 0.00627936702221632 }, { "x": 0.6944946050643921, "y": 0.7709181308746338, "z": 0.053824134171009064 }, { "x": 0.614617109298706, "y": 1.0022112131118774, "z": 0.02719894051551819 }, { "x": 0.6493719220161438, "y": 0.9665167927742004, "z": 0.053563784807920456 }, { "x": 0.6624587178230286, "y": 0.943530797958374, "z": 0.068605437874794 }, { "x": 0.6162528991699219, "y": 0.6558693051338196, "z": 0.002187855076044798 }, { "x": 0.6058168411254883, "y": 0.654328465461731, "z": 0.0036193584091961384 }, { "x": 0.5987918972969055, "y": 0.6536934971809387, "z": 0.006134530063718557 }, { "x": 0.6831037402153015, "y": 0.6195642948150635, "z": 0.03511790186166763 }, { "x": 0.6062582731246948, "y": 0.6356398463249207, "z": 0.001280312892049551 }, { "x": 0.6174948811531067, "y": 0.62776118516922, "z": -0.0013642468256875873 }, { "x": 0.6297246217727661, "y": 0.6253792643547058, "z": -7034156005829573e-19 }, { "x": 0.6407091617584229, "y": 0.627578616142273, "z": 0.0028144705574959517 }, { "x": 0.6479622721672058, "y": 0.6322650909423828, "z": 0.00750273372977972 }, { "x": 0.6915091276168823, "y": 0.5990704298019409, "z": 0.10270945727825165 }, { "x": 0.6457163095474243, "y": 0.6504453420639038, "z": 0.010696077719330788 }, { "x": 0.6164222955703735, "y": 0.8231936097145081, "z": -0.016772059723734856 }, { "x": 0.6042401194572449, "y": 0.7830976843833923, "z": -0.03630910441279411 }, { "x": 0.5922216773033142, "y": 0.8228387236595154, "z": -0.029992375522851944 }, { "x": 0.6646111011505127, "y": 0.92097008228302, "z": 0.050967294722795486 }, { "x": 0.651232898235321, "y": 0.9460107088088989, "z": 0.038000158965587616 }, { "x": 0.6140977144241333, "y": 0.9882472157478333, "z": 0.009882091544568539 }, { "x": 0.6870781183242798, "y": 0.8768675327301025, "z": 0.10980932414531708 }, { "x": 0.5986856818199158, "y": 0.6456438899040222, "z": 0.003999010659754276 }, { "x": 0.585981547832489, "y": 0.7034481763839722, "z": -0.0377722829580307 }, { "x": 0.6342031359672546, "y": 0.9867448806762695, "z": 0.03786521404981613 }, { "x": 0.7013950943946838, "y": 0.776049017906189, "z": 0.09598205983638763 }, { "x": 0.6030206680297852, "y": 0.8719133138656616, "z": -0.007931148633360863 }, { "x": 0.6050592064857483, "y": 0.8767156004905701, "z": -0.009791925549507141 }, { "x": 0.6073468923568726, "y": 0.8831382393836975, "z": -0.012361008673906326 }, { "x": 0.6087977290153503, "y": 0.890143632888794, "z": -0.01098148338496685 }, { "x": 0.6147705316543579, "y": 0.9110084772109985, "z": -0.0018823575228452682 }, { "x": 0.622577965259552, "y": 0.8670604825019836, "z": 0.002609190298244357 }, { "x": 0.6241236329078674, "y": 0.8651344180107117, "z": 0.0025534380692988634 }, { "x": 0.6257084608078003, "y": 0.8638408184051514, "z": 0.0023300074972212315 }, { "x": 0.639931321144104, "y": 0.8449671268463135, "z": 0.0038123116828501225 }, { "x": 0.6810906529426575, "y": 0.7856625318527222, "z": 0.02717764675617218 }, { "x": 0.583532452583313, "y": 0.6811994910240173, "z": -0.026588857173919678 }, { "x": 0.5855660438537598, "y": 0.6393819451332092, "z": -0.004512844607234001 }, { "x": 0.5932201743125916, "y": 0.6398029327392578, "z": 8020466193556786e-19 }, { "x": 0.6200879812240601, "y": 0.8683351874351501, "z": 0.00417016725987196 }, { "x": 0.6842559576034546, "y": 0.8330534100532532, "z": 0.050836317241191864 }, { "x": 0.5754412412643433, "y": 0.6418221592903137, "z": -0.022838059812784195 }, { "x": 0.6232790350914001, "y": 0.9295297265052795, "z": 0.006339520215988159 }, { "x": 0.5764067769050598, "y": 0.694546639919281, "z": -0.04825803264975548 }, { "x": 0.59778892993927, "y": 0.7343927621841431, "z": -0.035004377365112305 }, { "x": 0.6042810678482056, "y": 0.9441440105438232, "z": -0.0010970570147037506 }, { "x": 0.6496372222900391, "y": 0.8869078159332275, "z": 0.021036235615611076 }, { "x": 0.6274012327194214, "y": 0.7830310463905334, "z": -0.006658440921455622 }, { "x": 0.637792706489563, "y": 0.9104999899864197, "z": 0.014290250837802887 }, { "x": 0.6549934148788452, "y": 0.7748609185218811, "z": -6672973395325243e-19 }, { "x": 0.6404005289077759, "y": 0.801220715045929, "z": -0.0026642554439604282 }, { "x": 0.6671456694602966, "y": 0.8045546412467957, "z": 0.013180811889469624 }, { "x": 0.6107483506202698, "y": 0.9680658578872681, "z": 0.001778992242179811 }, { "x": 0.6060343980789185, "y": 0.744587242603302, "z": -0.024382334202528 }, { "x": 0.6602751612663269, "y": 0.8998945355415344, "z": 0.0344940721988678 }, { "x": 0.6463775038719177, "y": 0.9262562394142151, "z": 0.02617623284459114 }, { "x": 0.6579852104187012, "y": 0.8602304458618164, "z": 0.021586716175079346 }, { "x": 0.6926165223121643, "y": 0.8053340315818787, "z": 0.061075080186128616 }, { "x": 0.6724731922149658, "y": 0.8594399690628052, "z": 0.03457934781908989 }, { "x": 0.6975721716880798, "y": 0.8183245062828064, "z": 0.09300774335861206 }, { "x": 0.6512877941131592, "y": 0.8258221745491028, "z": 0.006324059329926968 }, { "x": 0.594887375831604, "y": 0.7148372530937195, "z": -0.026898479089140892 }, { "x": 0.6017440557479858, "y": 0.7773507833480835, "z": -0.05312420800328255 }, { "x": 0.6096571683883667, "y": 0.7806998491287231, "z": -0.037646256387233734 }, { "x": 0.5952993035316467, "y": 0.7654367685317993, "z": -0.06398405134677887 }, { "x": 0.5950021147727966, "y": 0.6201304793357849, "z": -0.009297547861933708 }, { "x": 0.6165438890457153, "y": 0.6052900552749634, "z": -0.012455573305487633 }, { "x": 0.6362661719322205, "y": 0.6015968918800354, "z": -0.011649220250546932 }, { "x": 0.6522727608680725, "y": 0.6046400666236877, "z": -0.005903332494199276 }, { "x": 0.6625409722328186, "y": 0.6128141283988953, "z": 0.0030042496509850025 }, { "x": 0.6688099503517151, "y": 0.6457712054252625, "z": 0.026322703808546066 }, { "x": 0.7013440728187561, "y": 0.6893666386604309, "z": 0.08984331786632538 }, { "x": 0.6608623266220093, "y": 0.6749406456947327, "z": 0.0172116681933403 }, { "x": 0.6482325196266174, "y": 0.6823726296424866, "z": 0.008881398476660252 }, { "x": 0.6313265562057495, "y": 0.6842025518417358, "z": 0.0031308617908507586 }, { "x": 0.6147016286849976, "y": 0.6809731721878052, "z": 7630771724507213e-19 }, { "x": 0.6018834114074707, "y": 0.6755372285842896, "z": -8834321051836014e-19 }, { "x": 0.5925027132034302, "y": 0.670681357383728, "z": -0.001968748401850462 }, { "x": 0.700127363204956, "y": 0.6871103644371033, "z": 0.13980500400066376 }, { "x": 0.6095665693283081, "y": 0.7853189706802368, "z": -0.03074747882783413 }, { "x": 0.5880423784255981, "y": 0.7229287028312683, "z": -0.04691500961780548 }, { "x": 0.5930182337760925, "y": 0.7811514139175415, "z": -0.06398335844278336 }, { "x": 0.5867722034454346, "y": 0.7922660112380981, "z": -0.05794971063733101 }, { "x": 0.5933279991149902, "y": 0.7842848896980286, "z": -0.05714067071676254 }, { "x": 0.6063535809516907, "y": 0.7920218706130981, "z": -0.02590685710310936 }, { "x": 0.5839452743530273, "y": 0.794978141784668, "z": -0.0615212507545948 }, { "x": 0.5828126072883606, "y": 0.8000800013542175, "z": -0.0449722595512867 }, { "x": 0.5909603834152222, "y": 0.6541213393211365, "z": 0.003991890233010054 }, { "x": 0.5852181911468506, "y": 0.6602938771247864, "z": -0.004428438376635313 }, { "x": 0.5825737714767456, "y": 0.6651063561439514, "z": -0.014345290139317513 }, { "x": 0.6517343521118164, "y": 0.6362385153770447, "z": 0.012151890434324741 }, { "x": 0.6615052819252014, "y": 0.6281577944755554, "z": 0.0123682152479887 }, { "x": 0.4856873154640198, "y": 0.6568945646286011, "z": 720038078725338e-18 }, { "x": 0.49988406896591187, "y": 0.6547410488128662, "z": 6949726957827806e-19 }, { "x": 0.48438939452171326, "y": 0.6392973065376282, "z": 705525919329375e-18 }, { "x": 0.47143134474754333, "y": 0.6589511632919312, "z": 6980331381782889e-19 }, { "x": 0.48704618215560913, "y": 0.6752797961235046, "z": 6921177846379578e-19 }, { "x": 0.6243702173233032, "y": 0.640461802482605, "z": -6592126737814397e-20 }, { "x": 0.6390967965126038, "y": 0.6385173797607422, "z": -16105435497593135e-20 }, { "x": 0.6230536699295044, "y": 0.6224825382232666, "z": -16136496560648084e-20 }, { "x": 0.6095397472381592, "y": 0.641917884349823, "z": -1803556369850412e-19 }, { "x": 0.6250996589660645, "y": 0.6586247682571411, "z": -1785515050869435e-19 }]], "faceBlendshapes": [{ "categories": [{ "index": 0, "score": 5187174338061595e-21, "categoryName": "_neutral", "displayName": "" }, { "index": 1, "score": 0.24521504342556, "categoryName": "browDownLeft", "displayName": "" }, { "index": 2, "score": 0.1987743377685547, "categoryName": "browDownRight", "displayName": "" }, { "index": 3, "score": 0.013400448486208916, "categoryName": "browInnerUp", "displayName": "" }, { "index": 4, "score": 0.012361560948193073, "categoryName": "browOuterUpLeft", "displayName": "" }, { "index": 5, "score": 0.019305096939206123, "categoryName": "browOuterUpRight", "displayName": "" }, { "index": 6, "score": 28426356948330067e-21, "categoryName": "cheekPuff", "displayName": "" }, { "index": 7, "score": 34500112633395474e-23, "categoryName": "cheekSquintLeft", "displayName": "" }, { "index": 8, "score": 483789051486383e-21, "categoryName": "cheekSquintRight", "displayName": "" }, { "index": 9, "score": 0.07650448381900787, "categoryName": "eyeBlinkLeft", "displayName": "" }, { "index": 10, "score": 0.05070012807846069, "categoryName": "eyeBlinkRight", "displayName": "" }, { "index": 11, "score": 0.13978900015354156, "categoryName": "eyeLookDownLeft", "displayName": "" }, { "index": 12, "score": 0.14198613166809082, "categoryName": "eyeLookDownRight", "displayName": "" }, { "index": 13, "score": 0.2177766114473343, "categoryName": "eyeLookInLeft", "displayName": "" }, { "index": 14, "score": 0.014739357866346836, "categoryName": "eyeLookInRight", "displayName": "" }, { "index": 15, "score": 0.02361512929201126, "categoryName": "eyeLookOutLeft", "displayName": "" }, { "index": 16, "score": 0.19679604470729828, "categoryName": "eyeLookOutRight", "displayName": "" }, { "index": 17, "score": 0.04874616861343384, "categoryName": "eyeLookUpLeft", "displayName": "" }, { "index": 18, "score": 0.049392376095056534, "categoryName": "eyeLookUpRight", "displayName": "" }, { "index": 19, "score": 0.34944331645965576, "categoryName": "eyeSquintLeft", "displayName": "" }, { "index": 20, "score": 0.2939716875553131, "categoryName": "eyeSquintRight", "displayName": "" }, { "index": 21, "score": 0.005955042317509651, "categoryName": "eyeWideLeft", "displayName": "" }, { "index": 22, "score": 0.006776117719709873, "categoryName": "eyeWideRight", "displayName": "" }, { "index": 23, "score": 16942436559475027e-21, "categoryName": "jawForward", "displayName": "" }, { "index": 24, "score": 0.0045165494084358215, "categoryName": "jawLeft", "displayName": "" }, { "index": 25, "score": 0.07803940027952194, "categoryName": "jawOpen", "displayName": "" }, { "index": 26, "score": 2090057751047425e-20, "categoryName": "jawRight", "displayName": "" }, { "index": 27, "score": 0.06032035872340202, "categoryName": "mouthClose", "displayName": "" }, { "index": 28, "score": 0.00228882092051208, "categoryName": "mouthDimpleLeft", "displayName": "" }, { "index": 29, "score": 0.00781762320548296, "categoryName": "mouthDimpleRight", "displayName": "" }, { "index": 30, "score": 0.0017093931091949344, "categoryName": "mouthFrownLeft", "displayName": "" }, { "index": 31, "score": 0.0019319106359034777, "categoryName": "mouthFrownRight", "displayName": "" }, { "index": 32, "score": 8485237776767462e-20, "categoryName": "mouthFunnel", "displayName": "" }, { "index": 33, "score": 9051355300471187e-19, "categoryName": "mouthLeft", "displayName": "" }, { "index": 34, "score": 3630454302765429e-19, "categoryName": "mouthLowerDownLeft", "displayName": "" }, { "index": 35, "score": 17601238505449146e-20, "categoryName": "mouthLowerDownRight", "displayName": "" }, { "index": 36, "score": 0.12865161895751953, "categoryName": "mouthPressLeft", "displayName": "" }, { "index": 37, "score": 0.20137207210063934, "categoryName": "mouthPressRight", "displayName": "" }, { "index": 38, "score": 0.0022203284315764904, "categoryName": "mouthPucker", "displayName": "" }, { "index": 39, "score": 9096377179957926e-19, "categoryName": "mouthRight", "displayName": "" }, { "index": 40, "score": 0.34189721941947937, "categoryName": "mouthRollLower", "displayName": "" }, { "index": 41, "score": 0.11409689486026764, "categoryName": "mouthRollUpper", "displayName": "" }, { "index": 42, "score": 0.17172536253929138, "categoryName": "mouthShrugLower", "displayName": "" }, { "index": 43, "score": 0.004038424696773291, "categoryName": "mouthShrugUpper", "displayName": "" }, { "index": 44, "score": 23205230536404997e-20, "categoryName": "mouthSmileLeft", "displayName": "" }, { "index": 45, "score": 19313619122840464e-20, "categoryName": "mouthSmileRight", "displayName": "" }, { "index": 46, "score": 0.0018571305554360151, "categoryName": "mouthStretchLeft", "displayName": "" }, { "index": 47, "score": 0.0023813238367438316, "categoryName": "mouthStretchRight", "displayName": "" }, { "index": 48, "score": 24323100660694763e-21, "categoryName": "mouthUpperUpLeft", "displayName": "" }, { "index": 49, "score": 3161552012898028e-20, "categoryName": "mouthUpperUpRight", "displayName": "" }, { "index": 50, "score": 108198406678639e-21, "categoryName": "noseSneerLeft", "displayName": "" }, { "index": 51, "score": 12652527630052646e-22, "categoryName": "noseSneerRight", "displayName": "" }], "headIndex": -1, "headName": "" }], "facialTransformationMatrixes": [{ "rows": 4, "columns": 4, "data": [0.9947517514228821, 0.10230544209480286, 0.0013679931871592999, 0, -0.10230997204780579, 0.9947447776794434, 0.003816320328041911, 0, -970348424743861e-18, -0.0039362297393381596, 0.9999914169311523, 0, 2.8888821601867676, -7.808934211730957, -30.52109146118164, 1] }] } }; // node_modules/@react-three/drei/web/FaceLandmarker.js var React140 = __toESM(require_react()); var import_react25 = __toESM(require_react()); var FaceLandmarkerContext = (0, import_react25.createContext)({}); var FaceLandmarkerDefaults = { basePath: "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.17/wasm", options: { baseOptions: { modelAssetPath: "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task", delegate: "GPU" }, runningMode: "VIDEO", outputFaceBlendshapes: true, outputFacialTransformationMatrixes: true } }; var FaceLandmarker = (0, import_react25.forwardRef)(({ basePath = FaceLandmarkerDefaults.basePath, options = FaceLandmarkerDefaults.options, children }, fref) => { const opts = JSON.stringify(options); const faceLandmarker = suspend(async () => { const { FilesetResolver, FaceLandmarker: FaceLandmarker2 } = await import("./vision_bundle-ZAS5UOAV.js"); const vision = await FilesetResolver.forVisionTasks(basePath); return FaceLandmarker2.createFromOptions(vision, options); }, [basePath, opts]); (0, import_react25.useEffect)(() => { return () => { faceLandmarker == null || faceLandmarker.close(); clear([basePath, opts]); }; }, [faceLandmarker, basePath, opts]); (0, import_react25.useImperativeHandle)(fref, () => faceLandmarker, [faceLandmarker]); return React140.createElement(FaceLandmarkerContext.Provider, { value: faceLandmarker }, children); }); function useFaceLandmarker() { return (0, import_react25.useContext)(FaceLandmarkerContext); } // node_modules/@react-three/drei/web/FaceControls.js function mean2(v13, v22) { return v13.clone().add(v22).multiplyScalar(0.5); } function localToLocal(objSrc, v5, objDst) { const v_world = objSrc.localToWorld(v5); return objDst.worldToLocal(v_world); } var FaceControlsContext = (0, import_react26.createContext)({}); var FaceControls = (0, import_react26.forwardRef)(({ camera, videoTexture = { start: true }, manualDetect = false, faceLandmarkerResult, manualUpdate = false, makeDefault, smoothTime = 0.25, offset = true, offsetScalar = 80, eyes = false, eyesAsOrigin = true, depth = 0.15, debug = false, facemesh }, fref) => { var _result$facialTransfo, _result$faceBlendshap; const scene = useThree((state) => state.scene); const defaultCamera = useThree((state) => state.camera); const set = useThree((state) => state.set); const get = useThree((state) => state.get); const explCamera = camera || defaultCamera; const facemeshApiRef = (0, import_react26.useRef)(null); const [target2] = (0, import_react26.useState)(() => new Object3D()); const [irisRightDirPos] = (0, import_react26.useState)(() => new Vector3()); const [irisLeftDirPos] = (0, import_react26.useState)(() => new Vector3()); const [irisRightLookAt] = (0, import_react26.useState)(() => new Vector3()); const [irisLeftLookAt] = (0, import_react26.useState)(() => new Vector3()); const computeTarget = (0, import_react26.useCallback)(() => { target2.parent = explCamera.parent; const facemeshApi = facemeshApiRef.current; if (facemeshApi) { const { outerRef, eyeRightRef, eyeLeftRef } = facemeshApi; if (eyeRightRef.current && eyeLeftRef.current) { const { irisDirRef: irisRightDirRef } = eyeRightRef.current; const { irisDirRef: irisLeftDirRef } = eyeLeftRef.current; if (irisRightDirRef.current && irisLeftDirRef.current && outerRef.current) { irisRightDirPos.copy(localToLocal(irisRightDirRef.current, new Vector3(0, 0, 0), outerRef.current)); irisLeftDirPos.copy(localToLocal(irisLeftDirRef.current, new Vector3(0, 0, 0), outerRef.current)); target2.position.copy(localToLocal(outerRef.current, mean2(irisRightDirPos, irisLeftDirPos), explCamera.parent || scene)); irisRightLookAt.copy(localToLocal(irisRightDirRef.current, new Vector3(0, 0, 1), outerRef.current)); irisLeftLookAt.copy(localToLocal(irisLeftDirRef.current, new Vector3(0, 0, 1), outerRef.current)); target2.lookAt(outerRef.current.localToWorld(mean2(irisRightLookAt, irisLeftLookAt))); } } else { if (outerRef.current) { target2.position.copy(localToLocal(outerRef.current, new Vector3(0, 0, 0), explCamera.parent || scene)); target2.lookAt(outerRef.current.localToWorld(new Vector3(0, 0, 1))); } } } return target2; }, [explCamera, irisLeftDirPos, irisLeftLookAt, irisRightDirPos, irisRightLookAt, scene, target2]); const [current] = (0, import_react26.useState)(() => new Object3D()); const update2 = (0, import_react26.useCallback)(function(delta, target3) { if (explCamera) { var _target; (_target = target3) !== null && _target !== void 0 ? _target : target3 = computeTarget(); if (smoothTime > 0) { const eps2 = 1e-9; easing.damp3(current.position, target3.position, smoothTime, delta, void 0, void 0, eps2); easing.dampE(current.rotation, target3.rotation, smoothTime, delta, void 0, void 0, eps2); } else { current.position.copy(target3.position); current.rotation.copy(target3.rotation); } explCamera.position.copy(current.position); explCamera.rotation.copy(current.rotation); } }, [explCamera, computeTarget, smoothTime, current.position, current.rotation]); useFrame((_, delta) => { if (manualUpdate) return; update2(delta); }); const videoTextureRef = (0, import_react26.useRef)(null); const [_faceLandmarkerResult, setFaceLandmarkerResult] = (0, import_react26.useState)(); const faceLandmarker = useFaceLandmarker(); const onVideoFrame = (0, import_react26.useCallback)((now2, metadata) => { const texture = videoTextureRef.current; if (!texture) return; const videoFrame = texture.source.data; const result2 = faceLandmarker == null ? void 0 : faceLandmarker.detectForVideo(videoFrame, now2); setFaceLandmarkerResult(result2); }, [faceLandmarker]); const api = (0, import_react26.useMemo)(() => Object.assign(Object.create(EventDispatcher.prototype), { computeTarget, update: update2, facemeshApiRef }), [computeTarget, update2]); (0, import_react26.useImperativeHandle)(fref, () => api, [api]); (0, import_react26.useEffect)(() => { if (makeDefault) { const old = get().controls; set({ controls: api }); return () => set({ controls: old }); } }, [makeDefault, api, get, set]); const result = faceLandmarkerResult !== null && faceLandmarkerResult !== void 0 ? faceLandmarkerResult : _faceLandmarkerResult; const points = result == null ? void 0 : result.faceLandmarks[0]; const facialTransformationMatrix = result == null || (_result$facialTransfo = result.facialTransformationMatrixes) == null ? void 0 : _result$facialTransfo[0]; const faceBlendshapes = result == null || (_result$faceBlendshap = result.faceBlendshapes) == null ? void 0 : _result$faceBlendshap[0]; const videoTextureProps = { onVideoFrame, ...videoTexture }; return React141.createElement(FaceControlsContext.Provider, { value: api }, !manualDetect && React141.createElement(import_react26.Suspense, { fallback: null }, "src" in videoTextureProps ? React141.createElement(VideoTexture2, _extends({ ref: videoTextureRef }, videoTextureProps)) : React141.createElement(WebcamVideoTexture, _extends({ ref: videoTextureRef }, videoTextureProps))), React141.createElement(Facemesh, _extends({ ref: facemeshApiRef, children: React141.createElement("meshNormalMaterial", { side: DoubleSide }) }, facemesh, { points, depth, facialTransformationMatrix, faceBlendshapes, eyes, eyesAsOrigin, offset, offsetScalar, debug, "rotation-z": Math.PI, visible: debug }))); }); var useFaceControls = () => (0, import_react26.useContext)(FaceControlsContext); export { AccumulativeShadows, AdaptiveDpr, AdaptiveEvents, ArcballControls2 as ArcballControls, AsciiRenderer, BBAnchor, Backdrop, BakeShadows, Billboard, Bounds, Box, Bvh, CameraControls3 as CameraControls, CameraControls2 as CameraControlsImpl, CameraShake, Capsule2 as Capsule, CatmullRomLine, Caustics, Center, Circle, Clone, Cloud, CloudInstance, Clouds, ComputedAttribute, Cone, ContactShadows, CubeCamera2 as CubeCamera, CubeTexture2 as CubeTexture, CubicBezierLine, CurveModifier, CycleRaycast, Cylinder, Decal, Detailed, DetectGPU, DeviceOrientationControls2 as DeviceOrientationControls, Dodecahedron, DragControls, Edges, Effects, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, Example, Extrude, FaceControls, FaceLandmarker, FaceLandmarkerDefaults, Facemesh, FacemeshDatas, FacemeshEye, FacemeshEyeDefaults, Fbo, Fbx, FirstPersonControls2 as FirstPersonControls, Fisheye, Float, FlyControls2 as FlyControls, GizmoHelper, GizmoViewcube, GizmoViewport, Gltf, GradientTexture, GradientType, Grid, Helper, Html, Hud, Icosahedron, Image2 as Image, Instance, InstancedAttribute, Instances, IsObject, KeyboardControls, Ktx2, Lathe, Lightformer, Line4 as Line, Loader2 as Loader, MapControls2 as MapControls, MarchingCube, MarchingCubes2 as MarchingCubes, MarchingPlane, Mask, MatcapTexture, Merged, MeshDiscardMaterial, MeshDistortMaterial, MeshPortalMaterial, MeshReflectorMaterial2 as MeshReflectorMaterial, MeshRefractionMaterial2 as MeshRefractionMaterial, MeshTransmissionMaterial, MeshWobbleMaterial, MotionPathControls, MultiMaterial, NormalTexture, Octahedron, OrbitControls2 as OrbitControls, OrthographicCamera2 as OrthographicCamera, Outlines, PerformanceMonitor, PerspectiveCamera2 as PerspectiveCamera, PivotControls, Plane2 as Plane, Point, PointMaterial, PointMaterialImpl, PointerLockControls2 as PointerLockControls, Points2 as Points, PointsBuffer, Polyhedron, PositionMesh, PositionPoint, PositionalAudio, Preload, PresentationControls, Progress, QuadraticBezierLine, RandomizedLight, RenderCubeTexture, RenderTexture, Resize, Ring, RoundedBox, RoundedBoxGeometry2 as RoundedBoxGeometry, Sampler, ScreenQuad, ScreenSizer, ScreenSpace, ScreenVideoTexture, Scroll, ScrollControls, Segment, SegmentObject, Segments, Select, Shadow, ShadowAlpha, Shape2 as Shape, Sky2 as Sky, SoftShadows, Sparkles, Sphere2 as Sphere, Splat, SpotLight2 as SpotLight, SpotLightShadow, SpriteAnimator, Stage, Stars, Stats, StatsGl, Svg, Tetrahedron, Text2 as Text, Text3D, Texture2 as Texture, Torus, TorusKnot2 as TorusKnot, TrackballControls2 as TrackballControls, Trail, TrailTexture, TransformControls2 as TransformControls, Tube, VideoTexture2 as VideoTexture, View, WebcamVideoTexture, Wireframe2 as Wireframe, accumulativeContext, calcPosFromAngles, calculateScaleFactor, checkIfFrameIsEmpty, createInstances, getFirstFrame, isWebGL2Available2 as isWebGL2Available, meshBounds, shaderMaterial, useAnimations, useAspect, useBVH, useBounds, useBoxProjectedEnv, useCamera, useContextBridge, useCubeCamera, useCubeTexture, useCursor, useDepthBuffer, useDetectGPU, useEnvironment, useFBO, useFBX, useFaceControls, useFaceLandmarker, useFont, useGLTF, useGizmoContext, useHelper, useIntersect, useKTX2, useKeyboardControls, useMask, useMatcapTexture, useMotion, useNormalTexture, usePerformanceMonitor, useProgress, useScroll, useSelect, useSpriteAnimator, useSpriteLoader, useSurfaceSampler, useTexture, useTrail, useTrailTexture, useVideoTexture }; //# sourceMappingURL=@react-three_drei.js.map