import { n as __exportAll } from "./chunk-B-1-B7_t.js"; import { $ as Camera, $i as OrthographicCamera, $n as InstancedMesh, As as UniformsUtils, Bo as Sphere, Br as LinearMipmapNearestFilter, Bs as Vector2, C as AnimationMixer, Da as RGBAFormat, Dn as Frustum, Dr as Line, Ea as RGBADepthPacking, Er as LightProbe, Fa as RGBA_ASTC_4x4_Format, Fr as LinearFilter, G as Box3Helper, Ga as RGBA_PVRTC_2BPPV1_Format, Gi as OctahedronGeometry, Gn as ImageBitmapLoader, Go as SpotLight, Gr as LoaderUtils, H as BooleanKeyframeTrack, Hi as Object3D, Ho as Spherical, Hs as Vector4, Ht as DataTexture, Io as Skeleton, J as BufferAttribute, Ja as RGBA_S3TC_DXT3_Format, Jn as IncrementStencilOp, Jo as SpriteMaterial, K as BoxGeometry, Ka as RGBA_PVRTC_4BPPV1_Format, Kr as LoadingManager, Lo as SkeletonHelper, No as ShapePath, Nr as LineLoop, Ns as UnsignedInt248Type, Oo as Scene, Or as Line3, Os as Uniform, Po as ShapeUtils, Pr as LineSegments, Pt as Curve, Qn as InstancedInterleavedBuffer, Qs as WireframeGeometry, Qt as DirectionalLight, Rn as GridHelper, Ro as SkinnedMesh, Rs as UnsignedShortType, Rt as CylinderGeometry, Sn as FloatType, Ti as NearestMipmapNearestFilter, Ts as Uint32BufferAttribute, U as Box2, Ua as RGBA_BPTC_Format, Uo as SphericalHarmonics3, Us as VectorKeyframeTrack, Ut as DataTextureLoader, V as Bone, Vi as NumberKeyframeTrack, Vn as HalfFloatType, Vo as SphereGeometry, Vs as Vector3, W as Box3, Wa as RGBA_ETC2_EAC_Format, Wn as IcosahedronGeometry, Wr as Loader, Wt as DataUtils, X as BufferGeometryLoader, Xn as InstancedBufferAttribute, Xr as MOUSE, Xt as DepthTexture, Y as BufferGeometry, Ya as RGBA_S3TC_DXT5_Format, Ys as WebGLRenderTarget, Yt as DepthStencilFormat, Zn as InstancedBufferGeometry, Zr as Material, _i as MirroredRepeatWrapping, _r as LatheGeometry, a as WebGLCubeRenderTarget, aa as PlaneGeometry, ai as Mesh, ao as RGB_S3TC_DXT1_Format, ar as InterleavedBufferAttribute, cr as InterpolateDiscrete, cs as TOUCH, ct as Color, di as MeshNormalMaterial, do as Raycaster, ds as Texture, ei as MathUtils, fi as MeshPhongMaterial, fo as RectAreaLight, fs as TextureLoader, gn as EventDispatcher$1, gs as TorusGeometry, gt as ConeGeometry, hi as MeshToonMaterial, hn as Euler, ht as CompressedTextureLoader, i as UniformsLib, ia as Plane, io as RGB_PVRTC_4BPPV1_Format, ir as InterleavedBuffer, jo as Shape, js as UnsignedByteType, ko as ShaderMaterial, kr as LineBasicMaterial, la as Points, li as MeshLambertMaterial, ln as EllipseCurve, lo as RawShaderMaterial, lr as InterpolateLinear, lt as ColorKeyframeTrack, ma as PropertyBinding, mi as MeshStandardMaterial, mt as CompressedTexture, n as ShaderChunk, na as Path, ni as Matrix3, no as RGB_ETC2_Format, o as WebGLRenderer, oi as MeshBasicMaterial, on as DynamicDrawUsage, or as Interpolant, ot as ClampToEdgeWrapping, pi as MeshPhysicalMaterial, po as RedFormat, qo as Sprite, qt as DefaultLoadingManager, r as ShaderLib, ra as PerspectiveCamera, ri as Matrix4, ro as RGB_PVRTC_2BPPV1_Format, sa as PointLight, si as MeshDepthMaterial, so as RGFormat, st as Clock, to as RGB_ETC1_Format, ts as StereoCamera, tt as CanvasTexture, ua as PointsMaterial, uo as Ray, va as Quaternion, vn as ExtrudeGeometry, vo as RepeatWrapping, vs as Triangle$1, wi as NearestMipmapLinearFilter, ws as Uint16BufferAttribute, wt as CubeTexture, x as AnimationClip, xi as NearestFilter, xn as Float32BufferAttribute, y as AmbientLight, ya as QuaternionKeyframeTrack, yn as FileLoader, za as RGBA_ASTC_6x6_Format, zn as Group, zr as LinearMipmapLinearFilter } from "./three.module-DxhMWCDR.js"; //#region node_modules/three-stdlib/loaders/MD2Loader.js var _normalData = [ [ -.525731, 0, .850651 ], [ -.442863, .238856, .864188 ], [ -.295242, 0, .955423 ], [ -.309017, .5, .809017 ], [ -.16246, .262866, .951056 ], [ 0, 0, 1 ], [ 0, .850651, .525731 ], [ -.147621, .716567, .681718 ], [ .147621, .716567, .681718 ], [ 0, .525731, .850651 ], [ .309017, .5, .809017 ], [ .525731, 0, .850651 ], [ .295242, 0, .955423 ], [ .442863, .238856, .864188 ], [ .16246, .262866, .951056 ], [ -.681718, .147621, .716567 ], [ -.809017, .309017, .5 ], [ -.587785, .425325, .688191 ], [ -.850651, .525731, 0 ], [ -.864188, .442863, .238856 ], [ -.716567, .681718, .147621 ], [ -.688191, .587785, .425325 ], [ -.5, .809017, .309017 ], [ -.238856, .864188, .442863 ], [ -.425325, .688191, .587785 ], [ -.716567, .681718, -.147621 ], [ -.5, .809017, -.309017 ], [ -.525731, .850651, 0 ], [ 0, .850651, -.525731 ], [ -.238856, .864188, -.442863 ], [ 0, .955423, -.295242 ], [ -.262866, .951056, -.16246 ], [ 0, 1, 0 ], [ 0, .955423, .295242 ], [ -.262866, .951056, .16246 ], [ .238856, .864188, .442863 ], [ .262866, .951056, .16246 ], [ .5, .809017, .309017 ], [ .238856, .864188, -.442863 ], [ .262866, .951056, -.16246 ], [ .5, .809017, -.309017 ], [ .850651, .525731, 0 ], [ .716567, .681718, .147621 ], [ .716567, .681718, -.147621 ], [ .525731, .850651, 0 ], [ .425325, .688191, .587785 ], [ .864188, .442863, .238856 ], [ .688191, .587785, .425325 ], [ .809017, .309017, .5 ], [ .681718, .147621, .716567 ], [ .587785, .425325, .688191 ], [ .955423, .295242, 0 ], [ 1, 0, 0 ], [ .951056, .16246, .262866 ], [ .850651, -.525731, 0 ], [ .955423, -.295242, 0 ], [ .864188, -.442863, .238856 ], [ .951056, -.16246, .262866 ], [ .809017, -.309017, .5 ], [ .681718, -.147621, .716567 ], [ .850651, 0, .525731 ], [ .864188, .442863, -.238856 ], [ .809017, .309017, -.5 ], [ .951056, .16246, -.262866 ], [ .525731, 0, -.850651 ], [ .681718, .147621, -.716567 ], [ .681718, -.147621, -.716567 ], [ .850651, 0, -.525731 ], [ .809017, -.309017, -.5 ], [ .864188, -.442863, -.238856 ], [ .951056, -.16246, -.262866 ], [ .147621, .716567, -.681718 ], [ .309017, .5, -.809017 ], [ .425325, .688191, -.587785 ], [ .442863, .238856, -.864188 ], [ .587785, .425325, -.688191 ], [ .688191, .587785, -.425325 ], [ -.147621, .716567, -.681718 ], [ -.309017, .5, -.809017 ], [ 0, .525731, -.850651 ], [ -.525731, 0, -.850651 ], [ -.442863, .238856, -.864188 ], [ -.295242, 0, -.955423 ], [ -.16246, .262866, -.951056 ], [ 0, 0, -1 ], [ .295242, 0, -.955423 ], [ .16246, .262866, -.951056 ], [ -.442863, -.238856, -.864188 ], [ -.309017, -.5, -.809017 ], [ -.16246, -.262866, -.951056 ], [ 0, -.850651, -.525731 ], [ -.147621, -.716567, -.681718 ], [ .147621, -.716567, -.681718 ], [ 0, -.525731, -.850651 ], [ .309017, -.5, -.809017 ], [ .442863, -.238856, -.864188 ], [ .16246, -.262866, -.951056 ], [ .238856, -.864188, -.442863 ], [ .5, -.809017, -.309017 ], [ .425325, -.688191, -.587785 ], [ .716567, -.681718, -.147621 ], [ .688191, -.587785, -.425325 ], [ .587785, -.425325, -.688191 ], [ 0, -.955423, -.295242 ], [ 0, -1, 0 ], [ .262866, -.951056, -.16246 ], [ 0, -.850651, .525731 ], [ 0, -.955423, .295242 ], [ .238856, -.864188, .442863 ], [ .262866, -.951056, .16246 ], [ .5, -.809017, .309017 ], [ .716567, -.681718, .147621 ], [ .525731, -.850651, 0 ], [ -.238856, -.864188, -.442863 ], [ -.5, -.809017, -.309017 ], [ -.262866, -.951056, -.16246 ], [ -.850651, -.525731, 0 ], [ -.716567, -.681718, -.147621 ], [ -.716567, -.681718, .147621 ], [ -.525731, -.850651, 0 ], [ -.5, -.809017, .309017 ], [ -.238856, -.864188, .442863 ], [ -.262866, -.951056, .16246 ], [ -.864188, -.442863, .238856 ], [ -.809017, -.309017, .5 ], [ -.688191, -.587785, .425325 ], [ -.681718, -.147621, .716567 ], [ -.442863, -.238856, .864188 ], [ -.587785, -.425325, .688191 ], [ -.309017, -.5, .809017 ], [ -.147621, -.716567, .681718 ], [ -.425325, -.688191, .587785 ], [ -.16246, -.262866, .951056 ], [ .442863, -.238856, .864188 ], [ .16246, -.262866, .951056 ], [ .309017, -.5, .809017 ], [ .147621, -.716567, .681718 ], [ 0, -.525731, .850651 ], [ .425325, -.688191, .587785 ], [ .587785, -.425325, .688191 ], [ .688191, -.587785, .425325 ], [ -.955423, .295242, 0 ], [ -.951056, .16246, .262866 ], [ -1, 0, 0 ], [ -.850651, 0, .525731 ], [ -.955423, -.295242, 0 ], [ -.951056, -.16246, .262866 ], [ -.864188, .442863, -.238856 ], [ -.951056, .16246, -.262866 ], [ -.809017, .309017, -.5 ], [ -.864188, -.442863, -.238856 ], [ -.951056, -.16246, -.262866 ], [ -.809017, -.309017, -.5 ], [ -.681718, .147621, -.716567 ], [ -.681718, -.147621, -.716567 ], [ -.850651, 0, -.525731 ], [ -.688191, .587785, -.425325 ], [ -.587785, .425325, -.688191 ], [ -.425325, .688191, -.587785 ], [ -.425325, -.688191, -.587785 ], [ -.587785, -.425325, -.688191 ], [ -.688191, -.587785, -.425325 ] ]; var MD2Loader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(buffer) { try { onLoad(scope.parse(buffer)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(buffer) { const data = new DataView(buffer); const header = {}; const headerNames = [ "ident", "version", "skinwidth", "skinheight", "framesize", "num_skins", "num_vertices", "num_st", "num_tris", "num_glcmds", "num_frames", "offset_skins", "offset_st", "offset_tris", "offset_frames", "offset_glcmds", "offset_end" ]; for (let i = 0; i < headerNames.length; i++) header[headerNames[i]] = data.getInt32(i * 4, true); if (header.ident !== 844121161 || header.version !== 8) { console.error("Not a valid MD2 file"); return; } if (header.offset_end !== data.byteLength) { console.error("Corrupted MD2 file"); return; } const geometry = new BufferGeometry(); const uvsTemp = []; let offset = header.offset_st; for (let i = 0, l = header.num_st; i < l; i++) { const u = data.getInt16(offset + 0, true); const v = data.getInt16(offset + 2, true); uvsTemp.push(u / header.skinwidth, 1 - v / header.skinheight); offset += 4; } offset = header.offset_tris; const vertexIndices = []; const uvIndices = []; for (let i = 0, l = header.num_tris; i < l; i++) { vertexIndices.push(data.getUint16(offset + 0, true), data.getUint16(offset + 2, true), data.getUint16(offset + 4, true)); uvIndices.push(data.getUint16(offset + 6, true), data.getUint16(offset + 8, true), data.getUint16(offset + 10, true)); offset += 12; } const translation = new Vector3(); const scale = new Vector3(); const string = []; const frames = []; offset = header.offset_frames; for (let i = 0, l = header.num_frames; i < l; i++) { scale.set(data.getFloat32(offset + 0, true), data.getFloat32(offset + 4, true), data.getFloat32(offset + 8, true)); translation.set(data.getFloat32(offset + 12, true), data.getFloat32(offset + 16, true), data.getFloat32(offset + 20, true)); offset += 24; for (let j = 0; j < 16; j++) { const character = data.getUint8(offset + j, true); if (character === 0) break; string[j] = character; } const frame = { name: String.fromCharCode.apply(null, string), vertices: [], normals: [] }; offset += 16; for (let j = 0; j < header.num_vertices; j++) { let x = data.getUint8(offset++, true); let y = data.getUint8(offset++, true); let z = data.getUint8(offset++, true); const n = _normalData[data.getUint8(offset++, true)]; x = x * scale.x + translation.x; y = y * scale.y + translation.y; z = z * scale.z + translation.z; frame.vertices.push(x, z, y); frame.normals.push(n[0], n[2], n[1]); } frames.push(frame); } const positions = []; const normals = []; const uvs = []; const verticesTemp = frames[0].vertices; const normalsTemp = frames[0].normals; for (let i = 0, l = vertexIndices.length; i < l; i++) { let stride = vertexIndices[i] * 3; const x = verticesTemp[stride]; const y = verticesTemp[stride + 1]; const z = verticesTemp[stride + 2]; positions.push(x, y, z); const nx = normalsTemp[stride]; const ny = normalsTemp[stride + 1]; const nz = normalsTemp[stride + 2]; normals.push(nx, ny, nz); stride = uvIndices[i] * 2; const u = uvsTemp[stride]; const v = uvsTemp[stride + 1]; uvs.push(u, v); } geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); const morphPositions = []; const morphNormals = []; for (let i = 0, l = frames.length; i < l; i++) { const frame = frames[i]; const attributeName = frame.name; if (frame.vertices.length > 0) { const positions2 = []; for (let j = 0, jl = vertexIndices.length; j < jl; j++) { const stride = vertexIndices[j] * 3; const x = frame.vertices[stride]; const y = frame.vertices[stride + 1]; const z = frame.vertices[stride + 2]; positions2.push(x, y, z); } const positionAttribute = new Float32BufferAttribute(positions2, 3); positionAttribute.name = attributeName; morphPositions.push(positionAttribute); } if (frame.normals.length > 0) { const normals2 = []; for (let j = 0, jl = vertexIndices.length; j < jl; j++) { const stride = vertexIndices[j] * 3; const nx = frame.normals[stride]; const ny = frame.normals[stride + 1]; const nz = frame.normals[stride + 2]; normals2.push(nx, ny, nz); } const normalAttribute = new Float32BufferAttribute(normals2, 3); normalAttribute.name = attributeName; morphNormals.push(normalAttribute); } } geometry.morphAttributes.position = morphPositions; geometry.morphAttributes.normal = morphNormals; geometry.morphTargetsRelative = false; geometry.animations = AnimationClip.CreateClipsFromMorphTargetSequences(frames, 10); return geometry; } }; //#endregion //#region node_modules/three-stdlib/misc/MorphBlendMesh.js var MorphBlendMesh = class extends Mesh { constructor(geometry, material) { super(geometry, material); this.animationsMap = {}; this.animationsList = []; const numFrames = Object.keys(this.morphTargetDictionary).length; const name = "__default"; const startFrame = 0; const endFrame = numFrames - 1; const fps = numFrames / 1; this.createAnimation(name, startFrame, endFrame, fps); this.setAnimationWeight(name, 1); } createAnimation(name, start, end, fps) { const animation = { start, end, length: end - start + 1, fps, duration: (end - start) / fps, lastFrame: 0, currentFrame: 0, active: false, time: 0, direction: 1, weight: 1, directionBackwards: false, mirroredLoop: false }; this.animationsMap[name] = animation; this.animationsList.push(animation); } autoCreateAnimations(fps) { const pattern = /([a-z]+)_?(\d+)/i; let firstAnimation; const frameRanges = {}; let i = 0; for (const key in this.morphTargetDictionary) { const chunks = key.match(pattern); if (chunks && chunks.length > 1) { const name = chunks[1]; if (!frameRanges[name]) frameRanges[name] = { start: Infinity, end: -Infinity }; const range = frameRanges[name]; if (i < range.start) range.start = i; if (i > range.end) range.end = i; if (!firstAnimation) firstAnimation = name; } i++; } for (const name in frameRanges) { const range = frameRanges[name]; this.createAnimation(name, range.start, range.end, fps); } this.firstAnimation = firstAnimation; } setAnimationDirectionForward(name) { const animation = this.animationsMap[name]; if (animation) { animation.direction = 1; animation.directionBackwards = false; } } setAnimationDirectionBackward(name) { const animation = this.animationsMap[name]; if (animation) { animation.direction = -1; animation.directionBackwards = true; } } setAnimationFPS(name, fps) { const animation = this.animationsMap[name]; if (animation) { animation.fps = fps; animation.duration = (animation.end - animation.start) / animation.fps; } } setAnimationDuration(name, duration) { const animation = this.animationsMap[name]; if (animation) { animation.duration = duration; animation.fps = (animation.end - animation.start) / animation.duration; } } setAnimationWeight(name, weight) { const animation = this.animationsMap[name]; if (animation) animation.weight = weight; } setAnimationTime(name, time) { const animation = this.animationsMap[name]; if (animation) animation.time = time; } getAnimationTime(name) { let time = 0; const animation = this.animationsMap[name]; if (animation) time = animation.time; return time; } getAnimationDuration(name) { let duration = -1; const animation = this.animationsMap[name]; if (animation) duration = animation.duration; return duration; } playAnimation(name) { const animation = this.animationsMap[name]; if (animation) { animation.time = 0; animation.active = true; } else console.warn("THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()"); } stopAnimation(name) { const animation = this.animationsMap[name]; if (animation) animation.active = false; } update(delta) { for (let i = 0, il = this.animationsList.length; i < il; i++) { const animation = this.animationsList[i]; if (!animation.active) continue; const frameTime = animation.duration / animation.length; animation.time += animation.direction * delta; if (animation.mirroredLoop) { if (animation.time > animation.duration || animation.time < 0) { animation.direction *= -1; if (animation.time > animation.duration) { animation.time = animation.duration; animation.directionBackwards = true; } if (animation.time < 0) { animation.time = 0; animation.directionBackwards = false; } } } else { animation.time = animation.time % animation.duration; if (animation.time < 0) animation.time += animation.duration; } const keyframe = animation.start + MathUtils.clamp(Math.floor(animation.time / frameTime), 0, animation.length - 1); const weight = animation.weight; if (keyframe !== animation.currentFrame) { this.morphTargetInfluences[animation.lastFrame] = 0; this.morphTargetInfluences[animation.currentFrame] = 1 * weight; this.morphTargetInfluences[keyframe] = 0; animation.lastFrame = animation.currentFrame; animation.currentFrame = keyframe; } let mix = animation.time % frameTime / frameTime; if (animation.directionBackwards) mix = 1 - mix; if (animation.currentFrame !== animation.lastFrame) { this.morphTargetInfluences[animation.currentFrame] = mix * weight; this.morphTargetInfluences[animation.lastFrame] = (1 - mix) * weight; } else this.morphTargetInfluences[animation.currentFrame] = weight; } } }; //#endregion //#region node_modules/three-stdlib/misc/MD2CharacterComplex.js var MD2CharacterComplex = class { constructor() { this.scale = 1; this.animationFPS = 6; this.transitionFrames = 15; this.maxSpeed = 275; this.maxReverseSpeed = -275; this.frontAcceleration = 600; this.backAcceleration = 600; this.frontDecceleration = 600; this.angularSpeed = 2.5; this.root = new Object3D(); this.meshBody = null; this.meshWeapon = null; this.controls = null; this.skinsBody = []; this.skinsWeapon = []; this.weapons = []; this.currentSkin = void 0; this.onLoadComplete = function() {}; this.meshes = []; this.animations = {}; this.loadCounter = 0; this.speed = 0; this.bodyOrientation = 0; this.walkSpeed = this.maxSpeed; this.crouchSpeed = this.maxSpeed * .5; this.activeAnimation = null; this.oldAnimation = null; } enableShadows(enable) { for (let i = 0; i < this.meshes.length; i++) { this.meshes[i].castShadow = enable; this.meshes[i].receiveShadow = enable; } } setVisible(enable) { for (let i = 0; i < this.meshes.length; i++) { this.meshes[i].visible = enable; this.meshes[i].visible = enable; } } shareParts(original) { this.animations = original.animations; this.walkSpeed = original.walkSpeed; this.crouchSpeed = original.crouchSpeed; this.skinsBody = original.skinsBody; this.skinsWeapon = original.skinsWeapon; const mesh = this._createPart(original.meshBody.geometry, this.skinsBody[0]); mesh.scale.set(this.scale, this.scale, this.scale); this.root.position.y = original.root.position.y; this.root.add(mesh); this.meshBody = mesh; this.meshes.push(mesh); for (let i = 0; i < original.weapons.length; i++) { const meshWeapon = this._createPart(original.weapons[i].geometry, this.skinsWeapon[i]); meshWeapon.scale.set(this.scale, this.scale, this.scale); meshWeapon.visible = false; meshWeapon.name = original.weapons[i].name; this.root.add(meshWeapon); this.weapons[i] = meshWeapon; this.meshWeapon = meshWeapon; this.meshes.push(meshWeapon); } } loadParts(config) { const scope = this; function loadTextures(baseUrl, textureUrls) { const textureLoader = new TextureLoader(); const textures = []; for (let i = 0; i < textureUrls.length; i++) { textures[i] = textureLoader.load(baseUrl + textureUrls[i], checkLoadingComplete); textures[i].mapping = 300; textures[i].name = textureUrls[i]; if ("colorSpace" in textures[i]) textures[i].colorSpace = "srgb"; else textures[i].encoding = 3001; } return textures; } function checkLoadingComplete() { scope.loadCounter -= 1; if (scope.loadCounter === 0) scope.onLoadComplete(); } this.animations = config.animations; this.walkSpeed = config.walkSpeed; this.crouchSpeed = config.crouchSpeed; this.loadCounter = config.weapons.length * 2 + config.skins.length + 1; const weaponsTextures = []; for (let i = 0; i < config.weapons.length; i++) weaponsTextures[i] = config.weapons[i][1]; this.skinsBody = loadTextures(config.baseUrl + "skins/", config.skins); this.skinsWeapon = loadTextures(config.baseUrl + "skins/", weaponsTextures); const loader = new MD2Loader(); loader.load(config.baseUrl + config.body, function(geo) { const boundingBox = new Box3(); boundingBox.setFromBufferAttribute(geo.attributes.position); scope.root.position.y = -scope.scale * boundingBox.min.y; const mesh = scope._createPart(geo, scope.skinsBody[0]); mesh.scale.set(scope.scale, scope.scale, scope.scale); scope.root.add(mesh); scope.meshBody = mesh; scope.meshes.push(mesh); checkLoadingComplete(); }); const generateCallback = function(index, name) { return function(geo) { const mesh = scope._createPart(geo, scope.skinsWeapon[index]); mesh.scale.set(scope.scale, scope.scale, scope.scale); mesh.visible = false; mesh.name = name; scope.root.add(mesh); scope.weapons[index] = mesh; scope.meshWeapon = mesh; scope.meshes.push(mesh); checkLoadingComplete(); }; }; for (let i = 0; i < config.weapons.length; i++) loader.load(config.baseUrl + config.weapons[i][0], generateCallback(i, config.weapons[i][0])); } setPlaybackRate(rate) { if (this.meshBody) this.meshBody.duration = this.meshBody.baseDuration / rate; if (this.meshWeapon) this.meshWeapon.duration = this.meshWeapon.baseDuration / rate; } setWireframe(wireframeEnabled) { if (wireframeEnabled) { if (this.meshBody) this.meshBody.material = this.meshBody.materialWireframe; if (this.meshWeapon) this.meshWeapon.material = this.meshWeapon.materialWireframe; } else { if (this.meshBody) this.meshBody.material = this.meshBody.materialTexture; if (this.meshWeapon) this.meshWeapon.material = this.meshWeapon.materialTexture; } } setSkin(index) { if (this.meshBody && this.meshBody.material.wireframe === false) { this.meshBody.material.map = this.skinsBody[index]; this.currentSkin = index; } } setWeapon(index) { for (let i = 0; i < this.weapons.length; i++) this.weapons[i].visible = false; const activeWeapon = this.weapons[index]; if (activeWeapon) { activeWeapon.visible = true; this.meshWeapon = activeWeapon; if (this.activeAnimation) { activeWeapon.playAnimation(this.activeAnimation); this.meshWeapon.setAnimationTime(this.activeAnimation, this.meshBody.getAnimationTime(this.activeAnimation)); } } } setAnimation(animationName) { if (animationName === this.activeAnimation || !animationName) return; if (this.meshBody) { this.meshBody.setAnimationWeight(animationName, 0); this.meshBody.playAnimation(animationName); this.oldAnimation = this.activeAnimation; this.activeAnimation = animationName; this.blendCounter = this.transitionFrames; } if (this.meshWeapon) { this.meshWeapon.setAnimationWeight(animationName, 0); this.meshWeapon.playAnimation(animationName); } } update(delta) { if (this.controls) this.updateMovementModel(delta); if (this.animations) { this.updateBehaviors(); this.updateAnimations(delta); } } updateAnimations(delta) { let mix = 1; if (this.blendCounter > 0) { mix = (this.transitionFrames - this.blendCounter) / this.transitionFrames; this.blendCounter -= 1; } if (this.meshBody) { this.meshBody.update(delta); this.meshBody.setAnimationWeight(this.activeAnimation, mix); this.meshBody.setAnimationWeight(this.oldAnimation, 1 - mix); } if (this.meshWeapon) { this.meshWeapon.update(delta); this.meshWeapon.setAnimationWeight(this.activeAnimation, mix); this.meshWeapon.setAnimationWeight(this.oldAnimation, 1 - mix); } } updateBehaviors() { const controls = this.controls; const animations = this.animations; let moveAnimation, idleAnimation; if (controls.crouch) { moveAnimation = animations["crouchMove"]; idleAnimation = animations["crouchIdle"]; } else { moveAnimation = animations["move"]; idleAnimation = animations["idle"]; } if (controls.jump) { moveAnimation = animations["jump"]; idleAnimation = animations["jump"]; } if (controls.attack) if (controls.crouch) { moveAnimation = animations["crouchAttack"]; idleAnimation = animations["crouchAttack"]; } else { moveAnimation = animations["attack"]; idleAnimation = animations["attack"]; } if (controls.moveForward || controls.moveBackward || controls.moveLeft || controls.moveRight) { if (this.activeAnimation !== moveAnimation) this.setAnimation(moveAnimation); } if (Math.abs(this.speed) < .2 * this.maxSpeed && !(controls.moveLeft || controls.moveRight || controls.moveForward || controls.moveBackward)) { if (this.activeAnimation !== idleAnimation) this.setAnimation(idleAnimation); } if (controls.moveForward) { if (this.meshBody) { this.meshBody.setAnimationDirectionForward(this.activeAnimation); this.meshBody.setAnimationDirectionForward(this.oldAnimation); } if (this.meshWeapon) { this.meshWeapon.setAnimationDirectionForward(this.activeAnimation); this.meshWeapon.setAnimationDirectionForward(this.oldAnimation); } } if (controls.moveBackward) { if (this.meshBody) { this.meshBody.setAnimationDirectionBackward(this.activeAnimation); this.meshBody.setAnimationDirectionBackward(this.oldAnimation); } if (this.meshWeapon) { this.meshWeapon.setAnimationDirectionBackward(this.activeAnimation); this.meshWeapon.setAnimationDirectionBackward(this.oldAnimation); } } } updateMovementModel(delta) { function exponentialEaseOut(k) { return k === 1 ? 1 : -Math.pow(2, -10 * k) + 1; } const controls = this.controls; if (controls.crouch) this.maxSpeed = this.crouchSpeed; else this.maxSpeed = this.walkSpeed; this.maxReverseSpeed = -this.maxSpeed; if (controls.moveForward) this.speed = MathUtils.clamp(this.speed + delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed); if (controls.moveBackward) this.speed = MathUtils.clamp(this.speed - delta * this.backAcceleration, this.maxReverseSpeed, this.maxSpeed); const dir = 1; if (controls.moveLeft) { this.bodyOrientation += delta * this.angularSpeed; this.speed = MathUtils.clamp(this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed); } if (controls.moveRight) { this.bodyOrientation -= delta * this.angularSpeed; this.speed = MathUtils.clamp(this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed); } if (!(controls.moveForward || controls.moveBackward)) if (this.speed > 0) { const k = exponentialEaseOut(this.speed / this.maxSpeed); this.speed = MathUtils.clamp(this.speed - k * delta * this.frontDecceleration, 0, this.maxSpeed); } else { const k = exponentialEaseOut(this.speed / this.maxReverseSpeed); this.speed = MathUtils.clamp(this.speed + k * delta * this.backAcceleration, this.maxReverseSpeed, 0); } const forwardDelta = this.speed * delta; this.root.position.x += Math.sin(this.bodyOrientation) * forwardDelta; this.root.position.z += Math.cos(this.bodyOrientation) * forwardDelta; this.root.rotation.y = this.bodyOrientation; } _createPart(geometry, skinMap) { const materialWireframe = new MeshLambertMaterial({ color: 16755200, wireframe: true, morphTargets: true, morphNormals: true }); const materialTexture = new MeshLambertMaterial({ color: 16777215, wireframe: false, map: skinMap, morphTargets: true, morphNormals: true }); const mesh = new MorphBlendMesh(geometry, materialTexture); mesh.rotation.y = -Math.PI / 2; mesh.materialTexture = materialTexture; mesh.materialWireframe = materialWireframe; mesh.autoCreateAnimations(this.animationFPS); return mesh; } }; //#endregion //#region node_modules/three-stdlib/math/ConvexHull.js var Visible = 0; var Deleted = 1; var _v1$5 = /* @__PURE__ */ new Vector3(); var _line3 = /* @__PURE__ */ new Line3(); var _plane$2 = /* @__PURE__ */ new Plane(); var _closestPoint$1 = /* @__PURE__ */ new Vector3(); var _triangle = /* @__PURE__ */ new Triangle$1(); var ConvexHull = class { constructor() { this.tolerance = -1; this.faces = []; this.newFaces = []; this.assigned = new VertexList(); this.unassigned = new VertexList(); this.vertices = []; } setFromPoints(points) { if (points.length >= 4) { this.makeEmpty(); for (let i = 0, l = points.length; i < l; i++) this.vertices.push(new VertexNode(points[i])); this.compute(); } return this; } setFromObject(object) { const points = []; object.updateMatrixWorld(true); object.traverse(function(node) { const geometry = node.geometry; if (geometry !== void 0) { const attribute = geometry.attributes.position; if (attribute !== void 0) for (let i = 0, l = attribute.count; i < l; i++) { const point = new Vector3(); point.fromBufferAttribute(attribute, i).applyMatrix4(node.matrixWorld); points.push(point); } } }); return this.setFromPoints(points); } containsPoint(point) { const faces = this.faces; for (let i = 0, l = faces.length; i < l; i++) if (faces[i].distanceToPoint(point) > this.tolerance) return false; return true; } intersectRay(ray, target) { const faces = this.faces; let tNear = -Infinity; let tFar = Infinity; for (let i = 0, l = faces.length; i < l; i++) { const face = faces[i]; const vN = face.distanceToPoint(ray.origin); const vD = face.normal.dot(ray.direction); if (vN > 0 && vD >= 0) return null; const t = vD !== 0 ? -vN / vD : 0; if (t <= 0) continue; if (vD > 0) tFar = Math.min(t, tFar); else tNear = Math.max(t, tNear); if (tNear > tFar) return null; } if (tNear !== -Infinity) ray.at(tNear, target); else ray.at(tFar, target); return target; } intersectsRay(ray) { return this.intersectRay(ray, _v1$5) !== null; } makeEmpty() { this.faces = []; this.vertices = []; return this; } addVertexToFace(vertex, face) { vertex.face = face; if (face.outside === null) this.assigned.append(vertex); else this.assigned.insertBefore(face.outside, vertex); face.outside = vertex; return this; } removeVertexFromFace(vertex, face) { if (vertex === face.outside) if (vertex.next !== null && vertex.next.face === face) face.outside = vertex.next; else face.outside = null; this.assigned.remove(vertex); return this; } removeAllVerticesFromFace(face) { if (face.outside !== null) { const start = face.outside; let end = face.outside; while (end.next !== null && end.next.face === face) end = end.next; this.assigned.removeSubList(start, end); start.prev = end.next = null; face.outside = null; return start; } } deleteFaceVertices(face, absorbingFace) { const faceVertices = this.removeAllVerticesFromFace(face); if (faceVertices !== void 0) if (absorbingFace === void 0) this.unassigned.appendChain(faceVertices); else { let vertex = faceVertices; do { const nextVertex = vertex.next; if (absorbingFace.distanceToPoint(vertex.point) > this.tolerance) this.addVertexToFace(vertex, absorbingFace); else this.unassigned.append(vertex); vertex = nextVertex; } while (vertex !== null); } return this; } resolveUnassignedPoints(newFaces) { if (this.unassigned.isEmpty() === false) { let vertex = this.unassigned.first(); do { const nextVertex = vertex.next; let maxDistance = this.tolerance; let maxFace = null; for (let i = 0; i < newFaces.length; i++) { const face = newFaces[i]; if (face.mark === Visible) { const distance = face.distanceToPoint(vertex.point); if (distance > maxDistance) { maxDistance = distance; maxFace = face; } if (maxDistance > 1e3 * this.tolerance) break; } } if (maxFace !== null) this.addVertexToFace(vertex, maxFace); vertex = nextVertex; } while (vertex !== null); } return this; } computeExtremes() { const min = new Vector3(); const max = new Vector3(); const minVertices = []; const maxVertices = []; for (let i = 0; i < 3; i++) minVertices[i] = maxVertices[i] = this.vertices[0]; min.copy(this.vertices[0].point); max.copy(this.vertices[0].point); for (let i = 0, l = this.vertices.length; i < l; i++) { const vertex = this.vertices[i]; const point = vertex.point; for (let j = 0; j < 3; j++) if (point.getComponent(j) < min.getComponent(j)) { min.setComponent(j, point.getComponent(j)); minVertices[j] = vertex; } for (let j = 0; j < 3; j++) if (point.getComponent(j) > max.getComponent(j)) { max.setComponent(j, point.getComponent(j)); maxVertices[j] = vertex; } } this.tolerance = 3 * Number.EPSILON * (Math.max(Math.abs(min.x), Math.abs(max.x)) + Math.max(Math.abs(min.y), Math.abs(max.y)) + Math.max(Math.abs(min.z), Math.abs(max.z))); return { min: minVertices, max: maxVertices }; } computeInitialHull() { const vertices = this.vertices; const extremes = this.computeExtremes(); const min = extremes.min; const max = extremes.max; let maxDistance = 0; let index = 0; for (let i = 0; i < 3; i++) { const distance = max[i].point.getComponent(i) - min[i].point.getComponent(i); if (distance > maxDistance) { maxDistance = distance; index = i; } } const v0 = min[index]; const v1 = max[index]; let v2; let v3; maxDistance = 0; _line3.set(v0.point, v1.point); for (let i = 0, l = this.vertices.length; i < l; i++) { const vertex = vertices[i]; if (vertex !== v0 && vertex !== v1) { _line3.closestPointToPoint(vertex.point, true, _closestPoint$1); const distance = _closestPoint$1.distanceToSquared(vertex.point); if (distance > maxDistance) { maxDistance = distance; v2 = vertex; } } } maxDistance = -1; _plane$2.setFromCoplanarPoints(v0.point, v1.point, v2.point); for (let i = 0, l = this.vertices.length; i < l; i++) { const vertex = vertices[i]; if (vertex !== v0 && vertex !== v1 && vertex !== v2) { const distance = Math.abs(_plane$2.distanceToPoint(vertex.point)); if (distance > maxDistance) { maxDistance = distance; v3 = vertex; } } } const faces = []; if (_plane$2.distanceToPoint(v3.point) < 0) { faces.push(Face$1.create(v0, v1, v2), Face$1.create(v3, v1, v0), Face$1.create(v3, v2, v1), Face$1.create(v3, v0, v2)); for (let i = 0; i < 3; i++) { const j = (i + 1) % 3; faces[i + 1].getEdge(2).setTwin(faces[0].getEdge(j)); faces[i + 1].getEdge(1).setTwin(faces[j + 1].getEdge(0)); } } else { faces.push(Face$1.create(v0, v2, v1), Face$1.create(v3, v0, v1), Face$1.create(v3, v1, v2), Face$1.create(v3, v2, v0)); for (let i = 0; i < 3; i++) { const j = (i + 1) % 3; faces[i + 1].getEdge(2).setTwin(faces[0].getEdge((3 - i) % 3)); faces[i + 1].getEdge(0).setTwin(faces[j + 1].getEdge(1)); } } for (let i = 0; i < 4; i++) this.faces.push(faces[i]); for (let i = 0, l = vertices.length; i < l; i++) { const vertex = vertices[i]; if (vertex !== v0 && vertex !== v1 && vertex !== v2 && vertex !== v3) { maxDistance = this.tolerance; let maxFace = null; for (let j = 0; j < 4; j++) { const distance = this.faces[j].distanceToPoint(vertex.point); if (distance > maxDistance) { maxDistance = distance; maxFace = this.faces[j]; } } if (maxFace !== null) this.addVertexToFace(vertex, maxFace); } } return this; } reindexFaces() { const activeFaces = []; for (let i = 0; i < this.faces.length; i++) { const face = this.faces[i]; if (face.mark === Visible) activeFaces.push(face); } this.faces = activeFaces; return this; } nextVertexToAdd() { if (this.assigned.isEmpty() === false) { let eyeVertex, maxDistance = 0; const eyeFace = this.assigned.first().face; let vertex = eyeFace.outside; do { const distance = eyeFace.distanceToPoint(vertex.point); if (distance > maxDistance) { maxDistance = distance; eyeVertex = vertex; } vertex = vertex.next; } while (vertex !== null && vertex.face === eyeFace); return eyeVertex; } } computeHorizon(eyePoint, crossEdge, face, horizon) { this.deleteFaceVertices(face); face.mark = Deleted; let edge; if (crossEdge === null) edge = crossEdge = face.getEdge(0); else edge = crossEdge.next; do { const twinEdge = edge.twin; const oppositeFace = twinEdge.face; if (oppositeFace.mark === Visible) if (oppositeFace.distanceToPoint(eyePoint) > this.tolerance) this.computeHorizon(eyePoint, twinEdge, oppositeFace, horizon); else horizon.push(edge); edge = edge.next; } while (edge !== crossEdge); return this; } addAdjoiningFace(eyeVertex, horizonEdge) { const face = Face$1.create(eyeVertex, horizonEdge.tail(), horizonEdge.head()); this.faces.push(face); face.getEdge(-1).setTwin(horizonEdge.twin); return face.getEdge(0); } addNewFaces(eyeVertex, horizon) { this.newFaces = []; let firstSideEdge = null; let previousSideEdge = null; for (let i = 0; i < horizon.length; i++) { const horizonEdge = horizon[i]; const sideEdge = this.addAdjoiningFace(eyeVertex, horizonEdge); if (firstSideEdge === null) firstSideEdge = sideEdge; else sideEdge.next.setTwin(previousSideEdge); this.newFaces.push(sideEdge.face); previousSideEdge = sideEdge; } firstSideEdge.next.setTwin(previousSideEdge); return this; } addVertexToHull(eyeVertex) { const horizon = []; this.unassigned.clear(); this.removeVertexFromFace(eyeVertex, eyeVertex.face); this.computeHorizon(eyeVertex.point, null, eyeVertex.face, horizon); this.addNewFaces(eyeVertex, horizon); this.resolveUnassignedPoints(this.newFaces); return this; } cleanup() { this.assigned.clear(); this.unassigned.clear(); this.newFaces = []; return this; } compute() { let vertex; this.computeInitialHull(); while ((vertex = this.nextVertexToAdd()) !== void 0) this.addVertexToHull(vertex); this.reindexFaces(); this.cleanup(); return this; } }; var Face$1 = /* @__PURE__ */ (() => { class Face2 { constructor() { this.normal = new Vector3(); this.midpoint = new Vector3(); this.area = 0; this.constant = 0; this.outside = null; this.mark = Visible; this.edge = null; } static create(a, b, c) { const face = new Face2(); const e0 = new HalfEdge(a, face); const e1 = new HalfEdge(b, face); const e2 = new HalfEdge(c, face); e0.next = e2.prev = e1; e1.next = e0.prev = e2; e2.next = e1.prev = e0; face.edge = e0; return face.compute(); } getEdge(i) { let edge = this.edge; while (i > 0) { edge = edge.next; i--; } while (i < 0) { edge = edge.prev; i++; } return edge; } compute() { const a = this.edge.tail(); const b = this.edge.head(); const c = this.edge.next.head(); _triangle.set(a.point, b.point, c.point); _triangle.getNormal(this.normal); _triangle.getMidpoint(this.midpoint); this.area = _triangle.getArea(); this.constant = this.normal.dot(this.midpoint); return this; } distanceToPoint(point) { return this.normal.dot(point) - this.constant; } } return Face2; })(); var HalfEdge = class { constructor(vertex, face) { this.vertex = vertex; this.prev = null; this.next = null; this.twin = null; this.face = face; } head() { return this.vertex; } tail() { return this.prev ? this.prev.vertex : null; } length() { const head = this.head(); const tail = this.tail(); if (tail !== null) return tail.point.distanceTo(head.point); return -1; } lengthSquared() { const head = this.head(); const tail = this.tail(); if (tail !== null) return tail.point.distanceToSquared(head.point); return -1; } setTwin(edge) { this.twin = edge; edge.twin = this; return this; } }; var VertexNode = class { constructor(point) { this.point = point; this.prev = null; this.next = null; this.face = null; } }; var VertexList = class { constructor() { this.head = null; this.tail = null; } first() { return this.head; } last() { return this.tail; } clear() { this.head = this.tail = null; return this; } insertBefore(target, vertex) { vertex.prev = target.prev; vertex.next = target; if (vertex.prev === null) this.head = vertex; else vertex.prev.next = vertex; target.prev = vertex; return this; } insertAfter(target, vertex) { vertex.prev = target; vertex.next = target.next; if (vertex.next === null) this.tail = vertex; else vertex.next.prev = vertex; target.next = vertex; return this; } append(vertex) { if (this.head === null) this.head = vertex; else this.tail.next = vertex; vertex.prev = this.tail; vertex.next = null; this.tail = vertex; return this; } appendChain(vertex) { if (this.head === null) this.head = vertex; else this.tail.next = vertex; vertex.prev = this.tail; while (vertex.next !== null) vertex = vertex.next; this.tail = vertex; return this; } remove(vertex) { if (vertex.prev === null) this.head = vertex.next; else vertex.prev.next = vertex.next; if (vertex.next === null) this.tail = vertex.prev; else vertex.next.prev = vertex.prev; return this; } removeSubList(a, b) { if (a.prev === null) this.head = b.next; else a.prev.next = b.next; if (b.next === null) this.tail = a.prev; else b.next.prev = a.prev; return this; } isEmpty() { return this.head === null; } }; //#endregion //#region node_modules/three-stdlib/geometries/ConvexGeometry.js var ConvexGeometry = class extends BufferGeometry { constructor(points = []) { super(); const vertices = []; const normals = []; const faces = new ConvexHull().setFromPoints(points).faces; for (let i = 0; i < faces.length; i++) { const face = faces[i]; let edge = face.edge; do { const point = edge.head().point; vertices.push(point.x, point.y, point.z); normals.push(face.normal.x, face.normal.y, face.normal.z); edge = edge.next; } while (edge !== face.edge); } this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); } }; //#endregion //#region node_modules/three-stdlib/misc/ConvexObjectBreaker.js var _v1$4 = /* @__PURE__ */ new Vector3(); var ConvexObjectBreaker = /* @__PURE__ */ (() => { class ConvexObjectBreaker2 { constructor(minSizeForBreak = 1.4, smallDelta = 1e-4) { this.minSizeForBreak = minSizeForBreak; this.smallDelta = smallDelta; this.tempLine1 = new Line3(); this.tempPlane1 = new Plane(); this.tempPlane2 = new Plane(); this.tempPlane_Cut = new Plane(); this.tempCM1 = new Vector3(); this.tempCM2 = new Vector3(); this.tempVector3 = new Vector3(); this.tempVector3_2 = new Vector3(); this.tempVector3_3 = new Vector3(); this.tempVector3_P0 = new Vector3(); this.tempVector3_P1 = new Vector3(); this.tempVector3_P2 = new Vector3(); this.tempVector3_N0 = new Vector3(); this.tempVector3_N1 = new Vector3(); this.tempVector3_AB = new Vector3(); this.tempVector3_CB = new Vector3(); this.tempResultObjects = { object1: null, object2: null }; this.segments = []; const n = 900; for (let i = 0; i < n; i++) this.segments[i] = false; } prepareBreakableObject(object, mass, velocity, angularVelocity, breakable) { const userData = object.userData; userData.mass = mass; userData.velocity = velocity.clone(); userData.angularVelocity = angularVelocity.clone(); userData.breakable = breakable; } subdivideByImpact(object, pointOfImpact, normal, maxRadialIterations, maxRandomIterations) { const debris = []; const tempPlane1 = this.tempPlane1; const tempPlane2 = this.tempPlane2; this.tempVector3.addVectors(pointOfImpact, normal); tempPlane1.setFromCoplanarPoints(pointOfImpact, object.position, this.tempVector3); const maxTotalIterations = maxRandomIterations + maxRadialIterations; const scope = this; function subdivideRadial(subObject, startAngle, endAngle, numIterations) { if (Math.random() < numIterations * .05 || numIterations > maxTotalIterations) { debris.push(subObject); return; } let angle = Math.PI; if (numIterations === 0) { tempPlane2.normal.copy(tempPlane1.normal); tempPlane2.constant = tempPlane1.constant; } else if (numIterations <= maxRadialIterations) { angle = (endAngle - startAngle) * (.2 + .6 * Math.random()) + startAngle; scope.tempVector3_2.copy(object.position).sub(pointOfImpact).applyAxisAngle(normal, angle).add(pointOfImpact); tempPlane2.setFromCoplanarPoints(pointOfImpact, scope.tempVector3, scope.tempVector3_2); } else { angle = (.5 * (numIterations & 1) + .2 * (2 - Math.random())) * Math.PI; scope.tempVector3_2.copy(pointOfImpact).sub(subObject.position).applyAxisAngle(normal, angle).add(subObject.position); scope.tempVector3_3.copy(normal).add(subObject.position); tempPlane2.setFromCoplanarPoints(subObject.position, scope.tempVector3_3, scope.tempVector3_2); } scope.cutByPlane(subObject, tempPlane2, scope.tempResultObjects); const obj1 = scope.tempResultObjects.object1; const obj2 = scope.tempResultObjects.object2; if (obj1) subdivideRadial(obj1, startAngle, angle, numIterations + 1); if (obj2) subdivideRadial(obj2, angle, endAngle, numIterations + 1); } subdivideRadial(object, 0, 2 * Math.PI, 0); return debris; } cutByPlane(object, plane, output) { const geometry = object.geometry; const coords = geometry.attributes.position.array; const normals = geometry.attributes.normal.array; const numPoints = coords.length / 3; let numFaces = numPoints / 3; let indices = geometry.getIndex(); if (indices) { indices = indices.array; numFaces = indices.length / 3; } function getVertexIndex(faceIdx, vert) { const idx = faceIdx * 3 + vert; return indices ? indices[idx] : idx; } const points1 = []; const points2 = []; const delta = this.smallDelta; const numPointPairs = numPoints * numPoints; for (let i = 0; i < numPointPairs; i++) this.segments[i] = false; const p0 = this.tempVector3_P0; const p1 = this.tempVector3_P1; const n0 = this.tempVector3_N0; const n1 = this.tempVector3_N1; for (let i = 0; i < numFaces - 1; i++) { const a1 = getVertexIndex(i, 0); const b1 = getVertexIndex(i, 1); const c1 = getVertexIndex(i, 2); n0.set(normals[a1], normals[a1] + 1, normals[a1] + 2); for (let j = i + 1; j < numFaces; j++) { const a2 = getVertexIndex(j, 0); const b2 = getVertexIndex(j, 1); const c2 = getVertexIndex(j, 2); n1.set(normals[a2], normals[a2] + 1, normals[a2] + 2); if (1 - n0.dot(n1) < delta) { if (a1 === a2 || a1 === b2 || a1 === c2) if (b1 === a2 || b1 === b2 || b1 === c2) { this.segments[a1 * numPoints + b1] = true; this.segments[b1 * numPoints + a1] = true; } else { this.segments[c1 * numPoints + a1] = true; this.segments[a1 * numPoints + c1] = true; } else if (b1 === a2 || b1 === b2 || b1 === c2) { this.segments[c1 * numPoints + b1] = true; this.segments[b1 * numPoints + c1] = true; } } } } const localPlane = this.tempPlane_Cut; object.updateMatrix(); ConvexObjectBreaker2.transformPlaneToLocalSpace(plane, object.matrix, localPlane); for (let i = 0; i < numFaces; i++) { const va = getVertexIndex(i, 0); const vb = getVertexIndex(i, 1); const vc = getVertexIndex(i, 2); for (let segment = 0; segment < 3; segment++) { const i0 = segment === 0 ? va : segment === 1 ? vb : vc; const i1 = segment === 0 ? vb : segment === 1 ? vc : va; if (this.segments[i0 * numPoints + i1]) continue; this.segments[i0 * numPoints + i1] = true; this.segments[i1 * numPoints + i0] = true; p0.set(coords[3 * i0], coords[3 * i0 + 1], coords[3 * i0 + 2]); p1.set(coords[3 * i1], coords[3 * i1 + 1], coords[3 * i1 + 2]); let mark0 = 0; let d = localPlane.distanceToPoint(p0); if (d > delta) { mark0 = 2; points2.push(p0.clone()); } else if (d < -delta) { mark0 = 1; points1.push(p0.clone()); } else { mark0 = 3; points1.push(p0.clone()); points2.push(p0.clone()); } let mark1 = 0; d = localPlane.distanceToPoint(p1); if (d > delta) { mark1 = 2; points2.push(p1.clone()); } else if (d < -delta) { mark1 = 1; points1.push(p1.clone()); } else { mark1 = 3; points1.push(p1.clone()); points2.push(p1.clone()); } if (mark0 === 1 && mark1 === 2 || mark0 === 2 && mark1 === 1) { this.tempLine1.start.copy(p0); this.tempLine1.end.copy(p1); let intersection = new Vector3(); intersection = localPlane.intersectLine(this.tempLine1, intersection); if (intersection === null) { console.error("Internal error: segment does not intersect plane."); output.segmentedObject1 = null; output.segmentedObject2 = null; return 0; } points1.push(intersection); points2.push(intersection.clone()); } } } const newMass = object.userData.mass * .5; this.tempCM1.set(0, 0, 0); let radius1 = 0; const numPoints1 = points1.length; if (numPoints1 > 0) { for (let i = 0; i < numPoints1; i++) this.tempCM1.add(points1[i]); this.tempCM1.divideScalar(numPoints1); for (let i = 0; i < numPoints1; i++) { const p = points1[i]; p.sub(this.tempCM1); radius1 = Math.max(radius1, p.x, p.y, p.z); } this.tempCM1.add(object.position); } this.tempCM2.set(0, 0, 0); let radius2 = 0; const numPoints2 = points2.length; if (numPoints2 > 0) { for (let i = 0; i < numPoints2; i++) this.tempCM2.add(points2[i]); this.tempCM2.divideScalar(numPoints2); for (let i = 0; i < numPoints2; i++) { const p = points2[i]; p.sub(this.tempCM2); radius2 = Math.max(radius2, p.x, p.y, p.z); } this.tempCM2.add(object.position); } let object1 = null; let object2 = null; let numObjects = 0; if (numPoints1 > 4) { object1 = new Mesh(new ConvexGeometry(points1), object.material); object1.position.copy(this.tempCM1); object1.quaternion.copy(object.quaternion); this.prepareBreakableObject(object1, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius1 > this.minSizeForBreak); numObjects++; } if (numPoints2 > 4) { object2 = new Mesh(new ConvexGeometry(points2), object.material); object2.position.copy(this.tempCM2); object2.quaternion.copy(object.quaternion); this.prepareBreakableObject(object2, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius2 > this.minSizeForBreak); numObjects++; } output.object1 = object1; output.object2 = object2; return numObjects; } static transformFreeVector(v, m) { const x = v.x, y = v.y, z = v.z; const e = m.elements; v.x = e[0] * x + e[4] * y + e[8] * z; v.y = e[1] * x + e[5] * y + e[9] * z; v.z = e[2] * x + e[6] * y + e[10] * z; return v; } static transformFreeVectorInverse(v, m) { const x = v.x, y = v.y, z = v.z; const e = m.elements; v.x = e[0] * x + e[1] * y + e[2] * z; v.y = e[4] * x + e[5] * y + e[6] * z; v.z = e[8] * x + e[9] * y + e[10] * z; return v; } static transformTiedVectorInverse(v, m) { const x = v.x, y = v.y, z = v.z; const e = m.elements; v.x = e[0] * x + e[1] * y + e[2] * z - e[12]; v.y = e[4] * x + e[5] * y + e[6] * z - e[13]; v.z = e[8] * x + e[9] * y + e[10] * z - e[14]; return v; } static transformPlaneToLocalSpace(plane, m, resultPlane) { resultPlane.normal.copy(plane.normal); resultPlane.constant = plane.constant; const referencePoint = ConvexObjectBreaker2.transformTiedVectorInverse(plane.coplanarPoint(_v1$4), m); ConvexObjectBreaker2.transformFreeVectorInverse(resultPlane.normal, m); resultPlane.constant = -referencePoint.dot(resultPlane.normal); } } return ConvexObjectBreaker2; })(); //#endregion //#region node_modules/three-stdlib/misc/GPUComputationRenderer.js var GPUComputationRenderer = class { constructor(sizeX, sizeY, renderer) { this.variables = []; this.currentTextureIndex = 0; let dataType = FloatType; const scene = new Scene(); const camera = new Camera(); camera.position.z = 1; const passThruUniforms = { passThruTexture: { value: null } }; const passThruShader = createShaderMaterial(getPassThroughFragmentShader(), passThruUniforms); const mesh = new Mesh(new PlaneGeometry(2, 2), passThruShader); scene.add(mesh); this.setDataType = function(type) { dataType = type; return this; }; this.addVariable = function(variableName, computeFragmentShader, initialValueTexture) { const variable = { name: variableName, initialValueTexture, material: this.createShaderMaterial(computeFragmentShader), dependencies: null, renderTargets: [], wrapS: null, wrapT: null, minFilter: NearestFilter, magFilter: NearestFilter }; this.variables.push(variable); return variable; }; this.setVariableDependencies = function(variable, dependencies) { variable.dependencies = dependencies; }; this.init = function() { if (renderer.capabilities.isWebGL2 === false && renderer.extensions.has("OES_texture_float") === false) return "No OES_texture_float support for float textures."; if (renderer.capabilities.maxVertexTextures === 0) return "No support for vertex shader textures."; for (let i = 0; i < this.variables.length; i++) { const variable = this.variables[i]; variable.renderTargets[0] = this.createRenderTarget(sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter); variable.renderTargets[1] = this.createRenderTarget(sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter); this.renderTexture(variable.initialValueTexture, variable.renderTargets[0]); this.renderTexture(variable.initialValueTexture, variable.renderTargets[1]); const material = variable.material; const uniforms = material.uniforms; if (variable.dependencies !== null) for (let d = 0; d < variable.dependencies.length; d++) { const depVar = variable.dependencies[d]; if (depVar.name !== variable.name) { let found = false; for (let j = 0; j < this.variables.length; j++) if (depVar.name === this.variables[j].name) { found = true; break; } if (!found) return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name; } uniforms[depVar.name] = { value: null }; material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader; } } this.currentTextureIndex = 0; return null; }; this.compute = function() { const currentTextureIndex = this.currentTextureIndex; const nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0; for (let i = 0, il = this.variables.length; i < il; i++) { const variable = this.variables[i]; if (variable.dependencies !== null) { const uniforms = variable.material.uniforms; for (let d = 0, dl = variable.dependencies.length; d < dl; d++) { const depVar = variable.dependencies[d]; uniforms[depVar.name].value = depVar.renderTargets[currentTextureIndex].texture; } } this.doRenderTarget(variable.material, variable.renderTargets[nextTextureIndex]); } this.currentTextureIndex = nextTextureIndex; }; this.getCurrentRenderTarget = function(variable) { return variable.renderTargets[this.currentTextureIndex]; }; this.getAlternateRenderTarget = function(variable) { return variable.renderTargets[this.currentTextureIndex === 0 ? 1 : 0]; }; this.dispose = function() { mesh.geometry.dispose(); mesh.material.dispose(); const variables = this.variables; for (let i = 0; i < variables.length; i++) { const variable = variables[i]; if (variable.initialValueTexture) variable.initialValueTexture.dispose(); const renderTargets = variable.renderTargets; for (let j = 0; j < renderTargets.length; j++) renderTargets[j].dispose(); } }; function addResolutionDefine(materialShader) { materialShader.defines.resolution = "vec2( " + sizeX.toFixed(1) + ", " + sizeY.toFixed(1) + " )"; } this.addResolutionDefine = addResolutionDefine; function createShaderMaterial(computeFragmentShader, uniforms) { uniforms = uniforms || {}; const material = new ShaderMaterial({ uniforms, vertexShader: getPassThroughVertexShader(), fragmentShader: computeFragmentShader }); addResolutionDefine(material); return material; } this.createShaderMaterial = createShaderMaterial; this.createRenderTarget = function(sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter) { sizeXTexture = sizeXTexture || sizeX; sizeYTexture = sizeYTexture || sizeY; wrapS = wrapS || 1001; wrapT = wrapT || 1001; minFilter = minFilter || 1003; magFilter = magFilter || 1003; return new WebGLRenderTarget(sizeXTexture, sizeYTexture, { wrapS, wrapT, minFilter, magFilter, format: RGBAFormat, type: dataType, depthBuffer: false }); }; this.createTexture = function() { const texture = new DataTexture(new Float32Array(sizeX * sizeY * 4), sizeX, sizeY, RGBAFormat, FloatType); texture.needsUpdate = true; return texture; }; this.renderTexture = function(input, output) { passThruUniforms.passThruTexture.value = input; this.doRenderTarget(passThruShader, output); passThruUniforms.passThruTexture.value = null; }; this.doRenderTarget = function(material, output) { const currentRenderTarget = renderer.getRenderTarget(); const currentXrEnabled = renderer.xr.enabled; const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; const currentOutputColorSpace = renderer.outputColorSpace; const currentToneMapping = renderer.toneMapping; renderer.xr.enabled = false; renderer.shadowMap.autoUpdate = false; if ("outputColorSpace" in renderer) renderer.outputColorSpace = "srgb-linear"; else renderer.encoding = 3e3; renderer.toneMapping = 0; mesh.material = material; renderer.setRenderTarget(output); renderer.render(scene, camera); mesh.material = passThruShader; renderer.xr.enabled = currentXrEnabled; renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; renderer.outputColorSpace = currentOutputColorSpace; renderer.toneMapping = currentToneMapping; renderer.setRenderTarget(currentRenderTarget); }; function getPassThroughVertexShader() { return "void main() {\n\n gl_Position = vec4( position, 1.0 );\n\n}\n"; } function getPassThroughFragmentShader() { return "uniform sampler2D passThruTexture;\n\nvoid main() {\n\n vec2 uv = gl_FragCoord.xy / resolution.xy;\n\n gl_FragColor = texture2D( passThruTexture, uv );\n\n}\n"; } } }; //#endregion //#region node_modules/three-stdlib/misc/Gyroscope.js var _translationObject = /* @__PURE__ */ new Vector3(); var _quaternionObject = /* @__PURE__ */ new Quaternion(); var _scaleObject = /* @__PURE__ */ new Vector3(); var _translationWorld = /* @__PURE__ */ new Vector3(); var _quaternionWorld = /* @__PURE__ */ new Quaternion(); var _scaleWorld = /* @__PURE__ */ new Vector3(); var Gyroscope = class extends Object3D { constructor() { super(); } updateMatrixWorld(force) { this.matrixAutoUpdate && this.updateMatrix(); if (this.matrixWorldNeedsUpdate || force) { if (this.parent !== null) { this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); this.matrixWorld.decompose(_translationWorld, _quaternionWorld, _scaleWorld); this.matrix.decompose(_translationObject, _quaternionObject, _scaleObject); this.matrixWorld.compose(_translationWorld, _quaternionObject, _scaleWorld); } else this.matrixWorld.copy(this.matrix); this.matrixWorldNeedsUpdate = false; force = true; } for (let i = 0, l = this.children.length; i < l; i++) this.children[i].updateMatrixWorld(force); } }; //#endregion //#region node_modules/three-stdlib/misc/MorphAnimMesh.js var MorphAnimMesh = class extends Mesh { constructor(geometry, material) { super(geometry, material); this.type = "MorphAnimMesh"; this.mixer = new AnimationMixer(this); this.activeAction = null; } setDirectionForward() { this.mixer.timeScale = 1; } setDirectionBackward() { this.mixer.timeScale = -1; } playAnimation(label, fps) { if (this.activeAction) { this.activeAction.stop(); this.activeAction = null; } const clip = AnimationClip.findByName(this, label); if (clip) { const action = this.mixer.clipAction(clip); action.timeScale = clip.tracks.length * fps / clip.duration; this.activeAction = action.play(); } else throw new Error("THREE.MorphAnimMesh: animations[" + label + "] undefined in .playAnimation()"); } updateAnimation(delta) { this.mixer.update(delta); } copy(source, recursive) { super.copy(source, recursive); this.mixer = new AnimationMixer(this); return this; } }; //#endregion //#region node_modules/three-stdlib/misc/RollerCoaster.js var RollerCoasterGeometry = class extends BufferGeometry { constructor(curve, divisions) { super(); const vertices = []; const normals = []; const colors = []; const color1 = [ 1, 1, 1 ]; const color2 = [ 1, 1, 0 ]; const up = new Vector3(0, 1, 0); const forward = new Vector3(); const right = new Vector3(); const quaternion = new Quaternion(); const prevQuaternion = new Quaternion(); prevQuaternion.setFromAxisAngle(up, Math.PI / 2); const point = new Vector3(); const prevPoint = new Vector3(); prevPoint.copy(curve.getPointAt(0)); const step = [ new Vector3(-.225, 0, 0), new Vector3(0, -.05, 0), new Vector3(0, -.175, 0), new Vector3(0, -.05, 0), new Vector3(.225, 0, 0), new Vector3(0, -.175, 0) ]; const PI2 = Math.PI * 2; let sides = 5; const tube1 = []; for (let i = 0; i < sides; i++) { const angle = i / sides * PI2; tube1.push(new Vector3(Math.sin(angle) * .06, Math.cos(angle) * .06, 0)); } sides = 6; const tube2 = []; for (let i = 0; i < sides; i++) { const angle = i / sides * PI2; tube2.push(new Vector3(Math.sin(angle) * .025, Math.cos(angle) * .025, 0)); } const vector = new Vector3(); const normal = new Vector3(); function drawShape(shape, color) { normal.set(0, 0, -1).applyQuaternion(quaternion); for (let j = 0; j < shape.length; j++) { vector.copy(shape[j]); vector.applyQuaternion(quaternion); vector.add(point); vertices.push(vector.x, vector.y, vector.z); normals.push(normal.x, normal.y, normal.z); colors.push(color[0], color[1], color[2]); } normal.set(0, 0, 1).applyQuaternion(quaternion); for (let j = shape.length - 1; j >= 0; j--) { vector.copy(shape[j]); vector.applyQuaternion(quaternion); vector.add(point); vertices.push(vector.x, vector.y, vector.z); normals.push(normal.x, normal.y, normal.z); colors.push(color[0], color[1], color[2]); } } const vector1 = new Vector3(); const vector2 = new Vector3(); const vector3 = new Vector3(); const vector4 = new Vector3(); const normal1 = new Vector3(); const normal2 = new Vector3(); const normal3 = new Vector3(); const normal4 = new Vector3(); function extrudeShape(shape, offset2, color) { for (let j = 0, jl = shape.length; j < jl; j++) { const point1 = shape[j]; const point2 = shape[(j + 1) % jl]; vector1.copy(point1).add(offset2); vector1.applyQuaternion(quaternion); vector1.add(point); vector2.copy(point2).add(offset2); vector2.applyQuaternion(quaternion); vector2.add(point); vector3.copy(point2).add(offset2); vector3.applyQuaternion(prevQuaternion); vector3.add(prevPoint); vector4.copy(point1).add(offset2); vector4.applyQuaternion(prevQuaternion); vector4.add(prevPoint); vertices.push(vector1.x, vector1.y, vector1.z); vertices.push(vector2.x, vector2.y, vector2.z); vertices.push(vector4.x, vector4.y, vector4.z); vertices.push(vector2.x, vector2.y, vector2.z); vertices.push(vector3.x, vector3.y, vector3.z); vertices.push(vector4.x, vector4.y, vector4.z); normal1.copy(point1); normal1.applyQuaternion(quaternion); normal1.normalize(); normal2.copy(point2); normal2.applyQuaternion(quaternion); normal2.normalize(); normal3.copy(point2); normal3.applyQuaternion(prevQuaternion); normal3.normalize(); normal4.copy(point1); normal4.applyQuaternion(prevQuaternion); normal4.normalize(); normals.push(normal1.x, normal1.y, normal1.z); normals.push(normal2.x, normal2.y, normal2.z); normals.push(normal4.x, normal4.y, normal4.z); normals.push(normal2.x, normal2.y, normal2.z); normals.push(normal3.x, normal3.y, normal3.z); normals.push(normal4.x, normal4.y, normal4.z); colors.push(color[0], color[1], color[2]); colors.push(color[0], color[1], color[2]); colors.push(color[0], color[1], color[2]); colors.push(color[0], color[1], color[2]); colors.push(color[0], color[1], color[2]); colors.push(color[0], color[1], color[2]); } } const offset = new Vector3(); for (let i = 1; i <= divisions; i++) { point.copy(curve.getPointAt(i / divisions)); up.set(0, 1, 0); forward.subVectors(point, prevPoint).normalize(); right.crossVectors(up, forward).normalize(); up.crossVectors(forward, right); const angle = Math.atan2(forward.x, forward.z); quaternion.setFromAxisAngle(up, angle); if (i % 2 === 0) drawShape(step, color2); extrudeShape(tube1, offset.set(0, -.125, 0), color2); extrudeShape(tube2, offset.set(.2, 0, 0), color1); extrudeShape(tube2, offset.set(-.2, 0, 0), color1); prevPoint.copy(point); prevQuaternion.copy(quaternion); } this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3)); this.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3)); this.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3)); } }; var RollerCoasterLiftersGeometry = class extends BufferGeometry { constructor(curve, divisions) { super(); const vertices = []; const normals = []; const quaternion = new Quaternion(); const up = new Vector3(0, 1, 0); const point = new Vector3(); const tangent = new Vector3(); const tube1 = [ new Vector3(0, .05, -.05), new Vector3(0, .05, .05), new Vector3(0, -.05, 0) ]; const tube2 = [ new Vector3(-.05, 0, .05), new Vector3(-.05, 0, -.05), new Vector3(.05, 0, 0) ]; const tube3 = [ new Vector3(.05, 0, -.05), new Vector3(.05, 0, .05), new Vector3(-.05, 0, 0) ]; const vector1 = new Vector3(); const vector2 = new Vector3(); const vector3 = new Vector3(); const vector4 = new Vector3(); const normal1 = new Vector3(); const normal2 = new Vector3(); const normal3 = new Vector3(); const normal4 = new Vector3(); function extrudeShape(shape, fromPoint2, toPoint2) { for (let j = 0, jl = shape.length; j < jl; j++) { const point1 = shape[j]; const point2 = shape[(j + 1) % jl]; vector1.copy(point1); vector1.applyQuaternion(quaternion); vector1.add(fromPoint2); vector2.copy(point2); vector2.applyQuaternion(quaternion); vector2.add(fromPoint2); vector3.copy(point2); vector3.applyQuaternion(quaternion); vector3.add(toPoint2); vector4.copy(point1); vector4.applyQuaternion(quaternion); vector4.add(toPoint2); vertices.push(vector1.x, vector1.y, vector1.z); vertices.push(vector2.x, vector2.y, vector2.z); vertices.push(vector4.x, vector4.y, vector4.z); vertices.push(vector2.x, vector2.y, vector2.z); vertices.push(vector3.x, vector3.y, vector3.z); vertices.push(vector4.x, vector4.y, vector4.z); normal1.copy(point1); normal1.applyQuaternion(quaternion); normal1.normalize(); normal2.copy(point2); normal2.applyQuaternion(quaternion); normal2.normalize(); normal3.copy(point2); normal3.applyQuaternion(quaternion); normal3.normalize(); normal4.copy(point1); normal4.applyQuaternion(quaternion); normal4.normalize(); normals.push(normal1.x, normal1.y, normal1.z); normals.push(normal2.x, normal2.y, normal2.z); normals.push(normal4.x, normal4.y, normal4.z); normals.push(normal2.x, normal2.y, normal2.z); normals.push(normal3.x, normal3.y, normal3.z); normals.push(normal4.x, normal4.y, normal4.z); } } const fromPoint = new Vector3(); const toPoint = new Vector3(); for (let i = 1; i <= divisions; i++) { point.copy(curve.getPointAt(i / divisions)); tangent.copy(curve.getTangentAt(i / divisions)); const angle = Math.atan2(tangent.x, tangent.z); quaternion.setFromAxisAngle(up, angle); if (point.y > 10) { fromPoint.set(-.75, -.35, 0); fromPoint.applyQuaternion(quaternion); fromPoint.add(point); toPoint.set(.75, -.35, 0); toPoint.applyQuaternion(quaternion); toPoint.add(point); extrudeShape(tube1, fromPoint, toPoint); fromPoint.set(-.7, -.3, 0); fromPoint.applyQuaternion(quaternion); fromPoint.add(point); toPoint.set(-.7, -point.y, 0); toPoint.applyQuaternion(quaternion); toPoint.add(point); extrudeShape(tube2, fromPoint, toPoint); fromPoint.set(.7, -.3, 0); fromPoint.applyQuaternion(quaternion); fromPoint.add(point); toPoint.set(.7, -point.y, 0); toPoint.applyQuaternion(quaternion); toPoint.add(point); extrudeShape(tube3, fromPoint, toPoint); } else { fromPoint.set(0, -.2, 0); fromPoint.applyQuaternion(quaternion); fromPoint.add(point); toPoint.set(0, -point.y, 0); toPoint.applyQuaternion(quaternion); toPoint.add(point); extrudeShape(tube3, fromPoint, toPoint); } } this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3)); this.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3)); } }; var RollerCoasterShadowGeometry = class extends BufferGeometry { constructor(curve, divisions) { super(); const vertices = []; const up = new Vector3(0, 1, 0); const forward = new Vector3(); const quaternion = new Quaternion(); const prevQuaternion = new Quaternion(); prevQuaternion.setFromAxisAngle(up, Math.PI / 2); const point = new Vector3(); const prevPoint = new Vector3(); prevPoint.copy(curve.getPointAt(0)); prevPoint.y = 0; const vector1 = new Vector3(); const vector2 = new Vector3(); const vector3 = new Vector3(); const vector4 = new Vector3(); for (let i = 1; i <= divisions; i++) { point.copy(curve.getPointAt(i / divisions)); point.y = 0; forward.subVectors(point, prevPoint); const angle = Math.atan2(forward.x, forward.z); quaternion.setFromAxisAngle(up, angle); vector1.set(-.3, 0, 0); vector1.applyQuaternion(quaternion); vector1.add(point); vector2.set(.3, 0, 0); vector2.applyQuaternion(quaternion); vector2.add(point); vector3.set(.3, 0, 0); vector3.applyQuaternion(prevQuaternion); vector3.add(prevPoint); vector4.set(-.3, 0, 0); vector4.applyQuaternion(prevQuaternion); vector4.add(prevPoint); vertices.push(vector1.x, vector1.y, vector1.z); vertices.push(vector2.x, vector2.y, vector2.z); vertices.push(vector4.x, vector4.y, vector4.z); vertices.push(vector2.x, vector2.y, vector2.z); vertices.push(vector3.x, vector3.y, vector3.z); vertices.push(vector4.x, vector4.y, vector4.z); prevPoint.copy(point); prevQuaternion.copy(quaternion); } this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3)); } }; var SkyGeometry = class extends BufferGeometry { constructor() { super(); const vertices = []; for (let i = 0; i < 100; i++) { const x = Math.random() * 800 - 400; const y = Math.random() * 50 + 50; const z = Math.random() * 800 - 400; const size = Math.random() * 40 + 20; vertices.push(x - size, y, z - size); vertices.push(x + size, y, z - size); vertices.push(x - size, y, z + size); vertices.push(x + size, y, z - size); vertices.push(x + size, y, z + size); vertices.push(x - size, y, z + size); } this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3)); } }; var TreesGeometry = class extends BufferGeometry { constructor(landscape) { super(); const vertices = []; const colors = []; const raycaster = new Raycaster(); raycaster.ray.direction.set(0, -1, 0); const _color = new Color(); for (let i = 0; i < 2e3; i++) { const x = Math.random() * 500 - 250; const z = Math.random() * 500 - 250; raycaster.ray.origin.set(x, 50, z); const intersections = raycaster.intersectObject(landscape); if (intersections.length === 0) continue; const y = intersections[0].point.y; const height = Math.random() * 5 + .5; let angle = Math.random() * Math.PI * 2; vertices.push(x + Math.sin(angle), y, z + Math.cos(angle)); vertices.push(x, y + height, z); vertices.push(x + Math.sin(angle + Math.PI), y, z + Math.cos(angle + Math.PI)); angle += Math.PI / 2; vertices.push(x + Math.sin(angle), y, z + Math.cos(angle)); vertices.push(x, y + height, z); vertices.push(x + Math.sin(angle + Math.PI), y, z + Math.cos(angle + Math.PI)); const random = Math.random() * .1; for (let j = 0; j < 6; j++) { _color.setRGB(.2 + random, .4 + random, 0, "srgb"); colors.push(_color.r, _color.g, _color.b); } } this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3)); this.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3)); } }; //#endregion //#region node_modules/three-stdlib/misc/Timer.js var __defProp$59 = Object.defineProperty; var __defNormalProp$59 = (obj, key, value) => key in obj ? __defProp$59(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$59 = (obj, key, value) => { __defNormalProp$59(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Timer = class { constructor() { __publicField$59(this, "_previousTime"); __publicField$59(this, "_currentTime"); __publicField$59(this, "_delta"); __publicField$59(this, "_elapsed"); __publicField$59(this, "_timescale"); __publicField$59(this, "_useFixedDelta"); __publicField$59(this, "_fixedDelta"); __publicField$59(this, "_usePageVisibilityAPI"); __publicField$59(this, "_pageVisibilityHandler"); this._previousTime = 0; this._currentTime = 0; this._delta = 0; this._elapsed = 0; this._timescale = 1; this._useFixedDelta = false; this._fixedDelta = 16.67; this._usePageVisibilityAPI = typeof document !== "undefined" && document.hidden !== void 0; } connect() { if (this._usePageVisibilityAPI) { this._pageVisibilityHandler = handleVisibilityChange.bind(this); document.addEventListener("visibilitychange", this._pageVisibilityHandler, false); } return this; } dispose() { if (this._usePageVisibilityAPI && this._pageVisibilityHandler) document.removeEventListener("visibilitychange", this._pageVisibilityHandler); return this; } disableFixedDelta() { this._useFixedDelta = false; return this; } enableFixedDelta() { this._useFixedDelta = true; return this; } getDelta() { return this._delta / 1e3; } getElapsedTime() { return this._elapsed / 1e3; } getFixedDelta() { return this._fixedDelta / 1e3; } getTimescale() { return this._timescale; } reset() { this._currentTime = this._now(); return this; } setFixedDelta(fixedDelta) { this._fixedDelta = fixedDelta * 1e3; return this; } setTimescale(timescale) { this._timescale = timescale; return this; } update() { if (this._useFixedDelta === true) this._delta = this._fixedDelta; else { this._previousTime = this._currentTime; this._currentTime = this._now(); this._delta = this._currentTime - this._previousTime; } this._delta *= this._timescale; this._elapsed += this._delta; return this; } get elapsedTime() { return this.getElapsedTime(); } _now() { return (typeof performance === "undefined" ? Date : performance).now(); } }; function handleVisibilityChange() { if (document.hidden === false) this.reset(); } //#endregion //#region node_modules/three-stdlib/misc/WebGL.js var webGLAvailable, webGL2Available; function isWebGLAvailable() { var _a; if (webGLAvailable !== void 0) return webGLAvailable; try { let gl; const canvas = document.createElement("canvas"); webGLAvailable = !!(window.WebGLRenderingContext && (gl = canvas.getContext("webgl"))); if (gl) (_a = gl.getExtension("WEBGL_lose_context")) == null || _a.loseContext(); return webGLAvailable; } catch (e) { return webGLAvailable = false; } } function isWebGL2Available() { var _a; if (webGL2Available !== void 0) return webGL2Available; try { let gl; const canvas = document.createElement("canvas"); webGL2Available = !!(window.WebGL2RenderingContext && (gl = canvas.getContext("webgl2"))); if (gl) (_a = gl.getExtension("WEBGL_lose_context")) == null || _a.loseContext(); return webGL2Available; } catch (e) { return webGL2Available = false; } } function getWebGLErrorMessage() { return getErrorMessage(1); } function getWebGL2ErrorMessage() { return getErrorMessage(2); } function getErrorMessage(version) { const names = { 1: "WebGL", 2: "WebGL 2" }; const contexts = { 1: window.WebGLRenderingContext, 2: window.WebGL2RenderingContext }; const element = document.createElement("div"); element.id = "webglmessage"; element.style.fontFamily = "monospace"; element.style.fontSize = "13px"; element.style.fontWeight = "normal"; element.style.textAlign = "center"; element.style.background = "#fff"; element.style.color = "#000"; element.style.padding = "1.5em"; element.style.width = "400px"; element.style.margin = "5em auto 0"; let message = "Your $0 does not seem to support $1"; if (contexts[version]) message = message.replace("$0", "graphics card"); else message = message.replace("$0", "browser"); message = message.replace("$1", names[version]); element.innerHTML = message; return element; } //#endregion //#region node_modules/three-stdlib/misc/MD2Character.js var MD2Character = class { constructor() { this.scale = 1; this.animationFPS = 6; this.root = new Object3D(); this.meshBody = null; this.meshWeapon = null; this.skinsBody = []; this.skinsWeapon = []; this.weapons = []; this.activeAnimation = null; this.mixer = null; this.onLoadComplete = function() {}; this.loadCounter = 0; } loadParts(config) { const scope = this; function createPart(geometry, skinMap) { const materialWireframe = new MeshLambertMaterial({ color: 16755200, wireframe: true, morphTargets: true, morphNormals: true }); const materialTexture = new MeshLambertMaterial({ color: 16777215, wireframe: false, map: skinMap, morphTargets: true, morphNormals: true }); const mesh = new Mesh(geometry, materialTexture); mesh.rotation.y = -Math.PI / 2; mesh.castShadow = true; mesh.receiveShadow = true; mesh.materialTexture = materialTexture; mesh.materialWireframe = materialWireframe; return mesh; } function loadTextures(baseUrl, textureUrls) { const textureLoader = new TextureLoader(); const textures = []; for (let i = 0; i < textureUrls.length; i++) { textures[i] = textureLoader.load(baseUrl + textureUrls[i], checkLoadingComplete); textures[i].mapping = 300; textures[i].name = textureUrls[i]; if ("colorSpace" in textures[i]) textures[i].colorSpace = "srgb"; else textures[i].encoding = 3001; } return textures; } function checkLoadingComplete() { scope.loadCounter -= 1; if (scope.loadCounter === 0) scope.onLoadComplete(); } this.loadCounter = config.weapons.length * 2 + config.skins.length + 1; const weaponsTextures = []; for (let i = 0; i < config.weapons.length; i++) weaponsTextures[i] = config.weapons[i][1]; this.skinsBody = loadTextures(config.baseUrl + "skins/", config.skins); this.skinsWeapon = loadTextures(config.baseUrl + "skins/", weaponsTextures); const loader = new MD2Loader(); loader.load(config.baseUrl + config.body, function(geo) { const boundingBox = new Box3(); boundingBox.setFromBufferAttribute(geo.attributes.position); scope.root.position.y = -scope.scale * boundingBox.min.y; const mesh = createPart(geo, scope.skinsBody[0]); mesh.scale.set(scope.scale, scope.scale, scope.scale); scope.root.add(mesh); scope.meshBody = mesh; scope.meshBody.clipOffset = 0; scope.activeAnimationClipName = mesh.geometry.animations[0].name; scope.mixer = new AnimationMixer(mesh); checkLoadingComplete(); }); const generateCallback = function(index, name) { return function(geo) { const mesh = createPart(geo, scope.skinsWeapon[index]); mesh.scale.set(scope.scale, scope.scale, scope.scale); mesh.visible = false; mesh.name = name; scope.root.add(mesh); scope.weapons[index] = mesh; scope.meshWeapon = mesh; checkLoadingComplete(); }; }; for (let i = 0; i < config.weapons.length; i++) loader.load(config.baseUrl + config.weapons[i][0], generateCallback(i, config.weapons[i][0])); } setPlaybackRate(rate) { if (rate !== 0) this.mixer.timeScale = 1 / rate; else this.mixer.timeScale = 0; } setWireframe(wireframeEnabled) { if (wireframeEnabled) { if (this.meshBody) this.meshBody.material = this.meshBody.materialWireframe; if (this.meshWeapon) this.meshWeapon.material = this.meshWeapon.materialWireframe; } else { if (this.meshBody) this.meshBody.material = this.meshBody.materialTexture; if (this.meshWeapon) this.meshWeapon.material = this.meshWeapon.materialTexture; } } setSkin(index) { if (this.meshBody && this.meshBody.material.wireframe === false) this.meshBody.material.map = this.skinsBody[index]; } setWeapon(index) { for (let i = 0; i < this.weapons.length; i++) this.weapons[i].visible = false; const activeWeapon = this.weapons[index]; if (activeWeapon) { activeWeapon.visible = true; this.meshWeapon = activeWeapon; this.syncWeaponAnimation(); } } setAnimation(clipName) { if (this.meshBody) { if (this.meshBody.activeAction) { this.meshBody.activeAction.stop(); this.meshBody.activeAction = null; } const action = this.mixer.clipAction(clipName, this.meshBody); if (action) this.meshBody.activeAction = action.play(); } this.activeClipName = clipName; this.syncWeaponAnimation(); } syncWeaponAnimation() { const clipName = this.activeClipName; if (this.meshWeapon) { if (this.meshWeapon.activeAction) { this.meshWeapon.activeAction.stop(); this.meshWeapon.activeAction = null; } const action = this.mixer.clipAction(clipName, this.meshWeapon); if (action) this.meshWeapon.activeAction = action.syncWith(this.meshBody.activeAction).play(); } } update(delta) { if (this.mixer) this.mixer.update(delta); } }; //#endregion //#region node_modules/three-stdlib/misc/VolumeSlice.js var VolumeSlice = class { constructor(volume, index, axis) { const slice = this; this.volume = volume; index = index || 0; Object.defineProperty(this, "index", { get: function() { return index; }, set: function(value) { index = value; slice.geometryNeedsUpdate = true; return index; } }); this.axis = axis || "z"; this.canvas = document.createElement("canvas"); this.canvasBuffer = document.createElement("canvas"); this.updateGeometry(); const canvasMap = new Texture(this.canvas); canvasMap.minFilter = LinearFilter; canvasMap.wrapS = canvasMap.wrapT = ClampToEdgeWrapping; if ("colorSpace" in canvasMap) canvasMap.colorSpace = "srgb"; else canvasMap.encoding = 3001; const material = new MeshBasicMaterial({ map: canvasMap, side: 2, transparent: true }); this.mesh = new Mesh(this.geometry, material); this.mesh.matrixAutoUpdate = false; this.geometryNeedsUpdate = true; this.repaint(); } /** * @member {Function} repaint Refresh the texture and the geometry if geometryNeedsUpdate is set to true * @memberof VolumeSlice */ repaint() { if (this.geometryNeedsUpdate) this.updateGeometry(); const iLength = this.iLength, jLength = this.jLength, sliceAccess = this.sliceAccess, volume = this.volume, canvas = this.canvasBuffer, ctx = this.ctxBuffer; const imgData = ctx.getImageData(0, 0, iLength, jLength); const data = imgData.data; const volumeData = volume.data; const upperThreshold = volume.upperThreshold; const lowerThreshold = volume.lowerThreshold; const windowLow = volume.windowLow; const windowHigh = volume.windowHigh; let pixelCount = 0; if (volume.dataType === "label") for (let j = 0; j < jLength; j++) for (let i = 0; i < iLength; i++) { let label = volumeData[sliceAccess(i, j)]; label = label >= this.colorMap.length ? label % this.colorMap.length + 1 : label; const color = this.colorMap[label]; data[4 * pixelCount] = color >> 24 & 255; data[4 * pixelCount + 1] = color >> 16 & 255; data[4 * pixelCount + 2] = color >> 8 & 255; data[4 * pixelCount + 3] = color & 255; pixelCount++; } else for (let j = 0; j < jLength; j++) for (let i = 0; i < iLength; i++) { let value = volumeData[sliceAccess(i, j)]; let alpha = 255; alpha = upperThreshold >= value ? lowerThreshold <= value ? alpha : 0 : 0; value = Math.floor(255 * (value - windowLow) / (windowHigh - windowLow)); value = value > 255 ? 255 : value < 0 ? 0 : value | 0; data[4 * pixelCount] = value; data[4 * pixelCount + 1] = value; data[4 * pixelCount + 2] = value; data[4 * pixelCount + 3] = alpha; pixelCount++; } ctx.putImageData(imgData, 0, 0); this.ctx.drawImage(canvas, 0, 0, iLength, jLength, 0, 0, this.canvas.width, this.canvas.height); this.mesh.material.map.needsUpdate = true; } /** * @member {Function} Refresh the geometry according to axis and index * @see Volume.extractPerpendicularPlane * @memberof VolumeSlice */ updateGeometry() { const extracted = this.volume.extractPerpendicularPlane(this.axis, this.index); this.sliceAccess = extracted.sliceAccess; this.jLength = extracted.jLength; this.iLength = extracted.iLength; this.matrix = extracted.matrix; this.canvas.width = extracted.planeWidth; this.canvas.height = extracted.planeHeight; this.canvasBuffer.width = this.iLength; this.canvasBuffer.height = this.jLength; this.ctx = this.canvas.getContext("2d"); this.ctxBuffer = this.canvasBuffer.getContext("2d"); if (this.geometry) this.geometry.dispose(); this.geometry = new PlaneGeometry(extracted.planeWidth, extracted.planeHeight); if (this.mesh) { this.mesh.geometry = this.geometry; this.mesh.matrix.identity(); this.mesh.applyMatrix4(this.matrix); } this.geometryNeedsUpdate = false; } }; //#endregion //#region node_modules/three-stdlib/misc/TubePainter.js function TubePainter() { const BUFFER_SIZE = 1e6 * 3; const positions = new BufferAttribute(new Float32Array(BUFFER_SIZE), 3); positions.usage = DynamicDrawUsage; const normals = new BufferAttribute(new Float32Array(BUFFER_SIZE), 3); normals.usage = DynamicDrawUsage; const colors = new BufferAttribute(new Float32Array(BUFFER_SIZE), 3); colors.usage = DynamicDrawUsage; const geometry = new BufferGeometry(); geometry.setAttribute("position", positions); geometry.setAttribute("normal", normals); geometry.setAttribute("color", colors); geometry.drawRange.count = 0; const mesh = new Mesh(geometry, new MeshStandardMaterial({ vertexColors: true })); mesh.frustumCulled = false; function getPoints(size2) { const PI2 = Math.PI * 2; const sides = 10; const array = []; const radius = .01 * size2; for (let i = 0; i < sides; i++) { const angle = i / sides * PI2; array.push(new Vector3(Math.sin(angle) * radius, Math.cos(angle) * radius, 0)); } return array; } const vector1 = new Vector3(); const vector2 = new Vector3(); const vector3 = new Vector3(); const vector4 = new Vector3(); const color = new Color(16777215); let size = 1; function stroke(position1, position2, matrix12, matrix22) { if (position1.distanceToSquared(position2) === 0) return; let count2 = geometry.drawRange.count; const points = getPoints(size); for (let i = 0, il = points.length; i < il; i++) { const vertex1 = points[i]; const vertex2 = points[(i + 1) % il]; vector1.copy(vertex1).applyMatrix4(matrix22).add(position2); vector2.copy(vertex2).applyMatrix4(matrix22).add(position2); vector3.copy(vertex2).applyMatrix4(matrix12).add(position1); vector4.copy(vertex1).applyMatrix4(matrix12).add(position1); vector1.toArray(positions.array, (count2 + 0) * 3); vector2.toArray(positions.array, (count2 + 1) * 3); vector4.toArray(positions.array, (count2 + 2) * 3); vector2.toArray(positions.array, (count2 + 3) * 3); vector3.toArray(positions.array, (count2 + 4) * 3); vector4.toArray(positions.array, (count2 + 5) * 3); vector1.copy(vertex1).applyMatrix4(matrix22).normalize(); vector2.copy(vertex2).applyMatrix4(matrix22).normalize(); vector3.copy(vertex2).applyMatrix4(matrix12).normalize(); vector4.copy(vertex1).applyMatrix4(matrix12).normalize(); vector1.toArray(normals.array, (count2 + 0) * 3); vector2.toArray(normals.array, (count2 + 1) * 3); vector4.toArray(normals.array, (count2 + 2) * 3); vector2.toArray(normals.array, (count2 + 3) * 3); vector3.toArray(normals.array, (count2 + 4) * 3); vector4.toArray(normals.array, (count2 + 5) * 3); color.toArray(colors.array, (count2 + 0) * 3); color.toArray(colors.array, (count2 + 1) * 3); color.toArray(colors.array, (count2 + 2) * 3); color.toArray(colors.array, (count2 + 3) * 3); color.toArray(colors.array, (count2 + 4) * 3); color.toArray(colors.array, (count2 + 5) * 3); count2 += 6; } geometry.drawRange.count = count2; } const up = new Vector3(0, 1, 0); const point1 = new Vector3(); const point2 = new Vector3(); const matrix1 = new Matrix4(); const matrix2 = new Matrix4(); function moveTo(position) { point1.copy(position); matrix1.lookAt(point2, point1, up); point2.copy(position); matrix2.copy(matrix1); } function lineTo(position) { point1.copy(position); matrix1.lookAt(point2, point1, up); stroke(point1, point2, matrix1, matrix2); point2.copy(point1); matrix2.copy(matrix1); } function setSize(value) { size = value; } let count = 0; function update() { const start = count; const end = geometry.drawRange.count; if (start === end) return; positions.updateRange.offset = start * 3; positions.updateRange.count = (end - start) * 3; positions.needsUpdate = true; normals.updateRange.offset = start * 3; normals.updateRange.count = (end - start) * 3; normals.needsUpdate = true; colors.updateRange.offset = start * 3; colors.updateRange.count = (end - start) * 3; colors.needsUpdate = true; count = geometry.drawRange.count; } return { mesh, moveTo, lineTo, setSize, update }; } //#endregion //#region node_modules/three-stdlib/misc/Volume.js var Volume = class { constructor(xLength, yLength, zLength, type, arrayBuffer) { if (xLength !== void 0) { this.xLength = Number(xLength) || 1; this.yLength = Number(yLength) || 1; this.zLength = Number(zLength) || 1; this.axisOrder = [ "x", "y", "z" ]; switch (type) { case "Uint8": case "uint8": case "uchar": case "unsigned char": case "uint8_t": this.data = new Uint8Array(arrayBuffer); break; case "Int8": case "int8": case "signed char": case "int8_t": this.data = new Int8Array(arrayBuffer); break; case "Int16": case "int16": case "short": case "short int": case "signed short": case "signed short int": case "int16_t": this.data = new Int16Array(arrayBuffer); break; case "Uint16": case "uint16": case "ushort": case "unsigned short": case "unsigned short int": case "uint16_t": this.data = new Uint16Array(arrayBuffer); break; case "Int32": case "int32": case "int": case "signed int": case "int32_t": this.data = new Int32Array(arrayBuffer); break; case "Uint32": case "uint32": case "uint": case "unsigned int": case "uint32_t": this.data = new Uint32Array(arrayBuffer); break; case "longlong": case "long long": case "long long int": case "signed long long": case "signed long long int": case "int64": case "int64_t": case "ulonglong": case "unsigned long long": case "unsigned long long int": case "uint64": case "uint64_t": throw new Error("Error in Volume constructor : this type is not supported in JavaScript"); case "Float32": case "float32": case "float": this.data = new Float32Array(arrayBuffer); break; case "Float64": case "float64": case "double": this.data = new Float64Array(arrayBuffer); break; default: this.data = new Uint8Array(arrayBuffer); } if (this.data.length !== this.xLength * this.yLength * this.zLength) throw new Error("Error in Volume constructor, lengths are not matching arrayBuffer size"); } this.spacing = [ 1, 1, 1 ]; this.offset = [ 0, 0, 0 ]; this.matrix = new Matrix3(); this.matrix.identity(); let lowerThreshold = -Infinity; Object.defineProperty(this, "lowerThreshold", { get: function() { return lowerThreshold; }, set: function(value) { lowerThreshold = value; this.sliceList.forEach(function(slice) { slice.geometryNeedsUpdate = true; }); } }); let upperThreshold = Infinity; Object.defineProperty(this, "upperThreshold", { get: function() { return upperThreshold; }, set: function(value) { upperThreshold = value; this.sliceList.forEach(function(slice) { slice.geometryNeedsUpdate = true; }); } }); this.sliceList = []; this.segmentation = false; } /** * @member {Function} getData Shortcut for data[access(i,j,k)] * @memberof Volume * @param {number} i First coordinate * @param {number} j Second coordinate * @param {number} k Third coordinate * @returns {number} value in the data array */ getData(i, j, k) { return this.data[k * this.xLength * this.yLength + j * this.xLength + i]; } /** * @member {Function} access compute the index in the data array corresponding to the given coordinates in IJK system * @memberof Volume * @param {number} i First coordinate * @param {number} j Second coordinate * @param {number} k Third coordinate * @returns {number} index */ access(i, j, k) { return k * this.xLength * this.yLength + j * this.xLength + i; } /** * @member {Function} reverseAccess Retrieve the IJK coordinates of the voxel corresponding of the given index in the data * @memberof Volume * @param {number} index index of the voxel * @returns {Array} [x,y,z] */ reverseAccess(index) { const z = Math.floor(index / (this.yLength * this.xLength)); const y = Math.floor((index - z * this.yLength * this.xLength) / this.xLength); return [ index - z * this.yLength * this.xLength - y * this.xLength, y, z ]; } /** * @member {Function} map Apply a function to all the voxels, be careful, the value will be replaced * @memberof Volume * @param {Function} functionToMap A function to apply to every voxel, will be called with the following parameters : * value of the voxel * index of the voxel * the data (TypedArray) * @param {Object} context You can specify a context in which call the function, default if this Volume * @returns {Volume} this */ map(functionToMap, context) { const length = this.data.length; context = context || this; for (let i = 0; i < length; i++) this.data[i] = functionToMap.call(context, this.data[i], i, this.data); return this; } /** * @member {Function} extractPerpendicularPlane Compute the orientation of the slice and returns all the information relative to the geometry such as sliceAccess, the plane matrix (orientation and position in RAS coordinate) and the dimensions of the plane in both coordinate system. * @memberof Volume * @param {string} axis the normal axis to the slice 'x' 'y' or 'z' * @param {number} index the index of the slice * @returns {Object} an object containing all the usefull information on the geometry of the slice */ extractPerpendicularPlane(axis, RASIndex) { let firstSpacing, secondSpacing, positionOffset, IJKIndex; const axisInIJK = new Vector3(), firstDirection = new Vector3(), secondDirection = new Vector3(), planeMatrix = new Matrix4().identity(), volume = this; const dimensions = new Vector3(this.xLength, this.yLength, this.zLength); switch (axis) { case "x": axisInIJK.set(1, 0, 0); firstDirection.set(0, 0, -1); secondDirection.set(0, -1, 0); firstSpacing = this.spacing[this.axisOrder.indexOf("z")]; secondSpacing = this.spacing[this.axisOrder.indexOf("y")]; IJKIndex = new Vector3(RASIndex, 0, 0); planeMatrix.multiply(new Matrix4().makeRotationY(Math.PI / 2)); positionOffset = (volume.RASDimensions[0] - 1) / 2; planeMatrix.setPosition(new Vector3(RASIndex - positionOffset, 0, 0)); break; case "y": axisInIJK.set(0, 1, 0); firstDirection.set(1, 0, 0); secondDirection.set(0, 0, 1); firstSpacing = this.spacing[this.axisOrder.indexOf("x")]; secondSpacing = this.spacing[this.axisOrder.indexOf("z")]; IJKIndex = new Vector3(0, RASIndex, 0); planeMatrix.multiply(new Matrix4().makeRotationX(-Math.PI / 2)); positionOffset = (volume.RASDimensions[1] - 1) / 2; planeMatrix.setPosition(new Vector3(0, RASIndex - positionOffset, 0)); break; default: axisInIJK.set(0, 0, 1); firstDirection.set(1, 0, 0); secondDirection.set(0, -1, 0); firstSpacing = this.spacing[this.axisOrder.indexOf("x")]; secondSpacing = this.spacing[this.axisOrder.indexOf("y")]; IJKIndex = new Vector3(0, 0, RASIndex); positionOffset = (volume.RASDimensions[2] - 1) / 2; planeMatrix.setPosition(new Vector3(0, 0, RASIndex - positionOffset)); break; } let iLength, jLength; if (!this.segmentation) { firstDirection.applyMatrix4(volume.inverseMatrix).normalize(); secondDirection.applyMatrix4(volume.inverseMatrix).normalize(); axisInIJK.applyMatrix4(volume.inverseMatrix).normalize(); } firstDirection.arglet = "i"; secondDirection.arglet = "j"; iLength = Math.floor(Math.abs(firstDirection.dot(dimensions))); jLength = Math.floor(Math.abs(secondDirection.dot(dimensions))); const planeWidth = Math.abs(iLength * firstSpacing); const planeHeight = Math.abs(jLength * secondSpacing); IJKIndex = Math.abs(Math.round(IJKIndex.applyMatrix4(volume.inverseMatrix).dot(axisInIJK))); const base = [ new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1) ]; const iDirection = [ firstDirection, secondDirection, axisInIJK ].find(function(x) { return Math.abs(x.dot(base[0])) > .9; }); const jDirection = [ firstDirection, secondDirection, axisInIJK ].find(function(x) { return Math.abs(x.dot(base[1])) > .9; }); const kDirection = [ firstDirection, secondDirection, axisInIJK ].find(function(x) { return Math.abs(x.dot(base[2])) > .9; }); function sliceAccess(i, j) { const si = iDirection === axisInIJK ? IJKIndex : iDirection.arglet === "i" ? i : j; const sj = jDirection === axisInIJK ? IJKIndex : jDirection.arglet === "i" ? i : j; const sk = kDirection === axisInIJK ? IJKIndex : kDirection.arglet === "i" ? i : j; const accessI = iDirection.dot(base[0]) > 0 ? si : volume.xLength - 1 - si; const accessJ = jDirection.dot(base[1]) > 0 ? sj : volume.yLength - 1 - sj; const accessK = kDirection.dot(base[2]) > 0 ? sk : volume.zLength - 1 - sk; return volume.access(accessI, accessJ, accessK); } return { iLength, jLength, sliceAccess, matrix: planeMatrix, planeWidth, planeHeight }; } /** * @member {Function} extractSlice Returns a slice corresponding to the given axis and index * The coordinate are given in the Right Anterior Superior coordinate format * @memberof Volume * @param {string} axis the normal axis to the slice 'x' 'y' or 'z' * @param {number} index the index of the slice * @returns {VolumeSlice} the extracted slice */ extractSlice(axis, index) { const slice = new VolumeSlice(this, index, axis); this.sliceList.push(slice); return slice; } /** * @member {Function} repaintAllSlices Call repaint on all the slices extracted from this volume * @see VolumeSlice.repaint * @memberof Volume * @returns {Volume} this */ repaintAllSlices() { this.sliceList.forEach(function(slice) { slice.repaint(); }); return this; } /** * @member {Function} computeMinMax Compute the minimum and the maximum of the data in the volume * @memberof Volume * @returns {Array} [min,max] */ computeMinMax() { let min = Infinity; let max = -Infinity; const datasize = this.data.length; let i = 0; for (i = 0; i < datasize; i++) if (!isNaN(this.data[i])) { const value = this.data[i]; min = Math.min(min, value); max = Math.max(max, value); } this.min = min; this.max = max; return [min, max]; } }; //#endregion //#region node_modules/potpack/index.mjs function potpack(boxes) { let area = 0; let maxWidth = 0; for (const box of boxes) { area += box.w * box.h; maxWidth = Math.max(maxWidth, box.w); } boxes.sort((a, b) => b.h - a.h); const spaces = [{ x: 0, y: 0, w: Math.max(Math.ceil(Math.sqrt(area / .95)), maxWidth), h: Infinity }]; let width = 0; let height = 0; for (const box of boxes) for (let i = spaces.length - 1; i >= 0; i--) { const space = spaces[i]; if (box.w > space.w || box.h > space.h) continue; box.x = space.x; box.y = space.y; height = Math.max(height, box.y + box.h); width = Math.max(width, box.x + box.w); if (box.w === space.w && box.h === space.h) { const last = spaces.pop(); if (i < spaces.length) spaces[i] = last; } else if (box.h === space.h) { space.x += box.w; space.w -= box.w; } else if (box.w === space.w) { space.y += box.h; space.h -= box.h; } else { spaces.push({ x: space.x + box.w, y: space.y, w: space.w - box.w, h: box.h }); space.y += box.h; space.h -= box.h; } break; } return { w: width, h: height, fill: area / (width * height) || 0 }; } //#endregion //#region node_modules/three-stdlib/_polyfill/constants.js var version = /* @__PURE__ */ (() => parseInt("184".replace(/\D+/g, "")))(); //#endregion //#region node_modules/three-stdlib/_polyfill/uv1.js var UV1 = version >= 125 ? "uv1" : "uv2"; //#endregion //#region node_modules/three-stdlib/misc/ProgressiveLightmap.js var ProgressiveLightMap = class { constructor(renderer, res = 1024) { this.renderer = renderer; this.res = res; this.lightMapContainers = []; this.compiled = false; this.scene = new Scene(); this.scene.background = null; this.tinyTarget = new WebGLRenderTarget(1, 1); this.buffer1Active = false; this.firstUpdate = true; this.warned = false; const format = /(Android|iPad|iPhone|iPod)/g.test(navigator.userAgent) ? alfFloatType : FloatType; this.progressiveLightMap1 = new WebGLRenderTarget(this.res, this.res, { type: format }); this.progressiveLightMap2 = new WebGLRenderTarget(this.res, this.res, { type: format }); this.uvMat = new MeshPhongMaterial(); this.uvMat.uniforms = {}; this.uvMat.onBeforeCompile = (shader) => { shader.vertexShader = "#define USE_LIGHTMAP\n" + shader.vertexShader.slice(0, -1) + ` gl_Position = vec4((${UV1} - 0.5) * 2.0, 1.0, 1.0); }`; const bodyStart = shader.fragmentShader.indexOf("void main() {"); shader.fragmentShader = `varying vec2 v${UV1 === "uv1" ? UV1 : "Uv2"}; ` + shader.fragmentShader.slice(0, bodyStart) + " uniform sampler2D previousShadowMap;\n uniform float averagingWindow;\n" + shader.fragmentShader.slice(bodyStart - 1, -1) + ` vec3 texelOld = texture2D(previousShadowMap, v${UV1 === "uv1" ? UV1 : "Uv2"}).rgb; gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/averagingWindow); }`; shader.uniforms.previousShadowMap = { value: this.progressiveLightMap1.texture }; shader.uniforms.averagingWindow = { value: 100 }; this.uvMat.uniforms = shader.uniforms; this.uvMat.userData.shader = shader; this.compiled = true; }; } /** * Sets these objects' materials' lightmaps and modifies their uv1's. * @param {Object3D} objects An array of objects and lights to set up your lightmap. */ addObjectsToLightMap(objects) { this.uv_boxes = []; const padding = 3 / this.res; for (let ob = 0; ob < objects.length; ob++) { const object = objects[ob]; if (object.isLight) { this.scene.attach(object); continue; } if (!object.geometry.hasAttribute("uv")) { console.warn("All lightmap objects need UVs!"); continue; } if (this.blurringPlane == null) this._initializeBlurPlane(this.res, this.progressiveLightMap1); object.material.lightMap = this.progressiveLightMap2.texture; object.material.dithering = true; object.castShadow = true; object.receiveShadow = true; object.renderOrder = 1e3 + ob; this.uv_boxes.push({ w: 1 + padding * 2, h: 1 + padding * 2, index: ob }); this.lightMapContainers.push({ basicMat: object.material, object }); this.compiled = false; } const dimensions = potpack(this.uv_boxes); this.uv_boxes.forEach((box) => { const uv1 = objects[box.index].geometry.getAttribute("uv").clone(); for (let i = 0; i < uv1.array.length; i += uv1.itemSize) { uv1.array[i] = (uv1.array[i] + box.x + padding) / dimensions.w; uv1.array[i + 1] = (uv1.array[i + 1] + box.y + padding) / dimensions.h; } objects[box.index].geometry.setAttribute(UV1, uv1); objects[box.index].geometry.getAttribute(UV1).needsUpdate = true; }); } /** * This function renders each mesh one at a time into their respective surface maps * @param {Camera} camera Standard Rendering Camera * @param {number} blendWindow When >1, samples will accumulate over time. * @param {boolean} blurEdges Whether to fix UV Edges via blurring */ update(camera, blendWindow = 100, blurEdges = true) { if (this.blurringPlane == null) return; const oldTarget = this.renderer.getRenderTarget(); this.blurringPlane.visible = blurEdges; for (let l = 0; l < this.lightMapContainers.length; l++) { this.lightMapContainers[l].object.oldScene = this.lightMapContainers[l].object.parent; this.scene.attach(this.lightMapContainers[l].object); } if (this.firstUpdate) { this.renderer.setRenderTarget(this.tinyTarget); this.renderer.render(this.scene, camera); this.firstUpdate = false; } for (let l = 0; l < this.lightMapContainers.length; l++) { this.uvMat.uniforms.averagingWindow = { value: blendWindow }; this.lightMapContainers[l].object.material = this.uvMat; this.lightMapContainers[l].object.oldFrustumCulled = this.lightMapContainers[l].object.frustumCulled; this.lightMapContainers[l].object.frustumCulled = false; } const activeMap = this.buffer1Active ? this.progressiveLightMap1 : this.progressiveLightMap2; const inactiveMap = this.buffer1Active ? this.progressiveLightMap2 : this.progressiveLightMap1; this.renderer.setRenderTarget(activeMap); this.uvMat.uniforms.previousShadowMap = { value: inactiveMap.texture }; this.blurringPlane.material.uniforms.previousShadowMap = { value: inactiveMap.texture }; this.buffer1Active = !this.buffer1Active; this.renderer.render(this.scene, camera); for (let l = 0; l < this.lightMapContainers.length; l++) { this.lightMapContainers[l].object.frustumCulled = this.lightMapContainers[l].object.oldFrustumCulled; this.lightMapContainers[l].object.material = this.lightMapContainers[l].basicMat; this.lightMapContainers[l].object.oldScene.attach(this.lightMapContainers[l].object); } this.renderer.setRenderTarget(oldTarget); } /** DEBUG * Draw the lightmap in the main scene. Call this after adding the objects to it. * @param {boolean} visible Whether the debug plane should be visible * @param {Vector3} position Where the debug plane should be drawn */ showDebugLightmap(visible, position = void 0) { if (this.lightMapContainers.length == 0) { if (!this.warned) { console.warn("Call this after adding the objects!"); this.warned = true; } return; } if (this.labelMesh == null) { this.labelMaterial = new MeshBasicMaterial({ map: this.progressiveLightMap1.texture, side: 2 }); this.labelPlane = new PlaneGeometry(100, 100); this.labelMesh = new Mesh(this.labelPlane, this.labelMaterial); this.labelMesh.position.y = 250; this.lightMapContainers[0].object.parent.add(this.labelMesh); } if (position != void 0) this.labelMesh.position.copy(position); this.labelMesh.visible = visible; } /** * INTERNAL Creates the Blurring Plane * @param {number} res The square resolution of this object's lightMap. * @param {WebGLRenderTexture} lightMap The lightmap to initialize the plane with. */ _initializeBlurPlane(res, lightMap = null) { const blurMaterial = new MeshBasicMaterial(); blurMaterial.uniforms = { previousShadowMap: { value: null }, pixelOffset: { value: 1 / res }, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: 3 }; blurMaterial.onBeforeCompile = (shader) => { shader.vertexShader = "#define USE_UV\n" + shader.vertexShader.slice(0, -1) + " gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }"; const bodyStart = shader.fragmentShader.indexOf("void main() {"); shader.fragmentShader = "#define USE_UV\n" + shader.fragmentShader.slice(0, bodyStart) + " uniform sampler2D previousShadowMap;\n uniform float pixelOffset;\n" + shader.fragmentShader.slice(bodyStart - 1, -1) + ` gl_FragColor.rgb = ( texture2D(previousShadowMap, vUv + vec2( pixelOffset, 0.0 )).rgb + texture2D(previousShadowMap, vUv + vec2( 0.0 , pixelOffset)).rgb + texture2D(previousShadowMap, vUv + vec2( 0.0 , -pixelOffset)).rgb + texture2D(previousShadowMap, vUv + vec2(-pixelOffset, 0.0 )).rgb + texture2D(previousShadowMap, vUv + vec2( pixelOffset, pixelOffset)).rgb + texture2D(previousShadowMap, vUv + vec2(-pixelOffset, pixelOffset)).rgb + texture2D(previousShadowMap, vUv + vec2( pixelOffset, -pixelOffset)).rgb + texture2D(previousShadowMap, vUv + vec2(-pixelOffset, -pixelOffset)).rgb)/8.0; }`; shader.uniforms.previousShadowMap = { value: lightMap.texture }; shader.uniforms.pixelOffset = { value: .5 / res }; blurMaterial.uniforms = shader.uniforms; blurMaterial.userData.shader = shader; this.compiled = true; }; this.blurringPlane = new Mesh(new PlaneGeometry(1, 1), blurMaterial); this.blurringPlane.name = "Blurring Plane"; this.blurringPlane.frustumCulled = false; this.blurringPlane.renderOrder = 0; this.blurringPlane.material.depthWrite = false; this.scene.add(this.blurringPlane); } }; //#endregion //#region node_modules/three-stdlib/renderers/CSS2DRenderer.js var CSS2DObject = class extends Object3D { constructor(element = document.createElement("div")) { super(); this.isCSS2DObject = true; this.element = element; this.element.style.position = "absolute"; this.element.style.userSelect = "none"; this.element.setAttribute("draggable", false); this.center = new Vector2(.5, .5); this.addEventListener("removed", function() { this.traverse(function(object) { if (object.element instanceof Element && object.element.parentNode !== null) object.element.parentNode.removeChild(object.element); }); }); } copy(source, recursive) { super.copy(source, recursive); this.element = source.element.cloneNode(true); this.center = source.center; return this; } }; var _vector$4 = /* @__PURE__ */ new Vector3(); var _viewMatrix = /* @__PURE__ */ new Matrix4(); var _viewProjectionMatrix = /* @__PURE__ */ new Matrix4(); var _a$1 = /* @__PURE__ */ new Vector3(); var _b$1 = /* @__PURE__ */ new Vector3(); var CSS2DRenderer = class { constructor(parameters = {}) { const _this = this; let _width, _height; let _widthHalf, _heightHalf; const cache = { objects: /* @__PURE__ */ new WeakMap() }; const domElement = parameters.element !== void 0 ? parameters.element : document.createElement("div"); domElement.style.overflow = "hidden"; this.domElement = domElement; this.getSize = function() { return { width: _width, height: _height }; }; this.render = function(scene, camera) { if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); _viewMatrix.copy(camera.matrixWorldInverse); _viewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, _viewMatrix); renderObject(scene, scene, camera); zOrder(scene); }; this.setSize = function(width, height) { _width = width; _height = height; _widthHalf = _width / 2; _heightHalf = _height / 2; domElement.style.width = width + "px"; domElement.style.height = height + "px"; }; function renderObject(object, scene, camera) { if (object.isCSS2DObject) { _vector$4.setFromMatrixPosition(object.matrixWorld); _vector$4.applyMatrix4(_viewProjectionMatrix); const visible = object.visible === true && _vector$4.z >= -1 && _vector$4.z <= 1 && object.layers.test(camera.layers) === true; object.element.style.display = visible === true ? "" : "none"; if (visible === true) { object.onBeforeRender(_this, scene, camera); const element = object.element; element.style.transform = "translate(" + -100 * object.center.x + "%," + -100 * object.center.y + "%)translate(" + (_vector$4.x * _widthHalf + _widthHalf) + "px," + (-_vector$4.y * _heightHalf + _heightHalf) + "px)"; if (element.parentNode !== domElement) domElement.appendChild(element); object.onAfterRender(_this, scene, camera); } const objectData = { distanceToCameraSquared: getDistanceToSquared(camera, object) }; cache.objects.set(object, objectData); } for (let i = 0, l = object.children.length; i < l; i++) renderObject(object.children[i], scene, camera); } function getDistanceToSquared(object1, object2) { _a$1.setFromMatrixPosition(object1.matrixWorld); _b$1.setFromMatrixPosition(object2.matrixWorld); return _a$1.distanceToSquared(_b$1); } function filterAndFlatten(scene) { const result = []; scene.traverse(function(object) { if (object.isCSS2DObject) result.push(object); }); return result; } function zOrder(scene) { const sorted = filterAndFlatten(scene).sort(function(a, b) { if (a.renderOrder !== b.renderOrder) return b.renderOrder - a.renderOrder; return cache.objects.get(a).distanceToCameraSquared - cache.objects.get(b).distanceToCameraSquared; }); const zMax = sorted.length; for (let i = 0, l = sorted.length; i < l; i++) sorted[i].element.style.zIndex = zMax - i; } } }; //#endregion //#region node_modules/three-stdlib/renderers/CSS3DRenderer.js var _position$1 = /* @__PURE__ */ new Vector3(); var _quaternion$1 = /* @__PURE__ */ new Quaternion(); var _scale$1 = /* @__PURE__ */ new Vector3(); var CSS3DObject = class extends Object3D { constructor(element = document.createElement("div")) { super(); this.isCSS3DObject = true; this.element = element; this.element.style.position = "absolute"; this.element.style.pointerEvents = "auto"; this.element.style.userSelect = "none"; this.element.setAttribute("draggable", false); this.addEventListener("removed", function() { this.traverse(function(object) { if (object.element instanceof Element && object.element.parentNode !== null) object.element.parentNode.removeChild(object.element); }); }); } copy(source, recursive) { super.copy(source, recursive); this.element = source.element.cloneNode(true); return this; } }; var CSS3DSprite = class extends CSS3DObject { constructor(element) { super(element); this.isCSS3DSprite = true; this.rotation2D = 0; } copy(source, recursive) { super.copy(source, recursive); this.rotation2D = source.rotation2D; return this; } }; var _matrix$2 = /* @__PURE__ */ new Matrix4(); var _matrix2 = /* @__PURE__ */ new Matrix4(); var CSS3DRenderer = class { constructor(parameters = {}) { const _this = this; let _width, _height; let _widthHalf, _heightHalf; const cache = { camera: { style: "" }, objects: /* @__PURE__ */ new WeakMap() }; const domElement = parameters.element !== void 0 ? parameters.element : document.createElement("div"); domElement.style.overflow = "hidden"; this.domElement = domElement; const viewElement = document.createElement("div"); viewElement.style.transformOrigin = "0 0"; viewElement.style.pointerEvents = "none"; domElement.appendChild(viewElement); const cameraElement = document.createElement("div"); cameraElement.style.transformStyle = "preserve-3d"; viewElement.appendChild(cameraElement); this.getSize = function() { return { width: _width, height: _height }; }; this.render = function(scene, camera) { const fov = camera.projectionMatrix.elements[5] * _heightHalf; if (camera.view && camera.view.enabled) { viewElement.style.transform = `translate( ${-camera.view.offsetX * (_width / camera.view.width)}px, ${-camera.view.offsetY * (_height / camera.view.height)}px )`; viewElement.style.transform += `scale( ${camera.view.fullWidth / camera.view.width}, ${camera.view.fullHeight / camera.view.height} )`; } else viewElement.style.transform = ""; if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); let tx, ty; if (camera.isOrthographicCamera) { tx = -(camera.right + camera.left) / 2; ty = (camera.top + camera.bottom) / 2; } const scaleByViewOffset = camera.view && camera.view.enabled ? camera.view.height / camera.view.fullHeight : 1; const cameraCSSMatrix = camera.isOrthographicCamera ? `scale( ${scaleByViewOffset} )scale(` + fov + ")translate(" + epsilon(tx) + "px," + epsilon(ty) + "px)" + getCameraCSSMatrix(camera.matrixWorldInverse) : `scale( ${scaleByViewOffset} )translateZ(` + fov + "px)" + getCameraCSSMatrix(camera.matrixWorldInverse); const style = (camera.isPerspectiveCamera ? "perspective(" + fov + "px) " : "") + cameraCSSMatrix + "translate(" + _widthHalf + "px," + _heightHalf + "px)"; if (cache.camera.style !== style) { cameraElement.style.transform = style; cache.camera.style = style; } renderObject(scene, scene, camera); }; this.setSize = function(width, height) { _width = width; _height = height; _widthHalf = _width / 2; _heightHalf = _height / 2; domElement.style.width = width + "px"; domElement.style.height = height + "px"; viewElement.style.width = width + "px"; viewElement.style.height = height + "px"; cameraElement.style.width = width + "px"; cameraElement.style.height = height + "px"; }; function epsilon(value) { return Math.abs(value) < 1e-10 ? 0 : value; } function getCameraCSSMatrix(matrix) { const elements = matrix.elements; return "matrix3d(" + epsilon(elements[0]) + "," + epsilon(-elements[1]) + "," + epsilon(elements[2]) + "," + epsilon(elements[3]) + "," + epsilon(elements[4]) + "," + epsilon(-elements[5]) + "," + epsilon(elements[6]) + "," + epsilon(elements[7]) + "," + epsilon(elements[8]) + "," + epsilon(-elements[9]) + "," + epsilon(elements[10]) + "," + epsilon(elements[11]) + "," + epsilon(elements[12]) + "," + epsilon(-elements[13]) + "," + epsilon(elements[14]) + "," + epsilon(elements[15]) + ")"; } function getObjectCSSMatrix(matrix) { const elements = matrix.elements; return "translate(-50%,-50%)" + ("matrix3d(" + epsilon(elements[0]) + "," + epsilon(elements[1]) + "," + epsilon(elements[2]) + "," + epsilon(elements[3]) + "," + epsilon(-elements[4]) + "," + epsilon(-elements[5]) + "," + epsilon(-elements[6]) + "," + epsilon(-elements[7]) + "," + epsilon(elements[8]) + "," + epsilon(elements[9]) + "," + epsilon(elements[10]) + "," + epsilon(elements[11]) + "," + epsilon(elements[12]) + "," + epsilon(elements[13]) + "," + epsilon(elements[14]) + "," + epsilon(elements[15]) + ")"); } function renderObject(object, scene, camera, cameraCSSMatrix) { if (object.isCSS3DObject) { const visible = object.visible === true && object.layers.test(camera.layers) === true; object.element.style.display = visible === true ? "" : "none"; if (visible === true) { object.onBeforeRender(_this, scene, camera); let style; if (object.isCSS3DSprite) { _matrix$2.copy(camera.matrixWorldInverse); _matrix$2.transpose(); if (object.rotation2D !== 0) _matrix$2.multiply(_matrix2.makeRotationZ(object.rotation2D)); object.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1); _matrix$2.setPosition(_position$1); _matrix$2.scale(_scale$1); _matrix$2.elements[3] = 0; _matrix$2.elements[7] = 0; _matrix$2.elements[11] = 0; _matrix$2.elements[15] = 1; style = getObjectCSSMatrix(_matrix$2); } else style = getObjectCSSMatrix(object.matrixWorld); const element = object.element; const cachedObject = cache.objects.get(object); if (cachedObject === void 0 || cachedObject.style !== style) { element.style.transform = style; const objectData = { style }; cache.objects.set(object, objectData); } if (element.parentNode !== cameraElement) cameraElement.appendChild(element); object.onAfterRender(_this, scene, camera); } } for (let i = 0, l = object.children.length; i < l; i++) renderObject(object.children[i], scene, camera); } } }; //#endregion //#region node_modules/three-stdlib/renderers/Projector.js var RenderableObject = class { constructor() { this.id = 0; this.object = null; this.z = 0; this.renderOrder = 0; } }; var RenderableFace = class { constructor() { this.id = 0; this.v1 = new RenderableVertex(); this.v2 = new RenderableVertex(); this.v3 = new RenderableVertex(); this.normalModel = new Vector3(); this.vertexNormalsModel = [ new Vector3(), new Vector3(), new Vector3() ]; this.vertexNormalsLength = 0; this.color = new Color(); this.material = null; this.uvs = [ new Vector2(), new Vector2(), new Vector2() ]; this.z = 0; this.renderOrder = 0; } }; var RenderableVertex = class { constructor() { this.position = new Vector3(); this.positionWorld = new Vector3(); this.positionScreen = new Vector4(); this.visible = true; } copy(vertex) { this.positionWorld.copy(vertex.positionWorld); this.positionScreen.copy(vertex.positionScreen); } }; var RenderableLine = class { constructor() { this.id = 0; this.v1 = new RenderableVertex(); this.v2 = new RenderableVertex(); this.vertexColors = [new Color(), new Color()]; this.material = null; this.z = 0; this.renderOrder = 0; } }; var RenderableSprite = class { constructor() { this.id = 0; this.object = null; this.x = 0; this.y = 0; this.z = 0; this.rotation = 0; this.scale = new Vector2(); this.material = null; this.renderOrder = 0; } }; var Projector = class { constructor() { let _object, _objectCount, _objectPoolLength = 0, _vertex, _vertexCount, _vertexPoolLength = 0, _face, _faceCount, _facePoolLength = 0, _line, _lineCount, _linePoolLength = 0, _sprite, _spriteCount, _spritePoolLength = 0, _modelMatrix; const _renderData = { objects: [], lights: [], elements: [] }, _vector3 = new Vector3(), _vector4 = new Vector4(), _clipBox = new Box3(new Vector3(-1, -1, -1), new Vector3(1, 1, 1)), _boundingBox = new Box3(), _points3 = new Array(3), _viewMatrix = new Matrix4(), _viewProjectionMatrix = new Matrix4(), _modelViewProjectionMatrix = new Matrix4(), _frustum = new Frustum(), _objectPool = [], _vertexPool = [], _facePool = [], _linePool = [], _spritePool = []; function RenderList() { const normals = []; const colors = []; const uvs = []; let object = null; const normalMatrix = new Matrix3(); function setObject(value) { object = value; normalMatrix.getNormalMatrix(object.matrixWorld); normals.length = 0; colors.length = 0; uvs.length = 0; } function projectVertex(vertex) { const position = vertex.position; const positionWorld = vertex.positionWorld; const positionScreen = vertex.positionScreen; positionWorld.copy(position).applyMatrix4(_modelMatrix); positionScreen.copy(positionWorld).applyMatrix4(_viewProjectionMatrix); const invW = 1 / positionScreen.w; positionScreen.x *= invW; positionScreen.y *= invW; positionScreen.z *= invW; vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 && positionScreen.y >= -1 && positionScreen.y <= 1 && positionScreen.z >= -1 && positionScreen.z <= 1; } function pushVertex(x, y, z) { _vertex = getNextVertexInPool(); _vertex.position.set(x, y, z); projectVertex(_vertex); } function pushNormal(x, y, z) { normals.push(x, y, z); } function pushColor(r, g, b) { colors.push(r, g, b); } function pushUv(x, y) { uvs.push(x, y); } function checkTriangleVisibility(v1, v2, v3) { if (v1.visible === true || v2.visible === true || v3.visible === true) return true; _points3[0] = v1.positionScreen; _points3[1] = v2.positionScreen; _points3[2] = v3.positionScreen; return _clipBox.intersectsBox(_boundingBox.setFromPoints(_points3)); } function checkBackfaceCulling(v1, v2, v3) { return (v3.positionScreen.x - v1.positionScreen.x) * (v2.positionScreen.y - v1.positionScreen.y) - (v3.positionScreen.y - v1.positionScreen.y) * (v2.positionScreen.x - v1.positionScreen.x) < 0; } function pushLine(a, b) { const v1 = _vertexPool[a]; const v2 = _vertexPool[b]; v1.positionScreen.copy(v1.position).applyMatrix4(_modelViewProjectionMatrix); v2.positionScreen.copy(v2.position).applyMatrix4(_modelViewProjectionMatrix); if (clipLine(v1.positionScreen, v2.positionScreen) === true) { v1.positionScreen.multiplyScalar(1 / v1.positionScreen.w); v2.positionScreen.multiplyScalar(1 / v2.positionScreen.w); _line = getNextLineInPool(); _line.id = object.id; _line.v1.copy(v1); _line.v2.copy(v2); _line.z = Math.max(v1.positionScreen.z, v2.positionScreen.z); _line.renderOrder = object.renderOrder; _line.material = object.material; if (object.material.vertexColors) { _line.vertexColors[0].fromArray(colors, a * 3); _line.vertexColors[1].fromArray(colors, b * 3); } _renderData.elements.push(_line); } } function pushTriangle(a, b, c, material) { const v1 = _vertexPool[a]; const v2 = _vertexPool[b]; const v3 = _vertexPool[c]; if (checkTriangleVisibility(v1, v2, v3) === false) return; if (material.side === 2 || checkBackfaceCulling(v1, v2, v3) === true) { _face = getNextFaceInPool(); _face.id = object.id; _face.v1.copy(v1); _face.v2.copy(v2); _face.v3.copy(v3); _face.z = (v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z) / 3; _face.renderOrder = object.renderOrder; _vector3.subVectors(v3.position, v2.position); _vector4.subVectors(v1.position, v2.position); _vector3.cross(_vector4); _face.normalModel.copy(_vector3); _face.normalModel.applyMatrix3(normalMatrix).normalize(); for (let i = 0; i < 3; i++) { const normal = _face.vertexNormalsModel[i]; normal.fromArray(normals, arguments[i] * 3); normal.applyMatrix3(normalMatrix).normalize(); _face.uvs[i].fromArray(uvs, arguments[i] * 2); } _face.vertexNormalsLength = 3; _face.material = material; if (material.vertexColors) _face.color.fromArray(colors, a * 3); _renderData.elements.push(_face); } } return { setObject, projectVertex, checkTriangleVisibility, checkBackfaceCulling, pushVertex, pushNormal, pushColor, pushUv, pushLine, pushTriangle }; } const renderList = new RenderList(); function projectObject(object) { if (object.visible === false) return; if (object.isLight) _renderData.lights.push(object); else if (object.isMesh || object.isLine || object.isPoints) { if (object.material.visible === false) return; if (object.frustumCulled === true && _frustum.intersectsObject(object) === false) return; addObject(object); } else if (object.isSprite) { if (object.material.visible === false) return; if (object.frustumCulled === true && _frustum.intersectsSprite(object) === false) return; addObject(object); } const children = object.children; for (let i = 0, l = children.length; i < l; i++) projectObject(children[i]); } function addObject(object) { _object = getNextObjectInPool(); _object.id = object.id; _object.object = object; _vector3.setFromMatrixPosition(object.matrixWorld); _vector3.applyMatrix4(_viewProjectionMatrix); _object.z = _vector3.z; _object.renderOrder = object.renderOrder; _renderData.objects.push(_object); } this.projectScene = function(scene, camera, sortObjects, sortElements) { _faceCount = 0; _lineCount = 0; _spriteCount = 0; _renderData.elements.length = 0; if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); _viewMatrix.copy(camera.matrixWorldInverse); _viewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, _viewMatrix); _frustum.setFromProjectionMatrix(_viewProjectionMatrix); _objectCount = 0; _renderData.objects.length = 0; _renderData.lights.length = 0; projectObject(scene); if (sortObjects === true) _renderData.objects.sort(painterSort); const objects = _renderData.objects; for (let o = 0, ol = objects.length; o < ol; o++) { const object = objects[o].object; const geometry = object.geometry; renderList.setObject(object); _modelMatrix = object.matrixWorld; _vertexCount = 0; if (object.isMesh) { let material = object.material; const isMultiMaterial = Array.isArray(material); const attributes = geometry.attributes; const groups = geometry.groups; if (attributes.position === void 0) continue; const positions = attributes.position.array; for (let i = 0, l = positions.length; i < l; i += 3) { let x = positions[i]; let y = positions[i + 1]; let z = positions[i + 2]; const morphTargets = geometry.morphAttributes.position; if (morphTargets !== void 0) { const morphTargetsRelative = geometry.morphTargetsRelative; const morphInfluences = object.morphTargetInfluences; for (let t = 0, tl = morphTargets.length; t < tl; t++) { const influence = morphInfluences[t]; if (influence === 0) continue; const target = morphTargets[t]; if (morphTargetsRelative) { x += target.getX(i / 3) * influence; y += target.getY(i / 3) * influence; z += target.getZ(i / 3) * influence; } else { x += (target.getX(i / 3) - positions[i]) * influence; y += (target.getY(i / 3) - positions[i + 1]) * influence; z += (target.getZ(i / 3) - positions[i + 2]) * influence; } } } renderList.pushVertex(x, y, z); } if (attributes.normal !== void 0) { const normals = attributes.normal.array; for (let i = 0, l = normals.length; i < l; i += 3) renderList.pushNormal(normals[i], normals[i + 1], normals[i + 2]); } if (attributes.color !== void 0) { const colors = attributes.color.array; for (let i = 0, l = colors.length; i < l; i += 3) renderList.pushColor(colors[i], colors[i + 1], colors[i + 2]); } if (attributes.uv !== void 0) { const uvs = attributes.uv.array; for (let i = 0, l = uvs.length; i < l; i += 2) renderList.pushUv(uvs[i], uvs[i + 1]); } if (geometry.index !== null) { const indices = geometry.index.array; if (groups.length > 0) for (let g = 0; g < groups.length; g++) { const group = groups[g]; material = isMultiMaterial === true ? object.material[group.materialIndex] : object.material; if (material === void 0) continue; for (let i = group.start, l = group.start + group.count; i < l; i += 3) renderList.pushTriangle(indices[i], indices[i + 1], indices[i + 2], material); } else for (let i = 0, l = indices.length; i < l; i += 3) renderList.pushTriangle(indices[i], indices[i + 1], indices[i + 2], material); } else if (groups.length > 0) for (let g = 0; g < groups.length; g++) { const group = groups[g]; material = isMultiMaterial === true ? object.material[group.materialIndex] : object.material; if (material === void 0) continue; for (let i = group.start, l = group.start + group.count; i < l; i += 3) renderList.pushTriangle(i, i + 1, i + 2, material); } else for (let i = 0, l = positions.length / 3; i < l; i += 3) renderList.pushTriangle(i, i + 1, i + 2, material); } else if (object.isLine) { _modelViewProjectionMatrix.multiplyMatrices(_viewProjectionMatrix, _modelMatrix); const attributes = geometry.attributes; if (attributes.position !== void 0) { const positions = attributes.position.array; for (let i = 0, l = positions.length; i < l; i += 3) renderList.pushVertex(positions[i], positions[i + 1], positions[i + 2]); if (attributes.color !== void 0) { const colors = attributes.color.array; for (let i = 0, l = colors.length; i < l; i += 3) renderList.pushColor(colors[i], colors[i + 1], colors[i + 2]); } if (geometry.index !== null) { const indices = geometry.index.array; for (let i = 0, l = indices.length; i < l; i += 2) renderList.pushLine(indices[i], indices[i + 1]); } else { const step = object.isLineSegments ? 2 : 1; for (let i = 0, l = positions.length / 3 - 1; i < l; i += step) renderList.pushLine(i, i + 1); } } } else if (object.isPoints) { _modelViewProjectionMatrix.multiplyMatrices(_viewProjectionMatrix, _modelMatrix); const attributes = geometry.attributes; if (attributes.position !== void 0) { const positions = attributes.position.array; for (let i = 0, l = positions.length; i < l; i += 3) { _vector4.set(positions[i], positions[i + 1], positions[i + 2], 1); _vector4.applyMatrix4(_modelViewProjectionMatrix); pushPoint(_vector4, object, camera); } } } else if (object.isSprite) { object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); _vector4.set(_modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1); _vector4.applyMatrix4(_viewProjectionMatrix); pushPoint(_vector4, object, camera); } } if (sortElements === true) _renderData.elements.sort(painterSort); return _renderData; }; function pushPoint(_vector42, object, camera) { const invW = 1 / _vector42.w; _vector42.z *= invW; if (_vector42.z >= -1 && _vector42.z <= 1) { _sprite = getNextSpriteInPool(); _sprite.id = object.id; _sprite.x = _vector42.x * invW; _sprite.y = _vector42.y * invW; _sprite.z = _vector42.z; _sprite.renderOrder = object.renderOrder; _sprite.object = object; _sprite.rotation = object.rotation; _sprite.scale.x = object.scale.x * Math.abs(_sprite.x - (_vector42.x + camera.projectionMatrix.elements[0]) / (_vector42.w + camera.projectionMatrix.elements[12])); _sprite.scale.y = object.scale.y * Math.abs(_sprite.y - (_vector42.y + camera.projectionMatrix.elements[5]) / (_vector42.w + camera.projectionMatrix.elements[13])); _sprite.material = object.material; _renderData.elements.push(_sprite); } } function getNextObjectInPool() { if (_objectCount === _objectPoolLength) { const object = new RenderableObject(); _objectPool.push(object); _objectPoolLength++; _objectCount++; return object; } return _objectPool[_objectCount++]; } function getNextVertexInPool() { if (_vertexCount === _vertexPoolLength) { const vertex = new RenderableVertex(); _vertexPool.push(vertex); _vertexPoolLength++; _vertexCount++; return vertex; } return _vertexPool[_vertexCount++]; } function getNextFaceInPool() { if (_faceCount === _facePoolLength) { const face = new RenderableFace(); _facePool.push(face); _facePoolLength++; _faceCount++; return face; } return _facePool[_faceCount++]; } function getNextLineInPool() { if (_lineCount === _linePoolLength) { const line = new RenderableLine(); _linePool.push(line); _linePoolLength++; _lineCount++; return line; } return _linePool[_lineCount++]; } function getNextSpriteInPool() { if (_spriteCount === _spritePoolLength) { const sprite = new RenderableSprite(); _spritePool.push(sprite); _spritePoolLength++; _spriteCount++; return sprite; } return _spritePool[_spriteCount++]; } function painterSort(a, b) { if (a.renderOrder !== b.renderOrder) return a.renderOrder - b.renderOrder; else if (a.z !== b.z) return b.z - a.z; else if (a.id !== b.id) return a.id - b.id; else return 0; } function clipLine(s1, s2) { let alpha1 = 0, alpha2 = 1; const bc1near = s1.z + s1.w, bc2near = s2.z + s2.w, bc1far = -s1.z + s1.w, bc2far = -s2.z + s2.w; if (bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0) return true; else if (bc1near < 0 && bc2near < 0 || bc1far < 0 && bc2far < 0) return false; else { if (bc1near < 0) alpha1 = Math.max(alpha1, bc1near / (bc1near - bc2near)); else if (bc2near < 0) alpha2 = Math.min(alpha2, bc1near / (bc1near - bc2near)); if (bc1far < 0) alpha1 = Math.max(alpha1, bc1far / (bc1far - bc2far)); else if (bc2far < 0) alpha2 = Math.min(alpha2, bc1far / (bc1far - bc2far)); if (alpha2 < alpha1) return false; else { s1.lerp(s2, alpha1); s2.lerp(s1, 1 - alpha2); return true; } } } } }; //#endregion //#region node_modules/three-stdlib/renderers/SVGRenderer.js var SVGObject = class extends Object3D { constructor(node) { super(); this.isSVGObject = true; this.node = node; } }; var SVGRenderer = class { constructor() { let _renderData, _elements, _lights, _svgWidth, _svgHeight, _svgWidthHalf, _svgHeightHalf, _v1, _v2, _v3, _svgNode, _pathCount = 0, _precision = null, _quality = 1, _currentPath, _currentStyle; const _this = this, _clipBox = new Box2(), _elemBox = new Box2(), _color = new Color(), _diffuseColor = new Color(), _ambientLight = new Color(), _directionalLights = new Color(), _pointLights = new Color(), _clearColor = new Color(), _vector3 = new Vector3(), _centroid = new Vector3(), _normal = new Vector3(), _normalViewMatrix = new Matrix3(), _viewMatrix = new Matrix4(), _viewProjectionMatrix = new Matrix4(), _svgPathPool = [], _projector = new Projector(), _svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); this.domElement = _svg; this.autoClear = true; this.sortObjects = true; this.sortElements = true; this.overdraw = .5; this.info = { render: { vertices: 0, faces: 0 } }; this.setQuality = function(quality) { switch (quality) { case "high": _quality = 1; break; case "low": _quality = 0; break; } }; this.setClearColor = function(color) { _clearColor.set(color); }; this.setPixelRatio = function() {}; this.setSize = function(width, height) { _svgWidth = width; _svgHeight = height; _svgWidthHalf = _svgWidth / 2; _svgHeightHalf = _svgHeight / 2; _svg.setAttribute("viewBox", -_svgWidthHalf + " " + -_svgHeightHalf + " " + _svgWidth + " " + _svgHeight); _svg.setAttribute("width", _svgWidth); _svg.setAttribute("height", _svgHeight); _clipBox.min.set(-_svgWidthHalf, -_svgHeightHalf); _clipBox.max.set(_svgWidthHalf, _svgHeightHalf); }; this.getSize = function() { return { width: _svgWidth, height: _svgHeight }; }; this.setPrecision = function(precision) { _precision = precision; }; function removeChildNodes() { _pathCount = 0; while (_svg.childNodes.length > 0) _svg.removeChild(_svg.childNodes[0]); } function convert(c) { return _precision !== null ? c.toFixed(_precision) : c; } this.clear = function() { removeChildNodes(); _svg.style.backgroundColor = _clearColor.getStyle(); }; this.render = function(scene, camera) { if (camera instanceof Camera === false) { console.error("THREE.SVGRenderer.render: camera is not an instance of Camera."); return; } const background = scene.background; if (background && background.isColor) { removeChildNodes(); _svg.style.backgroundColor = background.getStyle(); } else if (this.autoClear === true) this.clear(); _this.info.render.vertices = 0; _this.info.render.faces = 0; _viewMatrix.copy(camera.matrixWorldInverse); _viewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, _viewMatrix); _renderData = _projector.projectScene(scene, camera, this.sortObjects, this.sortElements); _elements = _renderData.elements; _lights = _renderData.lights; _normalViewMatrix.getNormalMatrix(camera.matrixWorldInverse); calculateLights(_lights); _currentPath = ""; _currentStyle = ""; for (let e = 0, el = _elements.length; e < el; e++) { const element = _elements[e]; const material = element.material; if (material === void 0 || material.opacity === 0) continue; _elemBox.makeEmpty(); if (element instanceof RenderableSprite) { _v1 = element; _v1.x *= _svgWidthHalf; _v1.y *= -_svgHeightHalf; renderSprite(_v1, element, material); } else if (element instanceof RenderableLine) { _v1 = element.v1; _v2 = element.v2; _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= -_svgHeightHalf; _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= -_svgHeightHalf; _elemBox.setFromPoints([_v1.positionScreen, _v2.positionScreen]); if (_clipBox.intersectsBox(_elemBox) === true) renderLine(_v1, _v2, material); } else if (element instanceof RenderableFace) { _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; if (_v1.positionScreen.z < -1 || _v1.positionScreen.z > 1) continue; if (_v2.positionScreen.z < -1 || _v2.positionScreen.z > 1) continue; if (_v3.positionScreen.z < -1 || _v3.positionScreen.z > 1) continue; _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= -_svgHeightHalf; _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= -_svgHeightHalf; _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= -_svgHeightHalf; if (this.overdraw > 0) { expand(_v1.positionScreen, _v2.positionScreen, this.overdraw); expand(_v2.positionScreen, _v3.positionScreen, this.overdraw); expand(_v3.positionScreen, _v1.positionScreen, this.overdraw); } _elemBox.setFromPoints([ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ]); if (_clipBox.intersectsBox(_elemBox) === true) renderFace3(_v1, _v2, _v3, element, material); } } flushPath(); scene.traverseVisible(function(object) { if (object.isSVGObject) { _vector3.setFromMatrixPosition(object.matrixWorld); _vector3.applyMatrix4(_viewProjectionMatrix); if (_vector3.z < -1 || _vector3.z > 1) return; const x = _vector3.x * _svgWidthHalf; const y = -_vector3.y * _svgHeightHalf; const node = object.node; node.setAttribute("transform", "translate(" + x + "," + y + ")"); _svg.appendChild(node); } }); }; function calculateLights(lights) { _ambientLight.setRGB(0, 0, 0); _directionalLights.setRGB(0, 0, 0); _pointLights.setRGB(0, 0, 0); for (let l = 0, ll = lights.length; l < ll; l++) { const light = lights[l]; const lightColor = light.color; if (light.isAmbientLight) { _ambientLight.r += lightColor.r; _ambientLight.g += lightColor.g; _ambientLight.b += lightColor.b; } else if (light.isDirectionalLight) { _directionalLights.r += lightColor.r; _directionalLights.g += lightColor.g; _directionalLights.b += lightColor.b; } else if (light.isPointLight) { _pointLights.r += lightColor.r; _pointLights.g += lightColor.g; _pointLights.b += lightColor.b; } } } function calculateLight(lights, position, normal, color) { for (let l = 0, ll = lights.length; l < ll; l++) { const light = lights[l]; const lightColor = light.color; if (light.isDirectionalLight) { const lightPosition = _vector3.setFromMatrixPosition(light.matrixWorld).normalize(); let amount = normal.dot(lightPosition); if (amount <= 0) continue; amount *= light.intensity; color.r += lightColor.r * amount; color.g += lightColor.g * amount; color.b += lightColor.b * amount; } else if (light.isPointLight) { const lightPosition = _vector3.setFromMatrixPosition(light.matrixWorld); let amount = normal.dot(_vector3.subVectors(lightPosition, position).normalize()); if (amount <= 0) continue; amount *= light.distance == 0 ? 1 : 1 - Math.min(position.distanceTo(lightPosition) / light.distance, 1); if (amount == 0) continue; amount *= light.intensity; color.r += lightColor.r * amount; color.g += lightColor.g * amount; color.b += lightColor.b * amount; } } } function renderSprite(v1, element, material) { let scaleX = element.scale.x * _svgWidthHalf; let scaleY = element.scale.y * _svgHeightHalf; if (material.isPointsMaterial) { scaleX *= material.size; scaleY *= material.size; } const path = "M" + convert(v1.x - scaleX * .5) + "," + convert(v1.y - scaleY * .5) + "h" + convert(scaleX) + "v" + convert(scaleY) + "h" + convert(-scaleX) + "z"; let style = ""; if (material.isSpriteMaterial || material.isPointsMaterial) style = "fill:" + material.color.getStyle() + ";fill-opacity:" + material.opacity; addPath(style, path); } function renderLine(v1, v2, material) { const path = "M" + convert(v1.positionScreen.x) + "," + convert(v1.positionScreen.y) + "L" + convert(v2.positionScreen.x) + "," + convert(v2.positionScreen.y); if (material.isLineBasicMaterial) { let style = "fill:none;stroke:" + material.color.getStyle() + ";stroke-opacity:" + material.opacity + ";stroke-width:" + material.linewidth + ";stroke-linecap:" + material.linecap; if (material.isLineDashedMaterial) style = style + ";stroke-dasharray:" + material.dashSize + "," + material.gapSize; addPath(style, path); } } function renderFace3(v1, v2, v3, element, material) { _this.info.render.vertices += 3; _this.info.render.faces++; const path = "M" + convert(v1.positionScreen.x) + "," + convert(v1.positionScreen.y) + "L" + convert(v2.positionScreen.x) + "," + convert(v2.positionScreen.y) + "L" + convert(v3.positionScreen.x) + "," + convert(v3.positionScreen.y) + "z"; let style = ""; if (material.isMeshBasicMaterial) { _color.copy(material.color); if (material.vertexColors) _color.multiply(element.color); } else if (material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial) { _diffuseColor.copy(material.color); if (material.vertexColors) _diffuseColor.multiply(element.color); _color.copy(_ambientLight); _centroid.copy(v1.positionWorld).add(v2.positionWorld).add(v3.positionWorld).divideScalar(3); calculateLight(_lights, _centroid, element.normalModel, _color); _color.multiply(_diffuseColor).add(material.emissive); } else if (material.isMeshNormalMaterial) { _normal.copy(element.normalModel).applyMatrix3(_normalViewMatrix).normalize(); _color.setRGB(_normal.x, _normal.y, _normal.z).multiplyScalar(.5).addScalar(.5); } if (material.wireframe) style = "fill:none;stroke:" + _color.getStyle() + ";stroke-opacity:" + material.opacity + ";stroke-width:" + material.wireframeLinewidth + ";stroke-linecap:" + material.wireframeLinecap + ";stroke-linejoin:" + material.wireframeLinejoin; else style = "fill:" + _color.getStyle() + ";fill-opacity:" + material.opacity; addPath(style, path); } function expand(v1, v2, pixels) { let x = v2.x - v1.x, y = v2.y - v1.y; const det = x * x + y * y; if (det === 0) return; const idet = pixels / Math.sqrt(det); x *= idet; y *= idet; v2.x += x; v2.y += y; v1.x -= x; v1.y -= y; } function addPath(style, path) { if (_currentStyle === style) _currentPath += path; else { flushPath(); _currentStyle = style; _currentPath = path; } } function flushPath() { if (_currentPath) { _svgNode = getPathNode(_pathCount++); _svgNode.setAttribute("d", _currentPath); _svgNode.setAttribute("style", _currentStyle); _svg.appendChild(_svgNode); } _currentPath = ""; _currentStyle = ""; } function getPathNode(id) { if (_svgPathPool[id] == null) { _svgPathPool[id] = document.createElementNS("http://www.w3.org/2000/svg", "path"); if (_quality == 0) _svgPathPool[id].setAttribute("shape-rendering", "crispEdges"); return _svgPathPool[id]; } return _svgPathPool[id]; } } }; //#endregion //#region node_modules/three-stdlib/textures/FlakesTexture.js var FlakesTexture = class { constructor(width = 512, height = 512) { const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; const context = canvas.getContext("2d"); context.fillStyle = "rgb(127,127,255)"; context.fillRect(0, 0, width, height); for (let i = 0; i < 4e3; i++) { const x = Math.random() * width; const y = Math.random() * height; const r = Math.random() * 3 + 3; let nx = Math.random() * 2 - 1; let ny = Math.random() * 2 - 1; let nz = 1.5; const l = Math.sqrt(nx * nx + ny * ny + nz * nz); nx /= l; ny /= l; nz /= l; context.fillStyle = "rgb(" + (nx * 127 + 127) + "," + (ny * 127 + 127) + "," + nz * 255 + ")"; context.beginPath(); context.arc(x, y, r, 0, Math.PI * 2); context.fill(); } return canvas; } }; //#endregion //#region node_modules/three-stdlib/modifiers/CurveModifier.js var __defProp$58 = Object.defineProperty; var __defNormalProp$58 = (obj, key, value) => key in obj ? __defProp$58(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$58 = (obj, key, value) => { __defNormalProp$58(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 dataTexture = new DataTexture(new Float32Array(TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * CHANNELS), 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 i = 0; i < numberOfPoints; i++) { const rowOffset = Math.floor(i / TEXTURE_WIDTH); const rowIndex = i % TEXTURE_WIDTH; let pt = points[i]; setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 0 + rowOffset + TEXTURE_HEIGHT * offset); pt = frenetFrames.tangents[i]; setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 1 + rowOffset + TEXTURE_HEIGHT * offset); pt = frenetFrames.normals[i]; setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 2 + rowOffset + TEXTURE_HEIGHT * offset); pt = frenetFrames.binormals[i]; setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 3 + rowOffset + TEXTURE_HEIGHT * offset); } texture.needsUpdate = true; }; var setTextureValue = (texture, index, x, y, z, o) => { const { data } = texture.image; const i = CHANNELS * TEXTURE_WIDTH * o; data[index * CHANNELS + i + 0] = x; data[index * CHANNELS + i + 1] = y; data[index * CHANNELS + i + 2] = z; data[index * CHANNELS + i + 3] = 1; }; var getUniforms = (splineTexture) => ({ spineTexture: { value: splineTexture }, pathOffset: { type: "f", value: 0 }, pathSegment: { type: "f", value: 1 }, 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); shader.vertexShader = ` uniform sampler2D spineTexture; uniform float pathOffset; uniform float pathSegment; uniform float spineOffset; uniform float spineLength; uniform int flow; float textureLayers = ${TEXTURE_HEIGHT * numberOfCurves}.; float textureStacks = ${TEXTURE_HEIGHT / 4}.; ${shader.vertexShader} `.replace("#include ", "").replace("#include ", "").replace("#include ", "").replace(/void\s*main\s*\(\)\s*\{/, ` 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 ", `vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 ); gl_Position = projectionMatrix * mvPosition;`); }; } 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$58(this, "curveArray"); __publicField$58(this, "curveLengthArray"); __publicField$58(this, "object3D"); __publicField$58(this, "splineTexure"); __publicField$58(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(index, curve) { if (index >= this.curveArray.length) throw Error("Index out of range for Flow"); const curveLength = curve.getLength(); this.uniforms.spineLength.value = curveLength; this.curveLengthArray[index] = curveLength; this.curveArray[index] = curve; updateSplineTexture(this.splineTexure, curve, index); } moveAlongCurve(amount) { this.uniforms.pathOffset.value += amount; } }; var matrix$1 = /* @__PURE__ */ new Matrix4(); var InstancedFlow = class extends Flow { /** * * @param {number} count The number of instanced elements * @param {number} curveCount The number of curves to preallocate for * @param {Geometry} geometry The geometry to use for the instanced mesh * @param {Material} material The material to use for the instanced mesh */ constructor(count, curveCount, geometry, material) { const mesh = new InstancedMesh(geometry, material, count); mesh.instanceMatrix.setUsage(DynamicDrawUsage); mesh.frustumCulled = false; super(mesh, curveCount); __publicField$58(this, "offsets"); __publicField$58(this, "whichCurve"); this.offsets = new Array(count).fill(0); this.whichCurve = new Array(count).fill(0); } /** * The extra information about which curve and curve position is stored in the translation components of the matrix for the instanced objects * This writes that information to the matrix and marks it as needing update. * * @param {number} index of the instanced element to update */ writeChanges(index) { matrix$1.makeTranslation(this.curveLengthArray[this.whichCurve[index]], this.whichCurve[index], this.offsets[index]); this.object3D.setMatrixAt(index, matrix$1); this.object3D.instanceMatrix.needsUpdate = true; } /** * Move an individual element along the curve by a specific amount * * @param {number} index Which element to update * @param {number} offset Move by how much */ moveIndividualAlongCurve(index, offset) { this.offsets[index] += offset; this.writeChanges(index); } /** * Select which curve to use for an element * * @param {number} index the index of the instanced element to update * @param {number} curveNo the index of the curve it should use */ setCurve(index, curveNo) { if (isNaN(curveNo)) throw Error("curve index being set is Not a Number (NaN)"); this.whichCurve[index] = curveNo; this.writeChanges(index); } }; //#endregion //#region node_modules/three-stdlib/types/helpers.js var getWithKey = (obj, key) => obj[key]; //#endregion //#region node_modules/three-stdlib/utils/BufferGeometryUtils.js var BufferGeometryUtils_exports = /* @__PURE__ */ __exportAll({ computeMorphedAttributes: () => computeMorphedAttributes, estimateBytesUsed: () => estimateBytesUsed, interleaveAttributes: () => interleaveAttributes, mergeBufferAttributes: () => mergeBufferAttributes, mergeBufferGeometries: () => mergeBufferGeometries, mergeVertices: () => mergeVertices, toCreasedNormals: () => toCreasedNormals, toTrianglesDrawMode: () => toTrianglesDrawMode }); var mergeBufferGeometries = (geometries, useGroups) => { const isIndexed = geometries[0].index !== null; const attributesUsed = new Set(Object.keys(geometries[0].attributes)); const morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes)); const attributes = {}; const morphAttributes = {}; const morphTargetsRelative = geometries[0].morphTargetsRelative; const mergedGeometry = new BufferGeometry(); let offset = 0; geometries.forEach((geom, i) => { let attributesCount = 0; if (isIndexed !== (geom.index !== null)) { console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index " + i + ". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."); return null; } for (let name in geom.attributes) { if (!attributesUsed.has(name)) { console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index " + i + ". All geometries must have compatible attributes; make sure \"" + name + "\" attribute exists among all geometries, or in none of them."); return null; } if (attributes[name] === void 0) attributes[name] = []; attributes[name].push(geom.attributes[name]); attributesCount++; } if (attributesCount !== attributesUsed.size) { console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index " + i + ". Make sure all geometries have the same number of attributes."); return null; } if (morphTargetsRelative !== geom.morphTargetsRelative) { console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index " + i + ". .morphTargetsRelative must be consistent throughout all geometries."); return null; } for (let name in geom.morphAttributes) { if (!morphAttributesUsed.has(name)) { console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index " + i + ". .morphAttributes must be consistent throughout all geometries."); return null; } if (morphAttributes[name] === void 0) morphAttributes[name] = []; morphAttributes[name].push(geom.morphAttributes[name]); } mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || []; mergedGeometry.userData.mergedUserData.push(geom.userData); if (useGroups) { let count; if (geom.index) count = geom.index.count; else if (geom.attributes.position !== void 0) count = geom.attributes.position.count; else { console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index " + i + ". The geometry must have either an index or a position attribute"); return null; } mergedGeometry.addGroup(offset, count, i); offset += count; } }); if (isIndexed) { let indexOffset = 0; const mergedIndex = []; geometries.forEach((geom) => { const index = geom.index; for (let j = 0; j < index.count; ++j) mergedIndex.push(index.getX(j) + indexOffset); indexOffset += geom.attributes.position.count; }); mergedGeometry.setIndex(mergedIndex); } for (let name in attributes) { const mergedAttribute = mergeBufferAttributes(attributes[name]); if (!mergedAttribute) { console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the " + name + " attribute."); return null; } mergedGeometry.setAttribute(name, mergedAttribute); } for (let name in morphAttributes) { const numMorphTargets = morphAttributes[name][0].length; if (numMorphTargets === 0) break; mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {}; mergedGeometry.morphAttributes[name] = []; for (let i = 0; i < numMorphTargets; ++i) { const morphAttributesToMerge = []; for (let j = 0; j < morphAttributes[name].length; ++j) morphAttributesToMerge.push(morphAttributes[name][j][i]); const mergedMorphAttribute = mergeBufferAttributes(morphAttributesToMerge); if (!mergedMorphAttribute) { console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the " + name + " morphAttribute."); return null; } mergedGeometry.morphAttributes[name].push(mergedMorphAttribute); } } return mergedGeometry; }; var mergeBufferAttributes = (attributes) => { let TypedArray = void 0; let itemSize = void 0; let normalized = void 0; let arrayLength = 0; attributes.forEach((attr) => { if (TypedArray === void 0) TypedArray = attr.array.constructor; if (TypedArray !== attr.array.constructor) { console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."); return null; } if (itemSize === void 0) itemSize = attr.itemSize; if (itemSize !== attr.itemSize) { console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."); return null; } if (normalized === void 0) normalized = attr.normalized; if (normalized !== attr.normalized) { console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."); return null; } arrayLength += attr.array.length; }); if (TypedArray && itemSize) { const array = new TypedArray(arrayLength); let offset = 0; attributes.forEach((attr) => { array.set(attr.array, offset); offset += attr.array.length; }); return new BufferAttribute(array, itemSize, normalized); } }; var interleaveAttributes = (attributes) => { let TypedArray = void 0; let arrayLength = 0; let stride = 0; for (let i = 0, l = attributes.length; i < l; ++i) { const attribute = attributes[i]; if (TypedArray === void 0) TypedArray = attribute.array.constructor; if (TypedArray !== attribute.array.constructor) { console.error("AttributeBuffers of different types cannot be interleaved"); return null; } arrayLength += attribute.array.length; stride += attribute.itemSize; } const interleavedBuffer = new InterleavedBuffer(new TypedArray(arrayLength), stride); let offset = 0; const res = []; const getters = [ "getX", "getY", "getZ", "getW" ]; const setters = [ "setX", "setY", "setZ", "setW" ]; for (let j = 0, l = attributes.length; j < l; j++) { const attribute = attributes[j]; const itemSize = attribute.itemSize; const count = attribute.count; const iba = new InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, attribute.normalized); res.push(iba); offset += itemSize; for (let c = 0; c < count; c++) for (let k = 0; k < itemSize; k++) { const set = getWithKey(iba, setters[k]); const get = getWithKey(attribute, getters[k]); set(c, get(c)); } } return res; }; function estimateBytesUsed(geometry) { let mem = 0; for (let name in geometry.attributes) { const attr = geometry.getAttribute(name); mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT; } const indices = geometry.getIndex(); mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0; return mem; } function mergeVertices(geometry, tolerance = 1e-4) { tolerance = Math.max(tolerance, Number.EPSILON); const hashToIndex = {}; const indices = geometry.getIndex(); const positions = geometry.getAttribute("position"); const vertexCount = indices ? indices.count : positions.count; let nextIndex = 0; const attributeNames = Object.keys(geometry.attributes); const attrArrays = {}; const morphAttrsArrays = {}; const newIndices = []; const getters = [ "getX", "getY", "getZ", "getW" ]; for (let i = 0, l = attributeNames.length; i < l; i++) { const name = attributeNames[i]; attrArrays[name] = []; const morphAttr = geometry.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 i = 0; i < vertexCount; i++) { const index = indices ? indices.getX(i) : i; let hash = ""; for (let j = 0, l = attributeNames.length; j < l; j++) { const name = attributeNames[j]; const attribute = geometry.getAttribute(name); const itemSize = attribute.itemSize; for (let k = 0; k < itemSize; k++) hash += `${~~(attribute[getters[k]](index) * shiftMultiplier)},`; } if (hash in hashToIndex) newIndices.push(hashToIndex[hash]); else { for (let j = 0, l = attributeNames.length; j < l; j++) { const name = attributeNames[j]; const attribute = geometry.getAttribute(name); const morphAttr = geometry.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](index)); if (morphAttr) for (let m = 0, ml = morphAttr.length; m < ml; m++) newMorphArrays[m].push(morphAttr[m][getterFunc](index)); } } hashToIndex[hash] = nextIndex; newIndices.push(nextIndex); nextIndex++; } } const result = geometry.clone(); for (let i = 0, l = attributeNames.length; i < l; i++) { const name = attributeNames[i]; const oldAttribute = geometry.getAttribute(name); const attribute = new BufferAttribute(new oldAttribute.array.constructor(attrArrays[name]), oldAttribute.itemSize, oldAttribute.normalized); result.setAttribute(name, attribute); if (name in morphAttrsArrays) for (let j = 0; j < morphAttrsArrays[name].length; j++) { const oldMorphAttribute = geometry.morphAttributes[name][j]; const morphAttribute = new BufferAttribute(new oldMorphAttribute.array.constructor(morphAttrsArrays[name][j]), oldMorphAttribute.itemSize, oldMorphAttribute.normalized); result.morphAttributes[name][j] = morphAttribute; } } result.setIndex(newIndices); return result; } function toTrianglesDrawMode(geometry, drawMode) { if (drawMode === 0) { console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."); return geometry; } if (drawMode === 2 || drawMode === 1) { let index = geometry.getIndex(); if (index === null) { const indices = []; const position = geometry.getAttribute("position"); if (position !== void 0) { for (let i = 0; i < position.count; i++) indices.push(i); geometry.setIndex(indices); index = geometry.getIndex(); } else { console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."); return geometry; } } const numberOfTriangles = index.count - 2; const newIndices = []; if (index) if (drawMode === 2) for (let i = 1; i <= numberOfTriangles; i++) { newIndices.push(index.getX(0)); newIndices.push(index.getX(i)); newIndices.push(index.getX(i + 1)); } else for (let i = 0; i < numberOfTriangles; i++) if (i % 2 === 0) { newIndices.push(index.getX(i)); newIndices.push(index.getX(i + 1)); newIndices.push(index.getX(i + 2)); } else { newIndices.push(index.getX(i + 2)); newIndices.push(index.getX(i + 1)); newIndices.push(index.getX(i)); } if (newIndices.length / 3 !== numberOfTriangles) console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles."); const newGeometry = geometry.clone(); newGeometry.setIndex(newIndices); newGeometry.clearGroups(); return newGeometry; } else { console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:", drawMode); return geometry; } } function computeMorphedAttributes(object) { if (object.geometry.isBufferGeometry !== true) { console.error("THREE.BufferGeometryUtils: Geometry is not of type BufferGeometry."); return null; } const _vA = new Vector3(); const _vB = new Vector3(); const _vC = new Vector3(); const _tempA = new Vector3(); const _tempB = new Vector3(); const _tempC = new Vector3(); const _morphA = new Vector3(); const _morphB = new Vector3(); const _morphC = new Vector3(); function _calculateMorphedAttributeData(object2, material2, attribute, morphAttribute, morphTargetsRelative2, a2, b2, c2, modifiedAttributeArray) { _vA.fromBufferAttribute(attribute, a2); _vB.fromBufferAttribute(attribute, b2); _vC.fromBufferAttribute(attribute, c2); const morphInfluences = object2.morphTargetInfluences; if (material2.morphTargets && morphAttribute && morphInfluences) { _morphA.set(0, 0, 0); _morphB.set(0, 0, 0); _morphC.set(0, 0, 0); for (let i2 = 0, il2 = morphAttribute.length; i2 < il2; i2++) { const influence = morphInfluences[i2]; const morph = morphAttribute[i2]; if (influence === 0) continue; _tempA.fromBufferAttribute(morph, a2); _tempB.fromBufferAttribute(morph, b2); _tempC.fromBufferAttribute(morph, c2); if (morphTargetsRelative2) { _morphA.addScaledVector(_tempA, influence); _morphB.addScaledVector(_tempB, influence); _morphC.addScaledVector(_tempC, influence); } else { _morphA.addScaledVector(_tempA.sub(_vA), influence); _morphB.addScaledVector(_tempB.sub(_vB), influence); _morphC.addScaledVector(_tempC.sub(_vC), influence); } } _vA.add(_morphA); _vB.add(_morphB); _vC.add(_morphC); } if (object2.isSkinnedMesh) { object2.boneTransform(a2, _vA); object2.boneTransform(b2, _vB); object2.boneTransform(c2, _vC); } modifiedAttributeArray[a2 * 3 + 0] = _vA.x; modifiedAttributeArray[a2 * 3 + 1] = _vA.y; modifiedAttributeArray[a2 * 3 + 2] = _vA.z; modifiedAttributeArray[b2 * 3 + 0] = _vB.x; modifiedAttributeArray[b2 * 3 + 1] = _vB.y; modifiedAttributeArray[b2 * 3 + 2] = _vB.z; modifiedAttributeArray[c2 * 3 + 0] = _vC.x; modifiedAttributeArray[c2 * 3 + 1] = _vC.y; modifiedAttributeArray[c2 * 3 + 2] = _vC.z; } const geometry = object.geometry; const material = object.material; let a, b, c; const index = geometry.index; const positionAttribute = geometry.attributes.position; const morphPosition = geometry.morphAttributes.position; const morphTargetsRelative = geometry.morphTargetsRelative; const normalAttribute = geometry.attributes.normal; const morphNormal = geometry.morphAttributes.position; const groups = geometry.groups; const drawRange = geometry.drawRange; let i, j, il, jl; let group, groupMaterial; let start, end; const modifiedPosition = new Float32Array(positionAttribute.count * positionAttribute.itemSize); const modifiedNormal = new Float32Array(normalAttribute.count * normalAttribute.itemSize); if (index !== null) if (Array.isArray(material)) for (i = 0, il = groups.length; i < il; i++) { group = groups[i]; groupMaterial = material[group.materialIndex]; start = Math.max(group.start, drawRange.start); end = Math.min(group.start + group.count, drawRange.start + drawRange.count); for (j = start, jl = end; j < jl; j += 3) { a = index.getX(j); b = index.getX(j + 1); c = index.getX(j + 2); _calculateMorphedAttributeData(object, groupMaterial, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition); _calculateMorphedAttributeData(object, groupMaterial, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal); } } else { start = Math.max(0, drawRange.start); end = Math.min(index.count, drawRange.start + drawRange.count); for (i = start, il = end; i < il; i += 3) { a = index.getX(i); b = index.getX(i + 1); c = index.getX(i + 2); _calculateMorphedAttributeData(object, material, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition); _calculateMorphedAttributeData(object, material, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal); } } else if (positionAttribute !== void 0) if (Array.isArray(material)) for (i = 0, il = groups.length; i < il; i++) { group = groups[i]; groupMaterial = material[group.materialIndex]; start = Math.max(group.start, drawRange.start); end = Math.min(group.start + group.count, drawRange.start + drawRange.count); for (j = start, jl = end; j < jl; j += 3) { a = j; b = j + 1; c = j + 2; _calculateMorphedAttributeData(object, groupMaterial, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition); _calculateMorphedAttributeData(object, groupMaterial, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal); } } else { start = Math.max(0, drawRange.start); end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); for (i = start, il = end; i < il; i += 3) { a = i; b = i + 1; c = i + 2; _calculateMorphedAttributeData(object, material, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition); _calculateMorphedAttributeData(object, material, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal); } } return { positionAttribute, normalAttribute, morphedPositionAttribute: new Float32BufferAttribute(modifiedPosition, 3), morphedNormalAttribute: new Float32BufferAttribute(modifiedNormal, 3) }; } function toCreasedNormals(geometry, creaseAngle = Math.PI / 3) { const creaseDot = Math.cos(creaseAngle); const hashMultiplier = 1.0000000001 * 100; const verts = [ new Vector3(), new Vector3(), new Vector3() ]; const tempVec1 = new Vector3(); const tempVec2 = new Vector3(); const tempNorm = new Vector3(); const tempNorm2 = new Vector3(); function hashVertex(v) { return `${~~(v.x * hashMultiplier)},${~~(v.y * hashMultiplier)},${~~(v.z * hashMultiplier)}`; } const resultGeometry = geometry.index ? geometry.toNonIndexed() : geometry; const posAttr = resultGeometry.attributes.position; const vertexMap = {}; for (let i = 0, l = posAttr.count / 3; i < l; i++) { const i3 = 3 * i; const a = verts[0].fromBufferAttribute(posAttr, i3 + 0); const b = verts[1].fromBufferAttribute(posAttr, i3 + 1); const c = verts[2].fromBufferAttribute(posAttr, i3 + 2); tempVec1.subVectors(c, b); tempVec2.subVectors(a, b); const normal = new Vector3().crossVectors(tempVec1, tempVec2).normalize(); for (let n = 0; n < 3; n++) { const vert = verts[n]; const hash = hashVertex(vert); if (!(hash in vertexMap)) vertexMap[hash] = []; vertexMap[hash].push(normal); } } const normAttr = new BufferAttribute(new Float32Array(posAttr.count * 3), 3, false); for (let i = 0, l = posAttr.count / 3; i < l; i++) { const i3 = 3 * i; const a = verts[0].fromBufferAttribute(posAttr, i3 + 0); const b = verts[1].fromBufferAttribute(posAttr, i3 + 1); const c = verts[2].fromBufferAttribute(posAttr, i3 + 2); tempVec1.subVectors(c, b); tempVec2.subVectors(a, b); tempNorm.crossVectors(tempVec1, tempVec2).normalize(); for (let n = 0; n < 3; n++) { const vert = verts[n]; const otherNormals = vertexMap[hashVertex(vert)]; 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(i3 + n, tempNorm2.x, tempNorm2.y, tempNorm2.z); } } resultGeometry.setAttribute("normal", normAttr); return resultGeometry; } //#endregion //#region node_modules/three-stdlib/modifiers/SimplifyModifier.js var __defProp$57 = Object.defineProperty; var __defNormalProp$57 = (obj, key, value) => key in obj ? __defProp$57(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$57 = (obj, key, value) => { __defNormalProp$57(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var cb = /* @__PURE__ */ new Vector3(); var ab = /* @__PURE__ */ new Vector3(); function pushIfUnique(array, object) { if (array.indexOf(object) === -1) array.push(object); } function removeFromArray(array, object) { const k = array.indexOf(object); if (k > -1) array.splice(k, 1); } var Vertex = class { constructor(v, id) { __publicField$57(this, "position"); __publicField$57(this, "id"); __publicField$57(this, "faces"); __publicField$57(this, "neighbors"); __publicField$57(this, "collapseCost"); __publicField$57(this, "collapseNeighbor"); __publicField$57(this, "minCost", 0); __publicField$57(this, "totalCost", 0); __publicField$57(this, "costCount", 0); this.position = v; this.id = id; this.faces = []; this.neighbors = []; this.collapseCost = 0; this.collapseNeighbor = null; } addUniqueNeighbor(vertex) { pushIfUnique(this.neighbors, vertex); } removeIfNonNeighbor(n) { const neighbors = this.neighbors; const faces = this.faces; const offset = neighbors.indexOf(n); if (offset === -1) return; for (let i = 0; i < faces.length; i++) if (faces[i].hasVertex(n)) return; neighbors.splice(offset, 1); } }; var Triangle = class { constructor(v1, v2, v3, a, b, c) { __publicField$57(this, "a"); __publicField$57(this, "b"); __publicField$57(this, "c"); __publicField$57(this, "v1"); __publicField$57(this, "v2"); __publicField$57(this, "v3"); __publicField$57(this, "normal", new Vector3()); this.a = a; this.b = b; this.c = c; this.v1 = v1; this.v2 = v2; this.v3 = v3; this.computeNormal(); v1.faces.push(this); v1.addUniqueNeighbor(v2); v1.addUniqueNeighbor(v3); v2.faces.push(this); v2.addUniqueNeighbor(v1); v2.addUniqueNeighbor(v3); v3.faces.push(this); v3.addUniqueNeighbor(v1); v3.addUniqueNeighbor(v2); } computeNormal() { const vA = this.v1.position; const vB = this.v2.position; const vC = this.v3.position; cb.subVectors(vC, vB); ab.subVectors(vA, vB); cb.cross(ab).normalize(); this.normal.copy(cb); } hasVertex(v) { return v === this.v1 || v === this.v2 || v === this.v3; } replaceVertex(oldv, newv) { if (oldv === this.v1) this.v1 = newv; else if (oldv === this.v2) this.v2 = newv; else if (oldv === this.v3) this.v3 = newv; removeFromArray(oldv.faces, this); newv.faces.push(this); oldv.removeIfNonNeighbor(this.v1); this.v1.removeIfNonNeighbor(oldv); oldv.removeIfNonNeighbor(this.v2); this.v2.removeIfNonNeighbor(oldv); oldv.removeIfNonNeighbor(this.v3); this.v3.removeIfNonNeighbor(oldv); this.v1.addUniqueNeighbor(this.v2); this.v1.addUniqueNeighbor(this.v3); this.v2.addUniqueNeighbor(this.v1); this.v2.addUniqueNeighbor(this.v3); this.v3.addUniqueNeighbor(this.v1); this.v3.addUniqueNeighbor(this.v2); this.computeNormal(); } }; var SimplifyModifier = class { constructor() { __publicField$57(this, "computeEdgeCollapseCost", (u, v) => { const edgelength = v.position.distanceTo(u.position); let curvature = 0; const sideFaces = []; let i, il = u.faces.length, face, sideFace; for (i = 0; i < il; i++) { face = u.faces[i]; if (face.hasVertex(v)) sideFaces.push(face); } for (i = 0; i < il; i++) { let minCurvature = 1; face = u.faces[i]; for (let j = 0; j < sideFaces.length; j++) { sideFace = sideFaces[j]; const dotProd = face.normal.dot(sideFace.normal); minCurvature = Math.min(minCurvature, (1.001 - dotProd) / 2); } curvature = Math.max(curvature, minCurvature); } const borders = 0; if (sideFaces.length < 2) curvature = 1; return edgelength * curvature + borders; }); __publicField$57(this, "computeEdgeCostAtVertex", (v) => { if (v.neighbors.length === 0) { v.collapseNeighbor = null; v.collapseCost = -.01; return; } v.collapseCost = 1e5; v.collapseNeighbor = null; for (let i = 0; i < v.neighbors.length; i++) { const collapseCost = this.computeEdgeCollapseCost(v, v.neighbors[i]); if (!v.collapseNeighbor) { v.collapseNeighbor = v.neighbors[i]; v.collapseCost = collapseCost; v.minCost = collapseCost; v.totalCost = 0; v.costCount = 0; } v.costCount++; v.totalCost += collapseCost; if (collapseCost < v.minCost) { v.collapseNeighbor = v.neighbors[i]; v.minCost = collapseCost; } } v.collapseCost = v.totalCost / v.costCount; }); __publicField$57(this, "removeFace", (f, faces) => { removeFromArray(faces, f); if (f.v1) removeFromArray(f.v1.faces, f); if (f.v2) removeFromArray(f.v2.faces, f); if (f.v3) removeFromArray(f.v3.faces, f); const vs = [ f.v1, f.v2, f.v3 ]; let v1, v2; for (let i = 0; i < 3; i++) { v1 = vs[i]; v2 = vs[(i + 1) % 3]; if (!v1 || !v2) continue; v1.removeIfNonNeighbor(v2); v2.removeIfNonNeighbor(v1); } }); __publicField$57(this, "collapse", (vertices, faces, u, v) => { if (!v) { this.removeVertex(u, vertices); return; } let i; const tmpVertices = []; for (i = 0; i < u.neighbors.length; i++) tmpVertices.push(u.neighbors[i]); for (i = u.faces.length - 1; i >= 0; i--) if (u.faces[i].hasVertex(v)) this.removeFace(u.faces[i], faces); for (i = u.faces.length - 1; i >= 0; i--) u.faces[i].replaceVertex(u, v); this.removeVertex(u, vertices); for (i = 0; i < tmpVertices.length; i++) this.computeEdgeCostAtVertex(tmpVertices[i]); }); __publicField$57(this, "minimumCostEdge", (vertices) => { let least = vertices[0]; for (let i = 0; i < vertices.length; i++) if (vertices[i].collapseCost < least.collapseCost) least = vertices[i]; return least; }); __publicField$57(this, "modify", (geometry, count) => { geometry = geometry.clone(); const attributes = geometry.attributes; for (let name in attributes) if (name !== "position") geometry.deleteAttribute(name); geometry = mergeVertices(geometry); const vertices = []; const faces = []; const positionAttribute = geometry.getAttribute("position"); for (let i = 0; i < positionAttribute.count; i++) { const vertex = new Vertex(new Vector3().fromBufferAttribute(positionAttribute, i), i); vertices.push(vertex); } const geomIndex = geometry.getIndex(); if (geomIndex !== null) for (let i = 0; i < geomIndex.count; i += 3) { const a = geomIndex.getX(i); const b = geomIndex.getX(i + 1); const c = geomIndex.getX(i + 2); const triangle = new Triangle(vertices[a], vertices[b], vertices[c], a, b, c); faces.push(triangle); } else for (let i = 0; i < positionAttribute.count; i += 3) { const a = i; const b = i + 1; const c = i + 2; const triangle = new Triangle(vertices[a], vertices[b], vertices[c], a, b, c); faces.push(triangle); } for (let i = 0, il = vertices.length; i < il; i++) this.computeEdgeCostAtVertex(vertices[i]); let nextVertex; let z = count; while (z--) { nextVertex = this.minimumCostEdge(vertices); if (!nextVertex) { console.log("THREE.SimplifyModifier: No next vertex"); break; } else this.collapse(vertices, faces, nextVertex, nextVertex.collapseNeighbor); } const simplifiedGeometry = new BufferGeometry(); const position = []; let index = []; for (let i = 0; i < vertices.length; i++) { const vertex = vertices[i].position; position.push(vertex.x, vertex.y, vertex.z); } for (let i = 0; i < faces.length; i++) { const face = faces[i]; const a = vertices.indexOf(face.v1); const b = vertices.indexOf(face.v2); const c = vertices.indexOf(face.v3); index.push(a, b, c); } simplifiedGeometry.setAttribute("position", new Float32BufferAttribute(position, 3)); simplifiedGeometry.setIndex(index); return simplifiedGeometry; }); } removeVertex(v, vertices) { console.assert(v.faces.length === 0); while (v.neighbors.length) removeFromArray(v.neighbors.pop().neighbors, v); removeFromArray(vertices, v); } }; //#endregion //#region node_modules/three-stdlib/modifiers/EdgeSplitModifier.js var __defProp$56 = Object.defineProperty; var __defNormalProp$56 = (obj, key, value) => key in obj ? __defProp$56(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$56 = (obj, key, value) => { __defNormalProp$56(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var EdgeSplitModifier = class { constructor() { __publicField$56(this, "A", new Vector3()); __publicField$56(this, "B", new Vector3()); __publicField$56(this, "C", new Vector3()); __publicField$56(this, "positions", []); __publicField$56(this, "normals", new Float32Array()); __publicField$56(this, "indexes", []); __publicField$56(this, "pointToIndexMap", []); __publicField$56(this, "splitIndexes", []); __publicField$56(this, "oldNormals", []); __publicField$56(this, "computeNormals", () => { this.normals = new Float32Array(this.indexes.length * 3); for (let i = 0; i < this.indexes.length; i += 3) { let index = this.indexes[i]; this.A.set(this.positions[3 * index], this.positions[3 * index + 1], this.positions[3 * index + 2]); index = this.indexes[i + 1]; this.B.set(this.positions[3 * index], this.positions[3 * index + 1], this.positions[3 * index + 2]); index = this.indexes[i + 2]; this.C.set(this.positions[3 * index], this.positions[3 * index + 1], this.positions[3 * index + 2]); this.C.sub(this.B); this.A.sub(this.B); const normal = this.C.cross(this.A).normalize(); for (let j = 0; j < 3; j++) { this.normals[3 * (i + j)] = normal.x; this.normals[3 * (i + j) + 1] = normal.y; this.normals[3 * (i + j) + 2] = normal.z; } } }); __publicField$56(this, "mapPositionsToIndexes", () => { this.pointToIndexMap = Array(this.positions.length / 3); for (let i = 0; i < this.indexes.length; i++) { const index = this.indexes[i]; if (this.pointToIndexMap[index] == null) this.pointToIndexMap[index] = []; this.pointToIndexMap[index].push(i); } }); __publicField$56(this, "edgeSplitToGroups", (indexes, cutOff, firstIndex) => { this.A.set(this.normals[3 * firstIndex], this.normals[3 * firstIndex + 1], this.normals[3 * firstIndex + 2]).normalize(); const result = { splitGroup: [], currentGroup: [firstIndex] }; for (let j of indexes) if (j !== firstIndex) { this.B.set(this.normals[3 * j], this.normals[3 * j + 1], this.normals[3 * j + 2]).normalize(); if (this.B.dot(this.A) < cutOff) result.splitGroup.push(j); else result.currentGroup.push(j); } return result; }); __publicField$56(this, "edgeSplit", (indexes, cutOff, original = null) => { if (indexes.length === 0) return; const groupResults = []; for (let index of indexes) groupResults.push(this.edgeSplitToGroups(indexes, cutOff, index)); let result = groupResults[0]; for (let groupResult of groupResults) if (groupResult.currentGroup.length > result.currentGroup.length) result = groupResult; if (original != null) this.splitIndexes.push({ original, indexes: result.currentGroup }); if (result.splitGroup.length) this.edgeSplit(result.splitGroup, cutOff, original || result.currentGroup[0]); }); __publicField$56(this, "modify", (geometry, cutOffAngle, tryKeepNormals = true) => { let hadNormals = false; if (geometry.attributes.normal) { hadNormals = true; geometry = geometry.clone(); if (tryKeepNormals === true && geometry.index !== null) this.oldNormals = geometry.attributes.normal.array; geometry.deleteAttribute("normal"); } if (geometry.index == null) { if (BufferGeometryUtils_exports === void 0) throw "THREE.EdgeSplitModifier relies on BufferGeometryUtils"; geometry = mergeVertices(geometry); } this.indexes = geometry.index.array; this.positions = geometry.getAttribute("position").array; this.computeNormals(); this.mapPositionsToIndexes(); this.splitIndexes = []; for (let vertexIndexes of this.pointToIndexMap) this.edgeSplit(vertexIndexes, Math.cos(cutOffAngle) - .001); const newAttributes = {}; for (let name of Object.keys(geometry.attributes)) { const oldAttribute = geometry.attributes[name]; const newArray = new oldAttribute.array.constructor((this.indexes.length + this.splitIndexes.length) * oldAttribute.itemSize); newArray.set(oldAttribute.array); newAttributes[name] = new BufferAttribute(newArray, oldAttribute.itemSize, oldAttribute.normalized); } const newIndexes = new Uint32Array(this.indexes.length); newIndexes.set(this.indexes); for (let i = 0; i < this.splitIndexes.length; i++) { const split = this.splitIndexes[i]; const index = this.indexes[split.original]; for (let attribute of Object.values(newAttributes)) for (let j = 0; j < attribute.itemSize; j++) attribute.array[(this.indexes.length + i) * attribute.itemSize + j] = attribute.array[index * attribute.itemSize + j]; for (let j of split.indexes) newIndexes[j] = this.indexes.length + i; } geometry = new BufferGeometry(); geometry.setIndex(new BufferAttribute(newIndexes, 1)); for (let name of Object.keys(newAttributes)) geometry.setAttribute(name, newAttributes[name]); if (hadNormals) { geometry.computeVertexNormals(); if (this.oldNormals !== null) { const changedNormals = new Array(this.oldNormals.length / 3).fill(false); for (let splitData of this.splitIndexes) changedNormals[splitData.original] = true; for (let i = 0; i < changedNormals.length; i++) if (changedNormals[i] === false) for (let j = 0; j < 3; j++) geometry.attributes.normal.array[3 * i + j] = this.oldNormals[3 * i + j]; } } return geometry; }); } }; //#endregion //#region node_modules/three-stdlib/modifiers/TessellateModifier.js var __defProp$55 = Object.defineProperty; var __defNormalProp$55 = (obj, key, value) => key in obj ? __defProp$55(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$55 = (obj, key, value) => { __defNormalProp$55(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var TessellateModifier = class { constructor(maxEdgeLength = .1, maxIterations = 6) { __publicField$55(this, "maxEdgeLength"); __publicField$55(this, "maxIterations"); __publicField$55(this, "modify", (geometry) => { if (geometry.index !== null) geometry = geometry.toNonIndexed(); const maxIterations = this.maxIterations; const maxEdgeLengthSquared = this.maxEdgeLength * this.maxEdgeLength; const va = new Vector3(); const vb = new Vector3(); const vc = new Vector3(); const vm = new Vector3(); const vs = [ va, vb, vc, vm ]; const na = new Vector3(); const nb = new Vector3(); const nc = new Vector3(); const nm = new Vector3(); const ns = [ na, nb, nc, nm ]; const ca = new Color(); const cb = new Color(); const cc = new Color(); const cm = new Color(); const cs = [ ca, cb, cc, cm ]; const ua = new Vector2(); const ub = new Vector2(); const uc = new Vector2(); const um = new Vector2(); const us = [ ua, ub, uc, um ]; const u2a = new Vector2(); const u2b = new Vector2(); const u2c = new Vector2(); const u2m = new Vector2(); const u2s = [ u2a, u2b, u2c, u2m ]; const attributes = geometry.attributes; const hasNormals = attributes.normal !== void 0; const hasColors = attributes.color !== void 0; const hasUVs = attributes.uv !== void 0; const hasUV1s = attributes[UV1] !== void 0; let positions = attributes.position.array; let normals = hasNormals ? attributes.normal.array : null; let colors = hasColors ? attributes.color.array : null; let uvs = hasUVs ? attributes.uv.array : null; let uv1s = hasUV1s ? attributes.uv1.array : null; let positions2 = positions; let normals2 = normals; let colors2 = colors; let uvs2 = uvs; let uv1s2 = uv1s; let iteration = 0; let tessellating = true; function addTriangle(a, b, c) { const v1 = vs[a]; const v2 = vs[b]; const v3 = vs[c]; positions2.push(v1.x, v1.y, v1.z); positions2.push(v2.x, v2.y, v2.z); positions2.push(v3.x, v3.y, v3.z); if (hasNormals) { const n1 = ns[a]; const n2 = ns[b]; const n3 = ns[c]; normals2.push(n1.x, n1.y, n1.z); normals2.push(n2.x, n2.y, n2.z); normals2.push(n3.x, n3.y, n3.z); } if (hasColors) { const c1 = cs[a]; const c2 = cs[b]; const c3 = cs[c]; colors2.push(c1.r, c1.g, c1.b); colors2.push(c2.r, c2.g, c2.b); colors2.push(c3.r, c3.g, c3.b); } if (hasUVs) { const u1 = us[a]; const u2 = us[b]; const u3 = us[c]; uvs2.push(u1.x, u1.y); uvs2.push(u2.x, u2.y); uvs2.push(u3.x, u3.y); } if (hasUV1s) { const u21 = u2s[a]; const u22 = u2s[b]; const u23 = u2s[c]; uv1s2.push(u21.x, u21.y); uv1s2.push(u22.x, u22.y); uv1s2.push(u23.x, u23.y); } } while (tessellating && iteration < maxIterations) { iteration++; tessellating = false; positions = positions2; positions2 = []; if (hasNormals) { normals = normals2; normals2 = []; } if (hasColors) { colors = colors2; colors2 = []; } if (hasUVs) { uvs = uvs2; uvs2 = []; } if (hasUV1s) { uv1s = uv1s2; uv1s2 = []; } for (let i = 0, i2 = 0, il = positions.length; i < il; i += 9, i2 += 6) { va.fromArray(positions, i + 0); vb.fromArray(positions, i + 3); vc.fromArray(positions, i + 6); if (hasNormals && normals) { na.fromArray(normals, i + 0); nb.fromArray(normals, i + 3); nc.fromArray(normals, i + 6); } if (hasColors && colors) { ca.fromArray(colors, i + 0); cb.fromArray(colors, i + 3); cc.fromArray(colors, i + 6); } if (hasUVs && uvs) { ua.fromArray(uvs, i2 + 0); ub.fromArray(uvs, i2 + 2); uc.fromArray(uvs, i2 + 4); } if (hasUV1s && uv1s) { u2a.fromArray(uv1s, i2 + 0); u2b.fromArray(uv1s, i2 + 2); u2c.fromArray(uv1s, i2 + 4); } const dab = va.distanceToSquared(vb); const dbc = vb.distanceToSquared(vc); const dac = va.distanceToSquared(vc); if (dab > maxEdgeLengthSquared || dbc > maxEdgeLengthSquared || dac > maxEdgeLengthSquared) { tessellating = true; if (dab >= dbc && dab >= dac) { vm.lerpVectors(va, vb, .5); if (hasNormals) nm.lerpVectors(na, nb, .5); if (hasColors) cm.lerpColors(ca, cb, .5); if (hasUVs) um.lerpVectors(ua, ub, .5); if (hasUV1s) u2m.lerpVectors(u2a, u2b, .5); addTriangle(0, 3, 2); addTriangle(3, 1, 2); } else if (dbc >= dab && dbc >= dac) { vm.lerpVectors(vb, vc, .5); if (hasNormals) nm.lerpVectors(nb, nc, .5); if (hasColors) cm.lerpColors(cb, cc, .5); if (hasUVs) um.lerpVectors(ub, uc, .5); if (hasUV1s) u2m.lerpVectors(u2b, u2c, .5); addTriangle(0, 1, 3); addTriangle(3, 2, 0); } else { vm.lerpVectors(va, vc, .5); if (hasNormals) nm.lerpVectors(na, nc, .5); if (hasColors) cm.lerpColors(ca, cc, .5); if (hasUVs) um.lerpVectors(ua, uc, .5); if (hasUV1s) u2m.lerpVectors(u2a, u2c, .5); addTriangle(0, 1, 3); addTriangle(3, 1, 2); } } else addTriangle(0, 1, 2); } } const geometry2 = new BufferGeometry(); geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3)); if (hasNormals) geometry2.setAttribute("normal", new Float32BufferAttribute(normals2, 3)); if (hasColors) geometry2.setAttribute("color", new Float32BufferAttribute(colors2, 3)); if (hasUVs) geometry2.setAttribute("uv", new Float32BufferAttribute(uvs2, 2)); if (hasUV1s) geometry2.setAttribute(UV1, new Float32BufferAttribute(uv1s2, 2)); return geometry2; }); this.maxEdgeLength = maxEdgeLength; this.maxIterations = maxIterations; } }; //#endregion //#region node_modules/three-stdlib/exporters/GLTFExporter.js var __defProp$54 = Object.defineProperty; var __defNormalProp$54 = (obj, key, value) => key in obj ? __defProp$54(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$54 = (obj, key, value) => { __defNormalProp$54(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; async function readAsDataURL(blob) { const buffer = await blob.arrayBuffer(); const data = btoa(String.fromCharCode(...new Uint8Array(buffer))); 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: ` varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy * 1.0,0.,.999999); } `, fragmentShader: ` uniform sampler2D blitTexture; varying vec2 vUv; void main(){ gl_FragColor = vec4(vUv.xy, 0, 1); #ifdef IS_SRGB gl_FragColor = 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 = /* @__PURE__ */ (() => { class GLTFExporter2 { constructor() { this.pluginCallbacks = []; this.register(function(writer) { return new GLTFLightExtension(writer); }); this.register(function(writer) { return new GLTFMaterialsUnlitExtension$1(writer); }); this.register(function(writer) { return new GLTFMaterialsTransmissionExtension$1(writer); }); this.register(function(writer) { return new GLTFMaterialsVolumeExtension$1(writer); }); this.register(function(writer) { return new GLTFMaterialsIorExtension$1(writer); }); this.register(function(writer) { return new GLTFMaterialsSpecularExtension$1(writer); }); this.register(function(writer) { return new GLTFMaterialsClearcoatExtension$1(writer); }); this.register(function(writer) { return new GLTFMaterialsIridescenceExtension$1(writer); }); this.register(function(writer) { return new GLTFMaterialsSheenExtension$1(writer); }); this.register(function(writer) { return new GLTFMaterialsAnisotropyExtension$1(writer); }); this.register(function(writer) { return new GLTFMaterialsEmissiveStrengthExtension$1(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 i = 0, il = this.pluginCallbacks.length; i < il; i++) plugins.push(this.pluginCallbacks[i](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); }); } } /** * Static utility functions */ __publicField$54(GLTFExporter2, "Utils", { insertKeyframe: function(track, time) { const tolerance = .001; 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 index; if (track.times.length === 0) { times[0] = time; for (let i = 0; i < valueSize; i++) values[i] = 0; index = 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); index = 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); index = times.length - 1; } else for (let i = 0; i < track.times.length; i++) { if (Math.abs(track.times[i] - time) < tolerance) return i; if (track.times[i] < time && track.times[i + 1] > time) { times.set(track.times.slice(0, i + 1), 0); times[i + 1] = time; times.set(track.times.slice(i + 1), i + 2); values.set(track.values.slice(0, (i + 1) * valueSize), 0); values.set(interpolant.evaluate(time), (i + 1) * valueSize); values.set(track.values.slice((i + 1) * valueSize), (i + 2) * valueSize); index = i + 1; break; } } track.times = times; track.values = values; return index; }, mergeMorphTargetTracks: function(clip, root) { const tracks = []; const mergedTracks = {}; const sourceTracks = clip.tracks; for (let i = 0; i < sourceTracks.length; ++i) { let sourceTrack = sourceTracks[i]; const sourceTrackBinding = PropertyBinding.parseTrackName(sourceTrack.name); const sourceTrackNode = PropertyBinding.findNode(root, sourceTrackBinding.nodeName); if (sourceTrackBinding.propertyName !== "morphTargetInfluences" || sourceTrackBinding.propertyIndex === void 0) { tracks.push(sourceTrack); continue; } if (sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear) { if (sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation."); console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."); sourceTrack = sourceTrack.clone(); sourceTrack.setInterpolation(InterpolateLinear); } const targetCount = sourceTrackNode.morphTargetInfluences.length; const targetIndex = sourceTrackNode.morphTargetDictionary[sourceTrackBinding.propertyIndex]; if (targetIndex === void 0) throw new Error("THREE.GLTFExporter: Morph target name not found: " + sourceTrackBinding.propertyIndex); let mergedTrack; if (mergedTracks[sourceTrackNode.uuid] === void 0) { mergedTrack = sourceTrack.clone(); const 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$1 = { 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$1.NEAREST; THREE_TO_WEBGL[NearestMipmapNearestFilter] = WEBGL_CONSTANTS$1.NEAREST_MIPMAP_NEAREST; THREE_TO_WEBGL[NearestMipmapLinearFilter] = WEBGL_CONSTANTS$1.NEAREST_MIPMAP_LINEAR; THREE_TO_WEBGL[LinearFilter] = WEBGL_CONSTANTS$1.LINEAR; THREE_TO_WEBGL[LinearMipmapNearestFilter] = WEBGL_CONSTANTS$1.LINEAR_MIPMAP_NEAREST; THREE_TO_WEBGL[LinearMipmapLinearFilter] = WEBGL_CONSTANTS$1.LINEAR_MIPMAP_LINEAR; THREE_TO_WEBGL[ClampToEdgeWrapping] = WEBGL_CONSTANTS$1.CLAMP_TO_EDGE; THREE_TO_WEBGL[RepeatWrapping] = WEBGL_CONSTANTS$1.REPEAT; THREE_TO_WEBGL[MirroredRepeatWrapping] = WEBGL_CONSTANTS$1.MIRRORED_REPEAT; var PATH_PROPERTIES$1 = { scale: "scale", position: "translation", quaternion: "rotation", morphTargetInfluences: "weights" }; var DEFAULT_SPECULAR_COLOR = /* @__PURE__ */ 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, index) { return element === array2[index]; }); } function stringToArrayBuffer(text) { return new TextEncoder().encode(text).buffer; } function isIdentityMatrix(matrix) { return equalArray(matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]); } function getMinMax(attribute, start, count) { const output = { min: new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY), max: new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY) }; for (let i = start; i < start + count; i++) for (let a = 0; a < attribute.itemSize; a++) { let value; if (attribute.itemSize > 4) value = attribute.array[i * attribute.itemSize + a]; else { if (a === 0) value = attribute.getX(i); else if (a === 1) value = attribute.getY(i); else if (a === 2) value = attribute.getZ(i); else if (a === 3) value = attribute.getW(i); if (attribute.normalized === true) value = MathUtils.normalize(value, attribute.array); } output.min[a] = Math.min(output.min[a], value); output.max[a] = Math.max(output.max[a], 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 i = arrayBuffer.byteLength; i < paddedLength; i++) array[i] = paddingByte; return array.buffer; } return arrayBuffer; } function getCanvas() { if (typeof document === "undefined" && typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(1, 1); return document.createElement("canvas"); } function getToBlobPromise(canvas, mimeType) { if (canvas.toBlob !== void 0) return new Promise((resolve) => canvas.toBlob(resolve, mimeType)); let quality; if (mimeType === "image/jpeg") quality = .92; else if (mimeType === "image/webp") quality = .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({ 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 = /* @__PURE__ */ new DataView(/* @__PURE__ */ 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 = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); jsonChunkPrefix.setUint32(0, jsonChunk.byteLength, true); jsonChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_JSON, true); const header = /* @__PURE__ */ 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); new Blob([ header, jsonChunkPrefix, jsonChunk, binaryChunkPrefix, binaryChunk ], { type: "application/octet-stream" }).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); } return this.uids.get(attribute).get(isRelativeCopy); } /** * Checks if normal attribute values are normalized. * * @param {BufferAttribute} normal * @returns {Boolean} */ isNormalizedNormalAttribute(normal) { if (this.cache.attributesNormalized.has(normal)) return false; const v = new Vector3(); for (let i = 0, il = normal.count; i < il; i++) if (Math.abs(v.fromBufferAttribute(normal, i).length() - 1) > 5e-4) return false; return true; } /** * Creates normalized normal buffer attribute. * * @param {BufferAttribute} normal * @returns {BufferAttribute} * */ createNormalizedNormalAttribute(normal) { const cache = this.cache; if (cache.attributesNormalized.has(normal)) return cache.attributesNormalized.get(normal); const attribute = normal.clone(); const v = new Vector3(); for (let i = 0, il = attribute.count; i < il; i++) { v.fromBufferAttribute(attribute, i); if (v.x === 0 && v.y === 0 && v.z === 0) v.setX(1); else v.normalize(); attribute.setXYZ(i, v.x, v.y, v.z); } cache.attributesNormalized.set(normal, attribute); return attribute; } /** * Applies a texture transform, if present, to the map definition. Requires * the KHR_texture_transform extension. * * @param {Object} mapDef * @param {THREE.Texture} texture */ applyTextureTransform(mapDef, texture) { let didTransform = false; const transformDef = {}; if (texture.offset.x !== 0 || texture.offset.y !== 0) { transformDef.offset = texture.offset.toArray(); didTransform = true; } if (texture.rotation !== 0) { transformDef.rotation = texture.rotation; didTransform = true; } if (texture.repeat.x !== 1 || texture.repeat.y !== 1) { transformDef.scale = texture.repeat.toArray(); didTransform = true; } if (didTransform) { mapDef.extensions = mapDef.extensions || {}; mapDef.extensions["KHR_texture_transform"] = transformDef; this.extensionsUsed["KHR_texture_transform"] = true; } } buildMetalRoughTexture(metalnessMap, roughnessMap) { if (metalnessMap === roughnessMap) return metalnessMap; function getEncodingConversion(map) { if ("colorSpace" in map ? map.colorSpace === "srgb" : map.encoding === 3001) return function SRGBToLinear(c) { return c < .04045 ? c * .0773993808 : Math.pow(c * .9478672986 + .0521327014, 2.4); }; return function LinearToLinear(c) { return c; }; } 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 context = canvas.getContext("2d"); context.fillStyle = "#00ffff"; context.fillRect(0, 0, width, height); const composite = context.getImageData(0, 0, width, height); if (metalness) { context.drawImage(metalness, 0, 0, width, height); const convert = getEncodingConversion(metalnessMap); const data = context.getImageData(0, 0, width, height).data; for (let i = 2; i < data.length; i += 4) composite.data[i] = convert(data[i] / 256) * 256; } if (roughness) { context.drawImage(roughness, 0, 0, width, height); const convert = getEncodingConversion(roughnessMap); const data = context.getImageData(0, 0, width, height).data; for (let i = 1; i < data.length; i += 4) composite.data[i] = convert(data[i] / 256) * 256; } context.putImageData(composite, 0, 0); const texture = (metalnessMap || roughnessMap).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(buffer) { const json = this.json; const buffers = this.buffers; if (!json.buffers) json.buffers = [{ byteLength: 0 }]; buffers.push(buffer); return 0; } /** * Process and generate a BufferView * @param {BufferAttribute} attribute * @param {number} componentType * @param {number} start * @param {number} count * @param {number} target (Optional) Target usage of the BufferView * @return {Object} */ processBufferView(attribute, componentType, start, count, target) { const json = this.json; if (!json.bufferViews) json.bufferViews = []; let componentSize; switch (componentType) { case WEBGL_CONSTANTS$1.BYTE: case WEBGL_CONSTANTS$1.UNSIGNED_BYTE: componentSize = 1; break; case WEBGL_CONSTANTS$1.SHORT: case WEBGL_CONSTANTS$1.UNSIGNED_SHORT: componentSize = 2; break; default: componentSize = 4; } let byteStride = attribute.itemSize * componentSize; if (target === WEBGL_CONSTANTS$1.ARRAY_BUFFER) byteStride = Math.ceil(byteStride / 4) * 4; const byteLength = getPaddedBufferSize(count * byteStride); const dataView = new DataView(new ArrayBuffer(byteLength)); let offset = 0; for (let i = start; i < start + count; i++) { for (let a = 0; a < attribute.itemSize; a++) { let value; if (attribute.itemSize > 4) value = attribute.array[i * attribute.itemSize + a]; else { if (a === 0) value = attribute.getX(i); else if (a === 1) value = attribute.getY(i); else if (a === 2) value = attribute.getZ(i); else if (a === 3) value = attribute.getW(i); if (attribute.normalized === true) value = MathUtils.normalize(value, attribute.array); } if (componentType === WEBGL_CONSTANTS$1.FLOAT) dataView.setFloat32(offset, value, true); else if (componentType === WEBGL_CONSTANTS$1.INT) dataView.setInt32(offset, value, true); else if (componentType === WEBGL_CONSTANTS$1.UNSIGNED_INT) dataView.setUint32(offset, value, true); else if (componentType === WEBGL_CONSTANTS$1.SHORT) dataView.setInt16(offset, value, true); else if (componentType === WEBGL_CONSTANTS$1.UNSIGNED_SHORT) dataView.setUint16(offset, value, true); else if (componentType === WEBGL_CONSTANTS$1.BYTE) dataView.setInt8(offset, value); else if (componentType === WEBGL_CONSTANTS$1.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 (target !== void 0) bufferViewDef.target = target; if (target === WEBGL_CONSTANTS$1.ARRAY_BUFFER) bufferViewDef.byteStride = byteStride; this.byteOffset += byteLength; json.bufferViews.push(bufferViewDef); return { id: json.bufferViews.length - 1, byteLength: 0 }; } /** * 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 buffer = getPaddedArrayBuffer(result); const bufferViewDef = { buffer: writer.processBuffer(buffer), byteOffset: writer.byteOffset, byteLength: buffer.byteLength }; writer.byteOffset += buffer.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, geometry, start, count) { const json = this.json; const types = { 1: "SCALAR", 2: "VEC2", 3: "VEC3", 4: "VEC4", 9: "MAT3", 16: "MAT4" }; let componentType; if (attribute.array.constructor === Float32Array) componentType = WEBGL_CONSTANTS$1.FLOAT; else if (attribute.array.constructor === Int32Array) componentType = WEBGL_CONSTANTS$1.INT; else if (attribute.array.constructor === Uint32Array) componentType = WEBGL_CONSTANTS$1.UNSIGNED_INT; else if (attribute.array.constructor === Int16Array) componentType = WEBGL_CONSTANTS$1.SHORT; else if (attribute.array.constructor === Uint16Array) componentType = WEBGL_CONSTANTS$1.UNSIGNED_SHORT; else if (attribute.array.constructor === Int8Array) componentType = WEBGL_CONSTANTS$1.BYTE; else if (attribute.array.constructor === Uint8Array) componentType = WEBGL_CONSTANTS$1.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 (geometry !== void 0) bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS$1.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS$1.ARRAY_BUFFER; const bufferView = this.processBufferView(attribute, componentType, start, count, bufferViewTarget); const accessorDef = { bufferView: bufferView.id, byteOffset: bufferView.byteOffset, componentType, count, max: minMax.max, min: minMax.min, type: types[attribute.itemSize] }; if (attribute.normalized === true) accessorDef.normalized = true; if (!json.accessors) json.accessors = []; return json.accessors.push(accessorDef) - 1; } /** * Process image * @param {Image} image to process * @param {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 !== 1023) 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 i = 0; i < data.length; i += 4) { data[i + 0] = image.data[i + 0]; data[i + 1] = image.data[i + 1]; data[i + 2] = image.data[i + 2]; data[i + 3] = image.data[i + 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 index = json.images.push(imageDef) - 1; cachedImages[key] = index; return index; } 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(map) { const json = this.json; if (!json.samplers) json.samplers = []; const samplerDef = { magFilter: THREE_TO_WEBGL[map.magFilter], minFilter: THREE_TO_WEBGL[map.minFilter], wrapS: THREE_TO_WEBGL[map.wrapS], wrapT: THREE_TO_WEBGL[map.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(map) { const options = this.options; const cache = this.cache; const json = this.json; if (cache.textures.has(map)) return cache.textures.get(map); if (!json.textures) json.textures = []; if (map instanceof CompressedTexture) map = decompress(map, options.maxTextureSize); let mimeType = map.userData.mimeType; if (mimeType === "image/webp") mimeType = "image/png"; const textureDef = { sampler: this.processSampler(map), source: this.processImage(map.image, map.format, map.flipY, mimeType) }; if (map.name) textureDef.name = map.name; this._invokeAll(function(ext) { ext.writeTexture && ext.writeTexture(map, textureDef); }); const index = json.textures.push(textureDef) - 1; cache.textures.set(map, index); return index; } /** * 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 = .5; materialDef.pbrMetallicRoughness.roughnessFactor = .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; if (Math.max(emissive.r, emissive.g, emissive.b) > 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 === 2) 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 index = json.materials.push(materialDef) - 1; cache.materials.set(material, index); return index; } /** * 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 i = 0, l = mesh.material.length; i < l; i++) meshCacheKeyParts.push(mesh.material[i].uuid); else meshCacheKeyParts.push(mesh.material.uuid); const meshCacheKey = meshCacheKeyParts.join(":"); if (cache.meshes.has(meshCacheKey)) return cache.meshes.get(meshCacheKey); const geometry = mesh.geometry; let mode; if (mesh.isLineSegments) mode = WEBGL_CONSTANTS$1.LINES; else if (mesh.isLineLoop) mode = WEBGL_CONSTANTS$1.LINE_LOOP; else if (mesh.isLine) mode = WEBGL_CONSTANTS$1.LINE_STRIP; else if (mesh.isPoints) mode = WEBGL_CONSTANTS$1.POINTS; else mode = mesh.material.wireframe ? WEBGL_CONSTANTS$1.LINES : WEBGL_CONSTANTS$1.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 = geometry.getAttribute("normal"); if (originalNormal !== void 0 && !this.isNormalizedNormalAttribute(originalNormal)) { console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."); geometry.setAttribute("normal", this.createNormalizedNormalAttribute(originalNormal)); } let modifiedAttribute = null; for (let attributeName in geometry.attributes) { if (attributeName.slice(0, 5) === "morph") continue; const attribute = geometry.attributes[attributeName]; attributeName = nameConversion[attributeName] || attributeName.toUpperCase(); if (!/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.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, geometry); if (accessor !== null) { if (!attributeName.startsWith("_")) this.detectMeshQuantization(attributeName, attribute); attributes[attributeName] = accessor; cache.attributes.set(this.getUID(attribute), accessor); } } if (originalNormal !== void 0) geometry.setAttribute("normal", originalNormal); if (Object.keys(attributes).length === 0) return null; if (mesh.morphTargetInfluences !== void 0 && mesh.morphTargetInfluences.length > 0) { const weights = []; const targetNames = []; const reverseDictionary = {}; if (mesh.morphTargetDictionary !== void 0) for (const key in mesh.morphTargetDictionary) reverseDictionary[mesh.morphTargetDictionary[key]] = key; for (let i = 0; i < mesh.morphTargetInfluences.length; ++i) { const target = {}; let warned = false; for (const attributeName in geometry.morphAttributes) { if (attributeName !== "position" && attributeName !== "normal") { if (!warned) { console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."); warned = true; } continue; } const attribute = geometry.morphAttributes[attributeName][i]; const gltfAttributeName = attributeName.toUpperCase(); const baseAttribute = geometry.attributes[attributeName]; if (cache.attributes.has(this.getUID(attribute, true))) { target[gltfAttributeName] = cache.attributes.get(this.getUID(attribute, true)); continue; } const relativeAttribute = attribute.clone(); if (!geometry.morphTargetsRelative) for (let j = 0, jl = attribute.count; j < jl; j++) for (let a = 0; a < attribute.itemSize; a++) { if (a === 0) relativeAttribute.setX(j, attribute.getX(j) - baseAttribute.getX(j)); if (a === 1) relativeAttribute.setY(j, attribute.getY(j) - baseAttribute.getY(j)); if (a === 2) relativeAttribute.setZ(j, attribute.getZ(j) - baseAttribute.getZ(j)); if (a === 3) relativeAttribute.setW(j, attribute.getW(j) - baseAttribute.getW(j)); } target[gltfAttributeName] = this.processAccessor(relativeAttribute, geometry); cache.attributes.set(this.getUID(baseAttribute, true), target[gltfAttributeName]); } targets.push(target); weights.push(mesh.morphTargetInfluences[i]); if (mesh.morphTargetDictionary !== void 0) targetNames.push(reverseDictionary[i]); } meshDef.weights = weights; if (targetNames.length > 0) { meshDef.extras = {}; meshDef.extras.targetNames = targetNames; } } const isMultiMaterial = Array.isArray(mesh.material); if (isMultiMaterial && geometry.groups.length === 0) return null; const materials = isMultiMaterial ? mesh.material : [mesh.material]; const groups = isMultiMaterial ? geometry.groups : [{ materialIndex: 0, start: void 0, count: void 0 }]; for (let i = 0, il = groups.length; i < il; i++) { const primitive = { mode, attributes }; this.serializeUserData(geometry, primitive); if (targets.length > 0) primitive.targets = targets; if (geometry.index !== null) { let cacheKey = this.getUID(geometry.index); if (groups[i].start !== void 0 || groups[i].count !== void 0) cacheKey += ":" + groups[i].start + ":" + groups[i].count; if (cache.attributes.has(cacheKey)) primitive.indices = cache.attributes.get(cacheKey); else { primitive.indices = this.processAccessor(geometry.index, geometry, groups[i].start, groups[i].count); cache.attributes.set(cacheKey, primitive.indices); } if (primitive.indices === null) delete primitive.indices; } const material = this.processMaterial(materials[groups[i].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 index = json.meshes.push(meshDef) - 1; cache.meshes.set(meshCacheKey, index); return index; } /** * 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 ? .001 : camera.far, znear: camera.near < 0 ? 0 : camera.near }; else cameraDef.perspective = { aspectRatio: camera.aspect, yfov: MathUtils.degToRad(camera.fov), zfar: camera.far <= 0 ? .001 : camera.far, znear: camera.near < 0 ? 0 : camera.near }; if (camera.name !== "") cameraDef.name = camera.type; return json.cameras.push(cameraDef) - 1; } /** * Creates glTF animation entry from AnimationClip object. * * Status: * - Only properties listed in PATH_PROPERTIES may be animated. * * @param {THREE.AnimationClip} clip * @param {THREE.Object3D} root * @return {number|null} */ processAnimation(clip, root) { const json = this.json; const nodeMap = this.nodeMap; if (!json.animations) json.animations = []; clip = GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(), root); const tracks = clip.tracks; const channels = []; const samplers = []; for (let i = 0; i < tracks.length; ++i) { const track = tracks[i]; const trackBinding = PropertyBinding.parseTrackName(track.name); let trackNode = PropertyBinding.findNode(root, trackBinding.nodeName); const trackProperty = PATH_PROPERTIES$1[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$1.morphTargetInfluences) outputItemSize /= trackNode.morphTargetInfluences.length; let interpolation; if (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true) { interpolation = "CUBICSPLINE"; outputItemSize /= 3; } else if (track.getInterpolation() === 2300) interpolation = "STEP"; else interpolation = "LINEAR"; samplers.push({ input: this.processAccessor(new BufferAttribute(track.times, inputItemSize)), output: this.processAccessor(new BufferAttribute(track.values, outputItemSize)), interpolation }); channels.push({ sampler: samplers.length - 1, target: { node: nodeMap.get(trackNode), path: trackProperty } }); } json.animations.push({ name: clip.name || "clip_" + json.animations.length, samplers, channels }); return json.animations.length - 1; } /** * @param {THREE.Object3D} object * @return {number|null} */ processSkin(object) { const json = this.json; const nodeMap = this.nodeMap; const node = json.nodes[nodeMap.get(object)]; const skeleton = object.skeleton; if (skeleton === void 0) return null; const rootJoint = object.skeleton.bones[0]; if (rootJoint === void 0) return null; const joints = []; const inverseBindMatrices = new Float32Array(skeleton.bones.length * 16); const temporaryBoneInverse = new Matrix4(); for (let i = 0; i < skeleton.bones.length; ++i) { joints.push(nodeMap.get(skeleton.bones[i])); temporaryBoneInverse.copy(skeleton.boneInverses[i]); temporaryBoneInverse.multiply(object.bindMatrix).toArray(inverseBindMatrices, i * 16); } if (json.skins === void 0) json.skins = []; json.skins.push({ inverseBindMatrices: this.processAccessor(new BufferAttribute(inverseBindMatrices, 16)), joints, skeleton: nodeMap.get(rootJoint) }); return node.skin = json.skins.length - 1; } /** * 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 rotation = object.quaternion.toArray(); const position = object.position.toArray(); const scale = object.scale.toArray(); if (!equalArray(rotation, [ 0, 0, 0, 1 ])) nodeDef.rotation = rotation; if (!equalArray(position, [ 0, 0, 0 ])) nodeDef.translation = position; if (!equalArray(scale, [ 1, 1, 1 ])) nodeDef.scale = scale; } 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 i = 0, l = object.children.length; i < l; i++) { const child = object.children[i]; 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 i = 0, l = scene.children.length; i < l; i++) { const child = scene.children[i]; 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 i = 0; i < objects.length; i++) scene.children.push(objects[i]); 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 i = 0; i < input.length; i++) if (input[i] instanceof Scene) this.processScene(input[i]); else objectsWithoutScene.push(input[i]); if (objectsWithoutScene.length > 0) this.processObjects(objectsWithoutScene); for (let i = 0; i < this.skins.length; ++i) this.processSkin(this.skins[i]); for (let i = 0; i < options.animations.length; ++i) this.processAnimation(options.animations[i], input[0]); this._invokeAll(function(ext) { ext.afterParse && ext.afterParse(input); }); } _invokeAll(func) { for (let i = 0, il = this.plugins.length; i < il; i++) func(this.plugins[i]); } }; var GLTFLightExtension = class { constructor(writer) { this.writer = writer; this.name = "KHR_lights_punctual"; } writeNode(light, nodeDef) { if (!light.isLight) return; if (!light.isDirectionalLight && !light.isPointLight && !light.isSpotLight) { console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.", light); return; } const writer = this.writer; const json = writer.json; const extensionsUsed = writer.extensionsUsed; const lightDef = {}; if (light.name) lightDef.name = light.name; lightDef.color = light.color.toArray(); lightDef.intensity = light.intensity; if (light.isDirectionalLight) lightDef.type = "directional"; else if (light.isPointLight) { lightDef.type = "point"; if (light.distance > 0) lightDef.range = light.distance; } else if (light.isSpotLight) { lightDef.type = "spot"; if (light.distance > 0) lightDef.range = light.distance; lightDef.spot = {}; lightDef.spot.innerConeAngle = (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$1 = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_unlit"; } writeMaterial(material, materialDef) { if (!material.isMeshBasicMaterial) return; const extensionsUsed = this.writer.extensionsUsed; materialDef.extensions = materialDef.extensions || {}; materialDef.extensions[this.name] = {}; extensionsUsed[this.name] = true; materialDef.pbrMetallicRoughness.metallicFactor = 0; materialDef.pbrMetallicRoughness.roughnessFactor = .9; } }; var GLTFMaterialsClearcoatExtension$1 = 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$1 = 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$1 = 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$1 = 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$1 = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_ior"; } writeMaterial(material, materialDef) { if (!material.isMeshPhysicalMaterial || material.ior === 1.5) return; const extensionsUsed = this.writer.extensionsUsed; const extensionDef = {}; extensionDef.ior = material.ior; materialDef.extensions = materialDef.extensions || {}; materialDef.extensions[this.name] = extensionDef; extensionsUsed[this.name] = true; } }; var GLTFMaterialsSpecularExtension$1 = 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$1 = 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$1 = 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$1 = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_emissive_strength"; } writeMaterial(material, materialDef) { if (!material.isMeshStandardMaterial || material.emissiveIntensity === 1) return; const extensionsUsed = this.writer.extensionsUsed; const extensionDef = {}; extensionDef.emissiveStrength = material.emissiveIntensity; materialDef.extensions = materialDef.extensions || {}; materialDef.extensions[this.name] = extensionDef; extensionsUsed[this.name] = true; } }; //#endregion //#region node_modules/three-stdlib/node_modules/fflate/esm/browser.js var u8 = Uint8Array, u16 = Uint16Array, 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, 0, 0, 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, 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 b = new u16(31); for (var i = 0; i < 31; ++i) b[i] = start += 1 << eb[i - 1]; var r = new u32(b[30]); for (var i = 1; i < 30; ++i) for (var j = b[i]; j < b[i + 1]; ++j) r[j] = j - b[i] << 5 | i; return [b, r]; }; var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1]; fl[28] = 258, revfl[258] = 28; var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1]; var rev = new u16(32768); for (var i$1 = 0; i$1 < 32768; ++i$1) { var x = (i$1 & 43690) >>> 1 | (i$1 & 21845) << 1; x = (x & 52428) >>> 2 | (x & 13107) << 2; x = (x & 61680) >>> 4 | (x & 3855) << 4; rev[i$1] = ((x & 65280) >>> 8 | (x & 255) << 8) >>> 1; } var hMap = (function(cd, mb, r) { var s = cd.length; var i = 0; var l = new u16(mb); for (; i < s; ++i) ++l[cd[i] - 1]; var le = new u16(mb); for (i = 0; i < mb; ++i) le[i] = le[i - 1] + l[i - 1] << 1; var co; if (r) { co = new u16(1 << mb); var rvb = 15 - mb; for (i = 0; i < s; ++i) if (cd[i]) { var sv = i << 4 | cd[i]; var r_1 = mb - cd[i]; var v = le[cd[i] - 1]++ << r_1; for (var m = v | (1 << r_1) - 1; v <= m; ++v) co[rev[v] >>> rvb] = sv; } } else { co = new u16(s); for (i = 0; i < s; ++i) if (cd[i]) co[i] = rev[le[cd[i] - 1]++] >>> 15 - cd[i]; } return co; }); var flt = new u8(288); for (var i$1 = 0; i$1 < 144; ++i$1) flt[i$1] = 8; for (var i$1 = 144; i$1 < 256; ++i$1) flt[i$1] = 9; for (var i$1 = 256; i$1 < 280; ++i$1) flt[i$1] = 7; for (var i$1 = 280; i$1 < 288; ++i$1) flt[i$1] = 8; var fdt = new u8(32); for (var i$1 = 0; i$1 < 32; ++i$1) fdt[i$1] = 5; var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); var max = function(a) { var m = a[0]; for (var i = 1; i < a.length; ++i) if (a[i] > m) m = a[i]; return m; }; var bits = function(d, p, m) { var o = p / 8 | 0; return (d[o] | d[o + 1] << 8) >> (p & 7) & m; }; var bits16 = function(d, p) { var o = p / 8 | 0; return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7); }; var shft = function(p) { return (p / 8 | 0) + (p & 7 && 1); }; var slc = function(v, s, e) { if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; var n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s); n.set(v.subarray(s, e)); return n; }; 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(l) { var bl = buf.length; if (l > bl) { var nbuf = new u8(Math.max(bl * 2, l)); 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 s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l; if (t > sl) { if (noSt) throw "unexpected EOF"; break; } if (noBuf) cbuf(bt + l); buf.set(dat.subarray(s, t), bt); st.b = bt += l, st.p = pos = t * 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 i = 0; i < hcLen; ++i) clt[clim[i]] = bits(dat, pos + i * 3, 7); pos += hcLen * 3; var clb = max(clt), clbmsk = (1 << clb) - 1; var clm = hMap(clt, clb, 1); for (var i = 0; i < tl;) { var r = clm[bits(dat, pos, clbmsk)]; pos += r & 15; var s = r >>> 4; if (s < 16) ldt[i++] = s; else { var c = 0, n = 0; if (s == 16) n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; else if (s == 17) n = 3 + bits(dat, pos, 7), pos += 3; else if (s == 18) n = 11 + bits(dat, pos, 127), pos += 7; while (n--) ldt[i++] = c; } } 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 c = lm[bits16(dat, pos) & lms], sym = c >>> 4; pos += c & 15; if (pos > tbts) { if (noSt) throw "unexpected EOF"; break; } if (!c) throw "invalid length/literal"; if (sym < 256) buf[bt++] = sym; else if (sym == 256) { lpos = pos, lm = null; break; } else { var add = sym - 254; if (sym > 264) { var i = sym - 257, b = fleb[i]; add = bits(dat, pos, (1 << b) - 1) + fl[i]; pos += b; } var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; if (!d) throw "invalid distance"; pos += d & 15; var dt = fd[dsym]; if (dsym > 3) { var b = fdeb[dsym]; dt += bits16(dat, pos) & (1 << b) - 1, pos += b; } if (pos > tbts) { if (noSt) throw "unexpected EOF"; break; } if (noBuf) cbuf(bt + 131072); var end = bt + add; 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(d, p, v) { v <<= p & 7; var o = p / 8 | 0; d[o] |= v; d[o + 1] |= v >>> 8; }; var wbits16 = function(d, p, v) { v <<= p & 7; var o = p / 8 | 0; d[o] |= v; d[o + 1] |= v >>> 8; d[o + 2] |= v >>> 16; }; var hTree = function(d, mb) { var t = []; for (var i = 0; i < d.length; ++i) if (d[i]) t.push({ s: i, f: d[i] }); var s = t.length; var t2 = t.slice(); if (!s) return [et, 0]; if (s == 1) { var v = new u8(t[0].s + 1); v[t[0].s] = 1; return [v, 1]; } t.sort(function(a, b) { return a.f - b.f; }); t.push({ s: -1, f: 25001 }); var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; t[0] = { s: -1, f: l.f + r.f, l, r }; while (i1 != s - 1) { l = t[t[i0].f < t[i2].f ? i0++ : i2++]; r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; t[i1++] = { s: -1, f: l.f + r.f, l, r }; } var maxSym = t2[0].s; for (var i = 1; i < s; ++i) if (t2[i].s > maxSym) maxSym = t2[i].s; var tr = new u16(maxSym + 1); var mbt = ln(t[i1 - 1], tr, 0); if (mbt > mb) { var i = 0, dt = 0; var lft = mbt - mb, cst = 1 << lft; t2.sort(function(a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); for (; i < s; ++i) { var i2_1 = t2[i].s; if (tr[i2_1] > mb) { dt += cst - (1 << mbt - tr[i2_1]); tr[i2_1] = mb; } else break; } dt >>>= lft; while (dt > 0) { var i2_2 = t2[i].s; if (tr[i2_2] < mb) dt -= 1 << mb - tr[i2_2]++ - 1; else ++i; } for (; i >= 0 && dt; --i) { var i2_3 = t2[i].s; if (tr[i2_3] == mb) { --tr[i2_3]; ++dt; } } mbt = mb; } return [new u8(tr), mbt]; }; var ln = function(n, l, d) { return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d; }; var lc = function(c) { var s = c.length; while (s && !c[--s]); var cl = new u16(++s); var cli = 0, cln = c[0], cls = 1; var w = function(v) { cl[cli++] = v; }; for (var i = 1; i <= s; ++i) if (c[i] == cln && i != s) ++cls; else { if (!cln && cls > 2) { for (; cls > 138; cls -= 138) w(32754); if (cls > 2) { w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305); cls = 0; } } else if (cls > 3) { w(cln), --cls; for (; cls > 6; cls -= 6) w(8304); if (cls > 2) w(cls - 3 << 5 | 8208), cls = 0; } while (cls--) w(cln); cls = 1; cln = c[i]; } return [cl.subarray(0, cli), s]; }; var clen = function(cf, cl) { var l = 0; for (var i = 0; i < cl.length; ++i) l += cf[i] * cl[i]; return l; }; var wfblk = function(out, pos, dat) { var s = dat.length; var o = shft(pos + 2); out[o] = s & 255; out[o + 1] = s >>> 8; out[o + 2] = out[o] ^ 255; out[o + 3] = out[o + 1] ^ 255; for (var i = 0; i < s; ++i) out[o + i + 4] = dat[i]; return (o + 4 + s) * 8; }; var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) { wbits(out, p++, final); ++lf[256]; var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1]; var _b = hTree(df, 15), ddt = _b[0], mdb = _b[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 i = 0; i < lclt.length; ++i) lcfreq[lclt[i] & 31]++; for (var i = 0; i < lcdt.length; ++i) lcfreq[lcdt[i] & 31]++; var _e = hTree(lcfreq, 7), lct = _e[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(out, p, dat.subarray(bs, bs + bl)); var lm, ll, dm, dl; wbits(out, p, 1 + (dtlen < ftlen)), p += 2; if (dtlen < ftlen) { lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; var llm = hMap(lct, mlcb, 0); wbits(out, p, nlc - 257); wbits(out, p + 5, ndc - 1); wbits(out, p + 10, nlcc - 4); p += 14; for (var i = 0; i < nlcc; ++i) wbits(out, p + 3 * i, lct[clim[i]]); p += 3 * nlcc; var lcts = [lclt, lcdt]; for (var it = 0; it < 2; ++it) { var clct = lcts[it]; for (var i = 0; i < clct.length; ++i) { var len = clct[i] & 31; wbits(out, p, llm[len]), p += lct[len]; if (len > 15) wbits(out, p, clct[i] >>> 5 & 127), p += clct[i] >>> 12; } } } else lm = flm, ll = flt, dm = fdm, dl = fdt; for (var i = 0; i < li; ++i) if (syms[i] > 255) { var len = syms[i] >>> 18 & 31; wbits16(out, p, lm[len + 257]), p += ll[len + 257]; if (len > 7) wbits(out, p, syms[i] >>> 23 & 31), p += fleb[len]; var dst = syms[i] & 31; wbits16(out, p, dm[dst]), p += dl[dst]; if (dst > 3) wbits16(out, p, syms[i] >>> 5 & 8191), p += fdeb[dst]; } else wbits16(out, p, lm[syms[i]]), p += ll[syms[i]]; wbits16(out, p, lm[256]); return p + ll[256]; }; var deo = /*#__PURE__*/ new u32([ 65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632 ]); var et = /*#__PURE__*/ new u8(0); var dflt = function(dat, lvl, plvl, pre, post, lst) { var s = dat.length; var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7e3)) + post); var w = o.subarray(pre, o.length - post); var pos = 0; if (!lvl || s < 8) for (var i = 0; i <= s; i += 65535) { var e = i + 65535; if (e < s) pos = wfblk(w, pos, dat.subarray(i, e)); else { w[i] = lst; pos = wfblk(w, pos, dat.subarray(i, s)); } } else { var opt = deo[lvl - 1]; var n = opt >>> 13, c = 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(i) { return (dat[i] ^ dat[i + 1] << bs1_1 ^ dat[i + 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, i = 0, li = 0, wi = 0, bs = 0; for (; i < s; ++i) { var hv = hsh(i); var imod = i & 32767, pimod = head[hv]; prev[imod] = pimod; head[hv] = imod; if (wi <= i) { var rem = s - i; if ((lc_1 > 7e3 || li > 24576) && rem > 423) { pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); li = lc_1 = eb = 0, bs = i; for (var j = 0; j < 286; ++j) lf[j] = 0; for (var j = 0; j < 30; ++j) df[j] = 0; } var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767; if (rem > 2 && hv == hsh(i - dif)) { var maxn = Math.min(n, rem) - 1; var maxd = Math.min(32767, i); var ml = Math.min(258, rem); while (dif <= maxd && --ch_1 && imod != pimod) { if (dat[i + l] == dat[i + l - dif]) { var nl = 0; for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl); if (nl > l) { l = nl, d = dif; if (nl > maxn) break; var mmd = Math.min(dif, nl - 2); var md = 0; for (var j = 0; j < mmd; ++j) { var ti = i - dif + j + 32768 & 32767; var cd = ti - prev[ti] + 32768 & 32767; if (cd > md) md = cd, pimod = ti; } } } imod = pimod, pimod = prev[imod]; dif += imod - pimod + 32768 & 32767; } } if (d) { syms[li++] = 268435456 | revfl[l] << 18 | revfd[d]; var lin = revfl[l] & 31, din = revfd[d] & 31; eb += fleb[lin] + fdeb[din]; ++lf[257 + lin]; ++df[din]; wi = i + l; ++lc_1; } else { syms[li++] = dat[i]; ++lf[dat[i]]; } } } pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); if (!lst && pos & 7) pos = wfblk(w, pos + 1, et); } return slc(o, 0, pre + shft(pos) + post); }; var crct = /*#__PURE__*/ (function() { var t = new Int32Array(256); for (var i = 0; i < 256; ++i) { var c = i, k = 9; while (--k) c = (c & 1 && -306674912) ^ c >>> 1; t[i] = c; } return t; })(); var crc = function() { var c = -1; return { p: function(d) { var cr = c; for (var i = 0; i < d.length; ++i) cr = crct[cr & 255 ^ d[i]] ^ cr >>> 8; c = cr; }, d: function() { return ~c; } }; }; 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(a, b) { var o = {}; for (var k in a) o[k] = a[k]; for (var k in b) o[k] = b[k]; return o; }; var b2 = function(d, b) { return d[b] | d[b + 1] << 8; }; var b4 = function(d, b) { return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0; }; var b8 = function(d, b) { return b4(d, b) + b4(d, b + 4) * 4294967296; }; var wbytes = function(d, b, v) { for (; v; ++b) d[b] = v, v >>>= 8; }; var gzs = function(d) { if (d[0] != 31 || d[1] != 139 || d[2] != 8) throw "invalid gzip data"; var flg = d[3]; var st = 10; if (flg & 4) st += d[10] | (d[11] << 8) + 2; for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]); return st + (flg & 2); }; var gzl = function(d) { var l = d.length; return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0; }; var zlv = function(d) { if ((d[0] & 15) != 8 || d[0] >>> 4 > 7 || (d[0] << 8 | d[1]) % 31) throw "invalid zlib data"; if (d[1] & 32) throw "invalid zlib data: preset dictionaries not supported"; }; /** * Compresses data with DEFLATE without any wrapper * @param data The data to compress * @param opts The compression options * @returns The deflated version of the data */ function deflateSync(data, opts) { return dopt(data, opts || {}, 0, 0); } /** * Expands DEFLATE data with no wrapper * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */ function inflateSync(data, out) { return inflt(data, out); } /** * Expands GZIP data * @param data The data to decompress * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory. * @returns The decompressed version of the data */ function gunzipSync(data, out) { return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data))); } /** * Expands Zlib data * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */ function unzlibSync(data, out) { return inflt((zlv(data), data.subarray(2, -4)), out); } var fltn = function(d, p, t, o) { for (var k in d) { var val = d[k], n = p + k; if (val instanceof u8) t[n] = [val, o]; else if (Array.isArray(val)) t[n] = [val[0], mrg(o, val[1])]; else fltn(val, n + "/", t, o); } }; var te = typeof TextEncoder != "undefined" && /*#__PURE__*/ new TextEncoder(); var td = typeof TextDecoder != "undefined" && /*#__PURE__*/ new TextDecoder(); try { td.decode(et, { stream: true }); } catch (e) {} var dutf8 = function(d) { for (var r = "", i = 0;;) { var c = d[i++]; var eb = (c > 127) + (c > 223) + (c > 239); if (i + eb > d.length) return [r, slc(d, i - 1)]; if (!eb) r += String.fromCharCode(c); else if (eb == 3) c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | d[i++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023); else if (eb & 1) r += String.fromCharCode((c & 31) << 6 | d[i++] & 63); else r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | d[i++] & 63); } }; /** * Converts a string into a Uint8Array for use with compression/decompression methods * @param str The string to encode * @param latin1 Whether or not to interpret the data as Latin-1. This should * not need to be true unless decoding a binary string. * @returns The string encoded in UTF-8/Latin-1 binary */ function strToU8(str, latin1) { if (latin1) { var ar_1 = new u8(str.length); for (var i = 0; i < str.length; ++i) ar_1[i] = str.charCodeAt(i); return ar_1; } if (te) return te.encode(str); var l = str.length; var ar = new u8(str.length + (str.length >> 1)); var ai = 0; var w = function(v) { ar[ai++] = v; }; for (var i = 0; i < l; ++i) { if (ai + 5 > ar.length) { var n = new u8(ai + 8 + (l - i << 1)); n.set(ar); ar = n; } var c = str.charCodeAt(i); if (c < 128 || latin1) w(c); else if (c < 2048) w(192 | c >> 6), w(128 | c & 63); else if (c > 55295 && c < 57344) c = 65536 + (c & 1047552) | str.charCodeAt(++i) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63); else w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63); } return slc(ar, 0, ai); } /** * Converts a Uint8Array to a string * @param dat The data to decode to string * @param latin1 Whether or not to interpret the data as Latin-1. This should * not need to be true unless encoding to binary string. * @returns The original UTF-8/Latin-1 string */ function strFromU8(dat, latin1) { if (latin1) { var r = ""; for (var i = 0; i < dat.length; i += 16384) r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); return r; } else if (td) return td.decode(dat); else { var _a = dutf8(dat), out = _a[0]; if (_a[1].length) throw "invalid utf-8 data"; return out; } } var slzh = function(d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); }; var zh = function(d, b, z) { var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20); var _a = z && bs == 4294967295 ? z64e(d, es) : [ bs, b4(d, b + 24), b4(d, b + 42) ], sc = _a[0], su = _a[1], off = _a[2]; return [ b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off ]; }; var z64e = function(d, b) { for (; b2(d, b) != 1; b += 4 + b2(d, b + 2)); return [ b8(d, b + 12), b8(d, b + 4), b8(d, b + 20) ]; }; var exfl = function(ex) { var le = 0; if (ex) for (var k in ex) { var l = ex[k].length; if (l > 65535) throw "extra field too long"; le += l + 4; } return le; }; var wzh = function(d, b, f, fn, u, c, ce, co) { var fl = fn.length, ex = f.extra, col = co && co.length; var exl = exfl(ex); wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4; if (ce != null) d[b++] = 20, d[b++] = f.os; d[b] = 20, b += 2; d[b++] = f.flag << 1 | (c == null && 8), d[b++] = u && 8; d[b++] = f.compression & 255, d[b++] = f.compression >> 8; var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; if (y < 0 || y > 119) throw "date not in range 1980-2099"; wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >>> 1), b += 4; if (c != null) { wbytes(d, b, f.crc); wbytes(d, b + 4, c); wbytes(d, b + 8, f.size); } wbytes(d, b + 12, fl); wbytes(d, b + 14, exl), b += 16; if (ce != null) { wbytes(d, b, col); wbytes(d, b + 6, f.attrs); wbytes(d, b + 10, ce), b += 14; } d.set(fn, b); b += fl; if (exl) for (var k in ex) { var exf = ex[k], l = exf.length; wbytes(d, b, +k); wbytes(d, b + 2, l); d.set(exf, b + 4), b += 4 + l; } if (col) d.set(co, b), b += col; return b; }; var wzf = function(o, b, c, d, e) { wbytes(o, b, 101010256); wbytes(o, b + 8, c); wbytes(o, b + 10, c); wbytes(o, b + 12, d); wbytes(o, b + 16, e); }; /** * Synchronously creates a ZIP file. Prefer using `zip` for better performance * with more than one file. * @param data The directory structure for the ZIP archive * @param opts The main options, merged with per-file options * @returns The generated ZIP archive */ function zipSync(data, opts) { if (!opts) opts = {}; var r = {}; var files = []; fltn(data, "", r, opts); var o = 0; var tot = 0; for (var fn in r) { var _a = r[fn], file = _a[0], p = _a[1]; var compression = p.level == 0 ? 0 : 8; var f = strToU8(fn), s = f.length; var com = p.comment, m = com && strToU8(com), ms = m && m.length; var exl = exfl(p.extra); if (s > 65535) throw "filename too long"; var d = compression ? deflateSync(file, p) : file, l = d.length; var c = crc(); c.p(file); files.push(mrg(p, { size: file.length, crc: c.d(), c: d, f, m, u: s != fn.length || m && com.length != ms, o, compression })); o += 30 + s + exl + l; tot += 76 + 2 * (s + exl) + (ms || 0) + l; } var out = new u8(tot + 22), oe = o, cdl = tot - o; for (var i = 0; i < files.length; ++i) { var f = files[i]; wzh(out, f.o, f, f.f, f.u, f.c.length); var badd = 30 + f.f.length + exfl(f.extra); out.set(f.c, f.o + badd); wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); } wzf(out, o, files.length, cdl, oe); return out; } /** * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better * performance with more than one file. * @param data The raw compressed ZIP file * @returns The decompressed files */ function unzipSync(data) { var files = {}; var e = data.length - 22; for (; b4(data, e) != 101010256; --e) if (!e || data.length - e > 65558) throw "invalid zip file"; var c = b2(data, e + 8); if (!c) return {}; var o = b4(data, e + 16); var z = o == 4294967295; if (z) { e = b4(data, e - 12); if (b4(data, e) != 101075792) throw "invalid zip file"; c = b4(data, e + 32); o = b4(data, e + 48); } for (var i = 0; i < c; ++i) { var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); o = no; if (!c_2) files[fn] = slc(data, b, b + sc); else if (c_2 == 8) files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su)); else throw "unknown compression type " + c_2; } return files; } //#endregion //#region node_modules/three-stdlib/exporters/USDZExporter.js var __defProp$53 = Object.defineProperty; var __defNormalProp$53 = (obj, key, value) => key in obj ? __defProp$53(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$53 = (obj, key, value) => { __defNormalProp$53(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var USDZExporter = class { constructor() { __publicField$53(this, "PRECISION", 7); __publicField$53(this, "materials"); __publicField$53(this, "textures"); __publicField$53(this, "files"); this.materials = {}; this.textures = {}; this.files = {}; } async parse(scene) { const modelFileName = "model.usda"; this.files[modelFileName] = null; let output = this.buildHeader(); scene.traverseVisible((object) => { if (object instanceof Mesh && object.isMesh && object.material.isMeshStandardMaterial) { const geometry = object.geometry; const material = object.material; const geometryFileName = "geometries/Geometry_" + geometry.id + ".usd"; if (!(geometryFileName in this.files)) { const meshObject = this.buildMeshObject(geometry); this.files[geometryFileName] = this.buildUSDFileAsString(meshObject); } if (!(material.uuid in this.materials)) this.materials[material.uuid] = material; output += this.buildXform(object, geometry, material); } }); output += this.buildMaterials(this.materials); this.files[modelFileName] = strToU8(output); output = null; for (const id in this.textures) { const texture = this.textures[id]; const color = id.split("_")[1]; const isRGBA = texture.format === 1023; const canvas = this.imageToCanvas(texture.image, color); const blob = await new Promise((resolve) => canvas == null ? void 0 : canvas.toBlob(resolve, isRGBA ? "image/png" : "image/jpeg", 1)); if (blob) this.files[`textures/Texture_${id}.${isRGBA ? "png" : "jpg"}`] = new Uint8Array(await blob.arrayBuffer()); } let offset = 0; for (const filename in this.files) { const file = this.files[filename]; const headerSize = 34 + filename.length; offset += headerSize; const offsetMod64 = offset & 63; if (offsetMod64 !== 4 && file !== null && file instanceof Uint8Array) { const padLength = 64 - offsetMod64; const padding = new Uint8Array(padLength); this.files[filename] = [file, { extra: { 12345: padding } }]; } if (file && typeof file.length === "number") offset = file.length; } return zipSync(this.files, { level: 0 }); } imageToCanvas(image, color) { if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof OffscreenCanvas !== "undefined" && image instanceof OffscreenCanvas || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { const scale = 1024 / Math.max(image.width, image.height); const canvas = document.createElement("canvas"); canvas.width = image.width * Math.min(1, scale); canvas.height = image.height * Math.min(1, scale); const context = canvas.getContext("2d"); context?.drawImage(image, 0, 0, canvas.width, canvas.height); if (color !== void 0) { const hex = parseInt(color, 16); const r = (hex >> 16 & 255) / 255; const g = (hex >> 8 & 255) / 255; const b = (hex & 255) / 255; const imagedata = context == null ? void 0 : context.getImageData(0, 0, canvas.width, canvas.height); if (imagedata) { const data = imagedata == null ? void 0 : imagedata.data; for (let i = 0; i < data.length; i += 4) { data[i + 0] = data[i + 0] * r; data[i + 1] = data[i + 1] * g; data[i + 2] = data[i + 2] * b; } context?.putImageData(imagedata, 0, 0); } } return canvas; } } buildHeader() { return `#usda 1.0 ( customLayerData = { string creator = "Three.js USDZExporter" } metersPerUnit = 1 upAxis = "Y" ) `; } buildUSDFileAsString(dataToInsert) { let output = this.buildHeader(); output += dataToInsert; return strToU8(output); } buildXform(object, geometry, material) { const name = "Object_" + object.id; const transform = this.buildMatrix(object.matrixWorld); if (object.matrixWorld.determinant() < 0) console.warn("THREE.USDZExporter: USDZ does not support negative scales", object); return `def Xform "${name}" ( prepend references = @./geometries/Geometry_${geometry.id}.usd@ ) { matrix4d xformOp:transform = ${transform} uniform token[] xformOpOrder = ["xformOp:transform"] rel material:binding = } `; } buildMatrix(matrix) { const array = matrix.elements; return `( ${this.buildMatrixRow(array, 0)}, ${this.buildMatrixRow(array, 4)}, ${this.buildMatrixRow(array, 8)}, ${this.buildMatrixRow(array, 12)} )`; } buildMatrixRow(array, offset) { return `(${array[offset + 0]}, ${array[offset + 1]}, ${array[offset + 2]}, ${array[offset + 3]})`; } buildMeshObject(geometry) { return ` def "Geometry" { ${this.buildMesh(geometry)} } `; } buildMesh(geometry) { const name = "Geometry"; const attributes = geometry.attributes; const count = attributes.position.count; return ` def Mesh "${name}" { int[] faceVertexCounts = [${this.buildMeshVertexCount(geometry)}] int[] faceVertexIndices = [${this.buildMeshVertexIndices(geometry)}] normal3f[] normals = [${this.buildVector3Array(attributes.normal, count)}] ( interpolation = "vertex" ) point3f[] points = [${this.buildVector3Array(attributes.position, count)}] float2[] primvars:st = [${this.buildVector2Array(attributes.uv, count)}] ( interpolation = "vertex" ) uniform token subdivisionScheme = "none" } `; } buildMeshVertexCount(geometry) { const count = geometry.index !== null ? geometry.index.array.length : geometry.attributes.position.count; return Array(count / 3).fill(3).join(", "); } buildMeshVertexIndices(geometry) { if (geometry.index !== null) return geometry.index.array.join(", "); const array = []; const length = geometry.attributes.position.count; for (let i = 0; i < length; i++) array.push(i); return array.join(", "); } buildVector3Array(attribute, count) { if (attribute === void 0) { console.warn("USDZExporter: Normals missing."); return Array(count).fill("(0, 0, 0)").join(", "); } const array = []; const data = attribute.array; for (let i = 0; i < data.length; i += 3) array.push(`(${data[i + 0].toPrecision(this.PRECISION)}, ${data[i + 1].toPrecision(this.PRECISION)}, ${data[i + 2].toPrecision(this.PRECISION)})`); return array.join(", "); } buildVector2Array(attribute, count) { if (attribute === void 0) { console.warn("USDZExporter: UVs missing."); return Array(count).fill("(0, 0)").join(", "); } const array = []; const data = attribute.array; for (let i = 0; i < data.length; i += 2) array.push(`(${data[i + 0].toPrecision(this.PRECISION)}, ${1 - data[i + 1].toPrecision(this.PRECISION)})`); return array.join(", "); } buildMaterials(materials) { const array = []; for (const uuid in materials) { const material = materials[uuid]; array.push(this.buildMaterial(material)); } return `def "Materials" { ${array.join("")} } `; } buildMaterial(material) { const pad = " "; const inputs = []; const samplers = []; if (material.map !== null) { inputs.push(`${pad}color3f inputs:diffuseColor.connect = `); if (material.transparent || material.alphaTest > 0) inputs.push(`${pad}float inputs:opacity.connect = `); if (material.alphaTest > .01) inputs.push(`${pad}float inputs:opacityThreshold = ${material.alphaTest}`); else if (material.transparent || material.alphaTest > 0) inputs.push(`${pad}float inputs:opacityThreshold = 0.01`); samplers.push(this.buildTexture(material, material.map, "diffuse", material.color)); } else inputs.push(`${pad}color3f inputs:diffuseColor = ${this.buildColor(material.color)}`); if (material.emissiveMap !== null) { inputs.push(`${pad}color3f inputs:emissiveColor.connect = `); samplers.push(this.buildTexture(material, material.emissiveMap, "emissive")); } else if (material.emissive.getHex() > 0) inputs.push(`${pad}color3f inputs:emissiveColor = ${this.buildColor(material.emissive)}`); if (material.normalMap !== null) { inputs.push(`${pad}normal3f inputs:normal.connect = `); samplers.push(this.buildTexture(material, material.normalMap, "normal")); } if (material.aoMap !== null) { inputs.push(`${pad}float inputs:occlusion.connect = `); samplers.push(this.buildTexture(material, material.aoMap, "occlusion")); } if (material.roughnessMap !== null && material.roughness === 1) { inputs.push(`${pad}float inputs:roughness.connect = `); samplers.push(this.buildTexture(material, material.roughnessMap, "roughness")); } else inputs.push(`${pad}float inputs:roughness = ${material.roughness}`); if (material.metalnessMap !== null && material.metalness === 1) { inputs.push(`${pad}float inputs:metallic.connect = `); samplers.push(this.buildTexture(material, material.metalnessMap, "metallic")); } else inputs.push(`${pad}float inputs:metallic = ${material.metalness}`); inputs.push(`${pad}float inputs:opacity = ${material.opacity}`); if (material instanceof MeshPhysicalMaterial) { inputs.push(`${pad}float inputs:clearcoat = ${material.clearcoat}`); inputs.push(`${pad}float inputs:clearcoatRoughness = ${material.clearcoatRoughness}`); inputs.push(`${pad}float inputs:ior = ${material.ior}`); } return ` def Material "Material_${material.id}" { def Shader "PreviewSurface" { uniform token info:id = "UsdPreviewSurface" ${inputs.join("\n")} int inputs:useSpecularWorkflow = 0 token outputs:surface } token outputs:surface.connect = token inputs:frame:stPrimvarName = "st" def Shader "uvReader_st" { uniform token info:id = "UsdPrimvarReader_float2" token inputs:varname.connect = float2 inputs:fallback = (0.0, 0.0) float2 outputs:result } ${samplers.join("\n")} } `; } buildTexture(material, texture, mapType, color) { const id = texture.id + (color ? "_" + color.getHexString() : ""); const isRGBA = texture.format === 1023; this.textures[id] = texture; return ` def Shader "Transform2d_${mapType}" ( sdrMetadata = { string role = "math" } ) { uniform token info:id = "UsdTransform2d" float2 inputs:in.connect = float2 inputs:scale = ${this.buildVector2(texture.repeat)} float2 inputs:translation = ${this.buildVector2(texture.offset)} float2 outputs:result } def Shader "Texture_${texture.id}_${mapType}" { uniform token info:id = "UsdUVTexture" asset inputs:file = @textures/Texture_${id}.${isRGBA ? "png" : "jpg"}@ float2 inputs:st.connect = token inputs:wrapS = "repeat" token inputs:wrapT = "repeat" float outputs:r float outputs:g float outputs:b float3 outputs:rgb ${material.transparent || material.alphaTest > 0 ? "float outputs:a" : ""} }`; } buildColor(color) { return `(${color.r}, ${color.g}, ${color.b})`; } buildVector2(vector) { return `(${vector.x}, ${vector.y})`; } }; //#endregion //#region node_modules/three-stdlib/exporters/PLYExporter.js var PLYExporter = class { parse(object, onDone, options) { if (onDone && typeof onDone === "object") { console.warn("THREE.PLYExporter: The options parameter is now the third argument to the \"parse\" function. See the documentation for the new API."); options = onDone; onDone = void 0; } options = Object.assign({ binary: false, excludeAttributes: [], littleEndian: false }, options); const excludeAttributes = options.excludeAttributes; let includeNormals = false; let includeColors = false; let includeUVs = false; let vertexCount = 0; let faceCount = 0; object.traverse(function(child) { if (child instanceof Mesh && child.isMesh) { const geometry = child.geometry; if (!geometry.isBufferGeometry) throw new Error("THREE.PLYExporter: Geometry is not of type THREE.BufferGeometry."); const vertices = geometry.getAttribute("position"); const normals = geometry.getAttribute("normal"); const uvs = geometry.getAttribute("uv"); const colors = geometry.getAttribute("color"); const indices = geometry.getIndex(); if (vertices === void 0) return; vertexCount += vertices.count; faceCount += indices ? indices.count / 3 : vertices.count / 3; if (normals !== void 0) includeNormals = true; if (uvs !== void 0) includeUVs = true; if (colors !== void 0) includeColors = true; } }); const includeIndices = (excludeAttributes == null ? void 0 : excludeAttributes.indexOf("index")) === -1; includeNormals = includeNormals && (excludeAttributes == null ? void 0 : excludeAttributes.indexOf("normal")) === -1; includeColors = includeColors && (excludeAttributes == null ? void 0 : excludeAttributes.indexOf("color")) === -1; includeUVs = includeUVs && (excludeAttributes == null ? void 0 : excludeAttributes.indexOf("uv")) === -1; if (includeIndices && faceCount !== Math.floor(faceCount)) { console.error("PLYExporter: Failed to generate a valid PLY file with triangle indices because the number of indices is not divisible by 3."); return null; } const indexByteCount = 4; let header = `ply format ${options.binary ? options.littleEndian ? "binary_little_endian" : "binary_big_endian" : "ascii"} 1.0 element vertex ${vertexCount} property float x property float y property float z `; if (includeNormals) header += "property float nx\nproperty float ny\nproperty float nz\n"; if (includeUVs) header += "property float s\nproperty float t\n"; if (includeColors) header += "property uchar red\nproperty uchar green\nproperty uchar blue\n"; if (includeIndices) header += `${`element face ${faceCount} `}property list uchar int vertex_index `; header += "end_header\n"; const vertex = new Vector3(); const normalMatrixWorld = new Matrix3(); let result = null; if (options.binary) { const headerBin = new TextEncoder().encode(header); const vertexListLength = vertexCount * (12 + (includeNormals ? 12 : 0) + (includeColors ? 3 : 0) + (includeUVs ? 8 : 0)); const faceListLength = includeIndices ? faceCount * 13 : 0; const output = new DataView(new ArrayBuffer(headerBin.length + vertexListLength + faceListLength)); new Uint8Array(output.buffer).set(headerBin, 0); let vOffset = headerBin.length; let fOffset = headerBin.length + vertexListLength; let writtenVertices = 0; this.traverseMeshes(object, function(mesh, geometry) { const vertices = geometry.getAttribute("position"); const normals = geometry.getAttribute("normal"); const uvs = geometry.getAttribute("uv"); const colors = geometry.getAttribute("color"); const indices = geometry.getIndex(); normalMatrixWorld.getNormalMatrix(mesh.matrixWorld); for (let i = 0, l = vertices.count; i < l; i++) { vertex.x = vertices.getX(i); vertex.y = vertices.getY(i); vertex.z = vertices.getZ(i); vertex.applyMatrix4(mesh.matrixWorld); output.setFloat32(vOffset, vertex.x, options.littleEndian); vOffset += 4; output.setFloat32(vOffset, vertex.y, options.littleEndian); vOffset += 4; output.setFloat32(vOffset, vertex.z, options.littleEndian); vOffset += 4; if (includeNormals) if (normals != null) { vertex.x = normals.getX(i); vertex.y = normals.getY(i); vertex.z = normals.getZ(i); vertex.applyMatrix3(normalMatrixWorld).normalize(); output.setFloat32(vOffset, vertex.x, options.littleEndian); vOffset += 4; output.setFloat32(vOffset, vertex.y, options.littleEndian); vOffset += 4; output.setFloat32(vOffset, vertex.z, options.littleEndian); vOffset += 4; } else { output.setFloat32(vOffset, 0, options.littleEndian); vOffset += 4; output.setFloat32(vOffset, 0, options.littleEndian); vOffset += 4; output.setFloat32(vOffset, 0, options.littleEndian); vOffset += 4; } if (includeUVs) { if (uvs != null) { output.setFloat32(vOffset, uvs.getX(i), options.littleEndian); vOffset += 4; output.setFloat32(vOffset, uvs.getY(i), options.littleEndian); vOffset += 4; } else if (!includeUVs) { output.setFloat32(vOffset, 0, options.littleEndian); vOffset += 4; output.setFloat32(vOffset, 0, options.littleEndian); vOffset += 4; } } if (includeColors) if (colors != null) { output.setUint8(vOffset, Math.floor(colors.getX(i) * 255)); vOffset += 1; output.setUint8(vOffset, Math.floor(colors.getY(i) * 255)); vOffset += 1; output.setUint8(vOffset, Math.floor(colors.getZ(i) * 255)); vOffset += 1; } else { output.setUint8(vOffset, 255); vOffset += 1; output.setUint8(vOffset, 255); vOffset += 1; output.setUint8(vOffset, 255); vOffset += 1; } } if (includeIndices) if (indices !== null) for (let i = 0, l = indices.count; i < l; i += 3) { output.setUint8(fOffset, 3); fOffset += 1; output.setUint32(fOffset, indices.getX(i + 0) + writtenVertices, options.littleEndian); fOffset += indexByteCount; output.setUint32(fOffset, indices.getX(i + 1) + writtenVertices, options.littleEndian); fOffset += indexByteCount; output.setUint32(fOffset, indices.getX(i + 2) + writtenVertices, options.littleEndian); fOffset += indexByteCount; } else for (let i = 0, l = vertices.count; i < l; i += 3) { output.setUint8(fOffset, 3); fOffset += 1; output.setUint32(fOffset, writtenVertices + i, options.littleEndian); fOffset += indexByteCount; output.setUint32(fOffset, writtenVertices + i + 1, options.littleEndian); fOffset += indexByteCount; output.setUint32(fOffset, writtenVertices + i + 2, options.littleEndian); fOffset += indexByteCount; } writtenVertices += vertices.count; }); result = output.buffer; } else { let writtenVertices = 0; let vertexList = ""; let faceList = ""; this.traverseMeshes(object, function(mesh, geometry) { const vertices = geometry.getAttribute("position"); const normals = geometry.getAttribute("normal"); const uvs = geometry.getAttribute("uv"); const colors = geometry.getAttribute("color"); const indices = geometry.getIndex(); normalMatrixWorld.getNormalMatrix(mesh.matrixWorld); for (let i = 0, l = vertices.count; i < l; i++) { vertex.x = vertices.getX(i); vertex.y = vertices.getY(i); vertex.z = vertices.getZ(i); vertex.applyMatrix4(mesh.matrixWorld); let line = vertex.x + " " + vertex.y + " " + vertex.z; if (includeNormals) if (normals != null) { vertex.x = normals.getX(i); vertex.y = normals.getY(i); vertex.z = normals.getZ(i); vertex.applyMatrix3(normalMatrixWorld).normalize(); line += " " + vertex.x + " " + vertex.y + " " + vertex.z; } else line += " 0 0 0"; if (includeUVs) { if (uvs != null) line += " " + uvs.getX(i) + " " + uvs.getY(i); else if (includeUVs) line += " 0 0"; } if (includeColors) if (colors != null) line += " " + Math.floor(colors.getX(i) * 255) + " " + Math.floor(colors.getY(i) * 255) + " " + Math.floor(colors.getZ(i) * 255); else line += " 255 255 255"; vertexList += line + "\n"; } if (includeIndices) { if (indices !== null) for (let i = 0, l = indices.count; i < l; i += 3) { faceList += `3 ${indices.getX(i + 0) + writtenVertices}`; faceList += ` ${indices.getX(i + 1) + writtenVertices}`; faceList += ` ${indices.getX(i + 2) + writtenVertices} `; } else for (let i = 0, l = vertices.count; i < l; i += 3) faceList += `3 ${writtenVertices + i} ${writtenVertices + i + 1} ${writtenVertices + i + 2} `; faceCount += indices ? indices.count / 3 : vertices.count / 3; } writtenVertices += vertices.count; }); result = `${header}${vertexList}${includeIndices ? `${faceList} ` : "\n"}`; } if (typeof onDone === "function") requestAnimationFrame(() => onDone && onDone(typeof result === "string" ? result : "")); return result; } traverseMeshes(object, cb) { object.traverse(function(child) { if (child instanceof Mesh && child.isMesh) { const mesh = child; const geometry = mesh.geometry; if (!geometry.isBufferGeometry) throw new Error("THREE.PLYExporter: Geometry is not of type THREE.BufferGeometry."); if (geometry.hasAttribute("position")) cb(mesh, geometry); } }); } }; //#endregion //#region node_modules/three-stdlib/exporters/DRACOExporter.js var __defProp$52 = Object.defineProperty; var __defNormalProp$52 = (obj, key, value) => key in obj ? __defProp$52(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$52 = (obj, key, value) => { __defNormalProp$52(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var DRACOExporter = /* @__PURE__ */ (() => { 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 geometry = object.geometry; const dracoEncoder = DracoEncoderModule(); const encoder = new dracoEncoder.Encoder(); let builder; let dracoObject; if (!geometry.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 = geometry.getAttribute("position"); builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); const faces = geometry.getIndex(); if (faces !== null) builder.AddFacesToMesh(dracoObject, faces.count / 3, faces.array); else { const faces2 = new (vertices.count > 65535 ? Uint32Array : Uint16Array)(vertices.count); for (let i = 0; i < faces2.length; i++) faces2[i] = i; builder.AddFacesToMesh(dracoObject, vertices.count, faces2); } if (options.exportNormals) { const normals = geometry.getAttribute("normal"); if (normals !== void 0) builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array); } if (options.exportUvs) { const uvs = geometry.getAttribute("uv"); if (uvs !== void 0) builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array); } if (options.exportColor) { const colors = geometry.getAttribute("color"); if (colors !== void 0) builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array); } } else if (object instanceof Points && object.isPoints) { builder = new dracoEncoder.PointCloudBuilder(); dracoObject = new dracoEncoder.PointCloud(); const vertices = geometry.getAttribute("position"); builder.AddFloatAttribute(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); if (options.exportColor) { const colors = geometry.getAttribute("color"); if (colors !== void 0) builder.AddFloatAttribute(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array); } } else throw new Error("DRACOExporter: Unsupported object type."); const encodedData = new dracoEncoder.DracoInt8Array(); const encodeSpeed = options.encodeSpeed !== void 0 ? options.encodeSpeed : 5; const decodeSpeed = options.decodeSpeed !== void 0 ? options.decodeSpeed : 5; encoder.SetSpeedOptions(encodeSpeed, decodeSpeed); if (options.encoderMethod !== void 0) encoder.SetEncodingMethod(options.encoderMethod); if (options.quantization !== void 0) { for (let i = 0; i < 5; i++) if (options.quantization[i] !== void 0) encoder.SetAttributeQuantization(i, options.quantization[i]); } let length; if (object instanceof Mesh && object.isMesh) length = encoder.EncodeMeshToDracoBuffer(dracoObject, encodedData); else length = encoder.EncodePointCloudToDracoBuffer(dracoObject, true, encodedData); dracoEncoder.destroy(dracoObject); if (length === 0) throw new Error("THREE.DRACOExporter: Draco encoding failed."); const outputData = new Int8Array(new ArrayBuffer(length)); for (let i = 0; i < length; i++) outputData[i] = encodedData.GetValue(i); dracoEncoder.destroy(encodedData); dracoEncoder.destroy(encoder); dracoEncoder.destroy(builder); return outputData; } }; let DRACOExporter2 = _DRACOExporter; __publicField$52(DRACOExporter2, "MESH_EDGEBREAKER_ENCODING", 1); __publicField$52(DRACOExporter2, "MESH_SEQUENTIAL_ENCODING", 0); __publicField$52(DRACOExporter2, "POINT_CLOUD", 0); __publicField$52(DRACOExporter2, "TRIANGULAR_MESH", 1); __publicField$52(DRACOExporter2, "INVALID", -1); __publicField$52(DRACOExporter2, "POSITION", 0); __publicField$52(DRACOExporter2, "NORMAL", 1); __publicField$52(DRACOExporter2, "COLOR", 2); __publicField$52(DRACOExporter2, "TEX_COORD", 3); __publicField$52(DRACOExporter2, "GENERIC", 4); return DRACOExporter2; })(); //#endregion //#region node_modules/three-stdlib/exporters/ColladaExporter.js var __defProp$51 = Object.defineProperty; var __defNormalProp$51 = (obj, key, value) => key in obj ? __defProp$51(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$51 = (obj, key, value) => { __defNormalProp$51(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var ColladaExporter = class { constructor() { __publicField$51(this, "options"); __publicField$51(this, "geometryInfo"); __publicField$51(this, "materialMap"); __publicField$51(this, "imageMap"); __publicField$51(this, "textures"); __publicField$51(this, "libraryImages"); __publicField$51(this, "libraryGeometries"); __publicField$51(this, "libraryEffects"); __publicField$51(this, "libraryMaterials"); __publicField$51(this, "canvas"); __publicField$51(this, "ctx"); __publicField$51(this, "transMat"); __publicField$51(this, "getFuncs", [ "getX", "getY", "getZ", "getW" ]); this.options = { version: "1.4.1", author: null, textureDirectory: "", upAxis: "Y_UP", unitName: null, unitMeter: null }; this.geometryInfo = /* @__PURE__ */ new WeakMap(); this.materialMap = /* @__PURE__ */ new WeakMap(); this.imageMap = /* @__PURE__ */ new WeakMap(); this.textures = []; this.libraryImages = []; this.libraryGeometries = []; this.libraryEffects = []; this.libraryMaterials = []; this.canvas = null; this.ctx = null; this.transMat = null; } parse(object, onDone, options = {}) { this.options = { ...this.options, ...options }; if (this.options.upAxis.match(/^[XYZ]_UP$/) === null) { console.error("ColladaExporter: Invalid upAxis: valid values are X_UP, Y_UP or Z_UP."); return null; } if (this.options.unitName !== null && this.options.unitMeter === null) { console.error("ColladaExporter: unitMeter needs to be specified if unitName is specified."); return null; } if (this.options.unitMeter !== null && this.options.unitName === null) { console.error("ColladaExporter: unitName needs to be specified if unitMeter is specified."); return null; } if (this.options.textureDirectory !== "") this.options.textureDirectory = `${this.options.textureDirectory}/`.replace(/\\/g, "/").replace(/\/+/g, "/"); if (this.options.version !== "1.4.1" && this.options.version !== "1.5.0") { console.warn(`ColladaExporter : Version ${this.options.version} not supported for export. Only 1.4.1 and 1.5.0.`); return null; } const libraryVisualScenes = this.processObject(object); let dae = `${``}three.js Collada Exporter${this.options.author !== null ? `${this.options.author}` : ""}${`${(/* @__PURE__ */ new Date()).toISOString()}`}${`${(/* @__PURE__ */ new Date()).toISOString()}`}Y_UP`; dae += `${this.libraryImages.join("")}`; dae += `${this.libraryEffects.join("")}`; dae += `${this.libraryMaterials.join("")}`; dae += `${this.libraryGeometries.join("")}`; dae += `${libraryVisualScenes}`; dae += ""; dae += ""; const res = { data: this.format(dae), textures: this.textures }; if (typeof onDone === "function") requestAnimationFrame(() => onDone(res)); return res; } format(urdf) { var _a, _b; const IS_END_TAG = /^<\//; const IS_SELF_CLOSING = /(\?>$)|(\/>$)/; const HAS_TEXT = /<[^>]+>[^<]*<\/[^<]+>/; const pad = (ch, num) => num > 0 ? ch + pad(ch, num - 1) : ""; let tagnum = 0; return (_b = (_a = urdf.match(/(<[^>]+>[^<]+<\/[^<]+>)|(<[^>]+>)/g)) == null ? void 0 : _a.map((tag) => { if (!HAS_TEXT.test(tag) && !IS_SELF_CLOSING.test(tag) && IS_END_TAG.test(tag)) tagnum--; const res = `${pad(" ", tagnum)}${tag}`; if (!HAS_TEXT.test(tag) && !IS_SELF_CLOSING.test(tag) && !IS_END_TAG.test(tag)) tagnum++; return res; }).join("\n")) != null ? _b : ""; } base64ToBuffer(str) { const b = atob(str); const buf = new Uint8Array(b.length); for (let i = 0, l = buf.length; i < l; i++) buf[i] = b.charCodeAt(i); return buf; } imageToData(image, ext) { var _a; this.canvas = this.canvas || document.createElement("canvas"); this.ctx = this.ctx || this.canvas.getContext("2d"); this.canvas.width = image.width instanceof SVGAnimatedLength ? 0 : image.width; this.canvas.height = image.height instanceof SVGAnimatedLength ? 0 : image.height; (_a = this.ctx) == null || _a.drawImage(image, 0, 0); const base64data = this.canvas.toDataURL(`image/${ext}`, 1).replace(/^data:image\/(png|jpg);base64,/, ""); return this.base64ToBuffer(base64data); } attrBufferToArray(attr) { if (attr instanceof InterleavedBufferAttribute && attr.isInterleavedBufferAttribute) { const TypedArrayConstructor = attr.array.constructor; const arr = new TypedArrayConstructor(attr.count * attr.itemSize); const size = attr.itemSize; for (let i = 0, l = attr.count; i < l; i++) for (let j = 0; j < size; j++) arr[i * size + j] = attr[this.getFuncs[j]](i); return arr; } else return attr.array; } subArray(arr, st, ct) { if (Array.isArray(arr)) return arr.slice(st, st + ct); else { const TypedArrayConstructor = arr.constructor; return new TypedArrayConstructor(arr.buffer, st * arr.BYTES_PER_ELEMENT, ct); } } getAttribute(attr, name, params, type) { const array = this.attrBufferToArray(attr); return Array.isArray(array) ? `${`` + array.join(" ")}${``}${params.map((n) => ``).join("")}` : ""; } getTransform(o) { o.updateMatrix(); this.transMat = this.transMat || new Matrix4(); this.transMat.copy(o.matrix); this.transMat.transpose(); return `${this.transMat.toArray().join(" ")}`; } processGeometry(g) { let info = this.geometryInfo.get(g); if (!info) { const bufferGeometry = g; if (!bufferGeometry.isBufferGeometry) throw new Error("THREE.ColladaExporter: Geometry is not of type THREE.BufferGeometry."); const meshid = `Mesh${this.libraryGeometries.length + 1}`; const indexCount = bufferGeometry.index ? bufferGeometry.index.count * bufferGeometry.index.itemSize : bufferGeometry.attributes.position.count; const groups = bufferGeometry.groups != null && bufferGeometry.groups.length !== 0 ? bufferGeometry.groups : [{ start: 0, count: indexCount, materialIndex: 0 }]; let gnode = ``; const posName = `${meshid}-position`; const vertName = `${meshid}-vertices`; gnode += this.getAttribute(bufferGeometry.attributes.position, posName, [ "X", "Y", "Z" ], "float"); gnode += ``; let triangleInputs = ``; if ("normal" in bufferGeometry.attributes) { const normName = `${meshid}-normal`; gnode += this.getAttribute(bufferGeometry.attributes.normal, normName, [ "X", "Y", "Z" ], "float"); triangleInputs += ``; } if ("uv" in bufferGeometry.attributes) { const uvName = `${meshid}-texcoord`; gnode += this.getAttribute(bufferGeometry.attributes.uv, uvName, ["S", "T"], "float"); triangleInputs += ``; } if (UV1 in bufferGeometry.attributes) { const uvName = `${meshid}-texcoord2`; gnode += this.getAttribute(bufferGeometry.attributes[UV1], uvName, ["S", "T"], "float"); triangleInputs += ``; } if ("color" in bufferGeometry.attributes) { const colName = `${meshid}-color`; gnode += this.getAttribute(bufferGeometry.attributes.color, colName, [ "X", "Y", "Z" ], "uint8"); triangleInputs += ``; } let indexArray = null; if (bufferGeometry.index) indexArray = this.attrBufferToArray(bufferGeometry.index); else { indexArray = new Array(indexCount); for (let i = 0, l = indexArray.length; i < l && Array.isArray(indexArray); i++) indexArray[i] = i; } for (let i = 0, l = groups.length; i < l; i++) { const group = groups[i]; const subarr = this.subArray(indexArray, group.start, group.count); const polycount = subarr.length / 3; gnode += ``; gnode += triangleInputs; gnode += `

${subarr.join(" ")}

`; gnode += "
"; } gnode += "
"; this.libraryGeometries.push(gnode); info = { meshid, bufferGeometry }; this.geometryInfo.set(g, info); } return info; } processTexture(tex) { let texid = this.imageMap.get(tex); if (texid == null) { texid = `image-${this.libraryImages.length + 1}`; const ext = "png"; const name = tex.name || texid; let imageNode = ``; if (this.options.version === "1.5.0") imageNode += `${this.options.textureDirectory}${name}.${ext}`; else imageNode += `${this.options.textureDirectory}${name}.${ext}`; imageNode += ""; this.libraryImages.push(imageNode); this.imageMap.set(tex, texid); this.textures.push({ directory: this.options.textureDirectory, name, ext, data: this.imageToData(tex.image, ext), original: tex }); } return texid; } processMaterial(m) { let matid = this.materialMap.get(m); if (matid == null) { matid = `Mat${this.libraryEffects.length + 1}`; let type = "phong"; if (m instanceof MeshLambertMaterial) type = "lambert"; else if (m instanceof MeshBasicMaterial) { type = "constant"; if (m.map !== null) console.warn("ColladaExporter: Texture maps not supported with MeshBasicMaterial."); } if (m instanceof MeshPhongMaterial) { const emissive = m.emissive ? m.emissive : new Color(0, 0, 0); const diffuse = m.color ? m.color : new Color(0, 0, 0); const specular = m.specular ? m.specular : new Color(1, 1, 1); const shininess = m.shininess || 0; const reflectivity = m.reflectivity || 0; let transparencyNode = ""; if (m.transparent) { transparencyNode += `${m.map ? "" : "1"}`; if (m.opacity < 1) transparencyNode += `${m.opacity}`; } const techniqueNode = `${`<${type}>`}${m.emissiveMap ? "" : `${emissive.r} ${emissive.g} ${emissive.b} 1`}${type !== "constant" ? `${m.map ? "" : `${diffuse.r} ${diffuse.g} ${diffuse.b} 1`}` : ""}${type !== "constant" ? `${m.normalMap ? "" : ""}` : ""}${type === "phong" ? `${`${specular.r} ${specular.g} ${specular.b} 1`}${m.specularMap ? "" : `${shininess}`}` : ""}${`${diffuse.r} ${diffuse.g} ${diffuse.b} 1`}${`${reflectivity}`}${transparencyNode}${``}`; const effectnode = `${``}${m.map ? `${`${this.processTexture(m.map)}`}diffuse-surface` : ""}${m.specularMap ? `${`${this.processTexture(m.specularMap)}`}specular-surface` : ""}${m.emissiveMap ? `${`${this.processTexture(m.emissiveMap)}`}emissive-surface` : ""}${m.normalMap ? `${`${this.processTexture(m.normalMap)}`}bump-surface` : ""}${techniqueNode}${m.side === 2 ? "1" : ""}`; const materialName = m.name ? ` name="${m.name}"` : ""; const materialNode = ``; this.libraryMaterials.push(materialNode); this.libraryEffects.push(effectnode); this.materialMap.set(m, matid); } } return matid; } processObject(o) { let node = ``; node += this.getTransform(o); new Mesh().geometry; if (o instanceof Mesh && o.isMesh && o.geometry !== null) { const geomInfo = this.processGeometry(o.geometry); const meshid = geomInfo.meshid; const geometry = geomInfo.bufferGeometry; let matids = null; let matidsArray; const mat = o.material || new MeshBasicMaterial(); const materials = Array.isArray(mat) ? mat : [mat]; if (geometry.groups.length > materials.length) matidsArray = new Array(geometry.groups.length); else matidsArray = new Array(materials.length); matids = matidsArray.fill(null).map((_, i) => this.processMaterial(materials[i % materials.length])); node += `${`` + (matids != null ? `${matids.map((id, i) => `${``}`).join("")}` : "")}`; } o.children.forEach((c) => node += this.processObject(c)); node += ""; return node; } }; //#endregion //#region node_modules/three-stdlib/libs/mmdparser.js var CharsetEncoder = class { constructor() { this.s2uTable = { 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, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20, 21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31, 32: 32, 33: 33, 34: 34, 35: 35, 36: 36, 37: 37, 38: 38, 39: 39, 40: 40, 41: 41, 42: 42, 43: 43, 44: 44, 45: 45, 46: 46, 47: 47, 48: 48, 49: 49, 50: 50, 51: 51, 52: 52, 53: 53, 54: 54, 55: 55, 56: 56, 57: 57, 58: 58, 59: 59, 60: 60, 61: 61, 62: 62, 63: 63, 64: 64, 65: 65, 66: 66, 67: 67, 68: 68, 69: 69, 70: 70, 71: 71, 72: 72, 73: 73, 74: 74, 75: 75, 76: 76, 77: 77, 78: 78, 79: 79, 80: 80, 81: 81, 82: 82, 83: 83, 84: 84, 85: 85, 86: 86, 87: 87, 88: 88, 89: 89, 90: 90, 91: 91, 92: 92, 93: 93, 94: 94, 95: 95, 96: 96, 97: 97, 98: 98, 99: 99, 100: 100, 101: 101, 102: 102, 103: 103, 104: 104, 105: 105, 106: 106, 107: 107, 108: 108, 109: 109, 110: 110, 111: 111, 112: 112, 113: 113, 114: 114, 115: 115, 116: 116, 117: 117, 118: 118, 119: 119, 120: 120, 121: 121, 122: 122, 123: 123, 124: 124, 125: 125, 126: 126, 161: 65377, 162: 65378, 163: 65379, 164: 65380, 165: 65381, 166: 65382, 167: 65383, 168: 65384, 169: 65385, 170: 65386, 171: 65387, 172: 65388, 173: 65389, 174: 65390, 175: 65391, 176: 65392, 177: 65393, 178: 65394, 179: 65395, 180: 65396, 181: 65397, 182: 65398, 183: 65399, 184: 65400, 185: 65401, 186: 65402, 187: 65403, 188: 65404, 189: 65405, 190: 65406, 191: 65407, 192: 65408, 193: 65409, 194: 65410, 195: 65411, 196: 65412, 197: 65413, 198: 65414, 199: 65415, 200: 65416, 201: 65417, 202: 65418, 203: 65419, 204: 65420, 205: 65421, 206: 65422, 207: 65423, 208: 65424, 209: 65425, 210: 65426, 211: 65427, 212: 65428, 213: 65429, 214: 65430, 215: 65431, 216: 65432, 217: 65433, 218: 65434, 219: 65435, 220: 65436, 221: 65437, 222: 65438, 223: 65439, 33088: 12288, 33089: 12289, 33090: 12290, 33091: 65292, 33092: 65294, 33093: 12539, 33094: 65306, 33095: 65307, 33096: 65311, 33097: 65281, 33098: 12443, 33099: 12444, 33100: 180, 33101: 65344, 33102: 168, 33103: 65342, 33104: 65507, 33105: 65343, 33106: 12541, 33107: 12542, 33108: 12445, 33109: 12446, 33110: 12291, 33111: 20189, 33112: 12293, 33113: 12294, 33114: 12295, 33115: 12540, 33116: 8213, 33117: 8208, 33118: 65295, 33119: 65340, 33120: 65374, 33121: 8741, 33122: 65372, 33123: 8230, 33124: 8229, 33125: 8216, 33126: 8217, 33127: 8220, 33128: 8221, 33129: 65288, 33130: 65289, 33131: 12308, 33132: 12309, 33133: 65339, 33134: 65341, 33135: 65371, 33136: 65373, 33137: 12296, 33138: 12297, 33139: 12298, 33140: 12299, 33141: 12300, 33142: 12301, 33143: 12302, 33144: 12303, 33145: 12304, 33146: 12305, 33147: 65291, 33148: 65293, 33149: 177, 33150: 215, 33152: 247, 33153: 65309, 33154: 8800, 33155: 65308, 33156: 65310, 33157: 8806, 33158: 8807, 33159: 8734, 33160: 8756, 33161: 9794, 33162: 9792, 33163: 176, 33164: 8242, 33165: 8243, 33166: 8451, 33167: 65509, 33168: 65284, 33169: 65504, 33170: 65505, 33171: 65285, 33172: 65283, 33173: 65286, 33174: 65290, 33175: 65312, 33176: 167, 33177: 9734, 33178: 9733, 33179: 9675, 33180: 9679, 33181: 9678, 33182: 9671, 33183: 9670, 33184: 9633, 33185: 9632, 33186: 9651, 33187: 9650, 33188: 9661, 33189: 9660, 33190: 8251, 33191: 12306, 33192: 8594, 33193: 8592, 33194: 8593, 33195: 8595, 33196: 12307, 33208: 8712, 33209: 8715, 33210: 8838, 33211: 8839, 33212: 8834, 33213: 8835, 33214: 8746, 33215: 8745, 33224: 8743, 33225: 8744, 33226: 65506, 33227: 8658, 33228: 8660, 33229: 8704, 33230: 8707, 33242: 8736, 33243: 8869, 33244: 8978, 33245: 8706, 33246: 8711, 33247: 8801, 33248: 8786, 33249: 8810, 33250: 8811, 33251: 8730, 33252: 8765, 33253: 8733, 33254: 8757, 33255: 8747, 33256: 8748, 33264: 8491, 33265: 8240, 33266: 9839, 33267: 9837, 33268: 9834, 33269: 8224, 33270: 8225, 33271: 182, 33276: 9711, 33359: 65296, 33360: 65297, 33361: 65298, 33362: 65299, 33363: 65300, 33364: 65301, 33365: 65302, 33366: 65303, 33367: 65304, 33368: 65305, 33376: 65313, 33377: 65314, 33378: 65315, 33379: 65316, 33380: 65317, 33381: 65318, 33382: 65319, 33383: 65320, 33384: 65321, 33385: 65322, 33386: 65323, 33387: 65324, 33388: 65325, 33389: 65326, 33390: 65327, 33391: 65328, 33392: 65329, 33393: 65330, 33394: 65331, 33395: 65332, 33396: 65333, 33397: 65334, 33398: 65335, 33399: 65336, 33400: 65337, 33401: 65338, 33409: 65345, 33410: 65346, 33411: 65347, 33412: 65348, 33413: 65349, 33414: 65350, 33415: 65351, 33416: 65352, 33417: 65353, 33418: 65354, 33419: 65355, 33420: 65356, 33421: 65357, 33422: 65358, 33423: 65359, 33424: 65360, 33425: 65361, 33426: 65362, 33427: 65363, 33428: 65364, 33429: 65365, 33430: 65366, 33431: 65367, 33432: 65368, 33433: 65369, 33434: 65370, 33439: 12353, 33440: 12354, 33441: 12355, 33442: 12356, 33443: 12357, 33444: 12358, 33445: 12359, 33446: 12360, 33447: 12361, 33448: 12362, 33449: 12363, 33450: 12364, 33451: 12365, 33452: 12366, 33453: 12367, 33454: 12368, 33455: 12369, 33456: 12370, 33457: 12371, 33458: 12372, 33459: 12373, 33460: 12374, 33461: 12375, 33462: 12376, 33463: 12377, 33464: 12378, 33465: 12379, 33466: 12380, 33467: 12381, 33468: 12382, 33469: 12383, 33470: 12384, 33471: 12385, 33472: 12386, 33473: 12387, 33474: 12388, 33475: 12389, 33476: 12390, 33477: 12391, 33478: 12392, 33479: 12393, 33480: 12394, 33481: 12395, 33482: 12396, 33483: 12397, 33484: 12398, 33485: 12399, 33486: 12400, 33487: 12401, 33488: 12402, 33489: 12403, 33490: 12404, 33491: 12405, 33492: 12406, 33493: 12407, 33494: 12408, 33495: 12409, 33496: 12410, 33497: 12411, 33498: 12412, 33499: 12413, 33500: 12414, 33501: 12415, 33502: 12416, 33503: 12417, 33504: 12418, 33505: 12419, 33506: 12420, 33507: 12421, 33508: 12422, 33509: 12423, 33510: 12424, 33511: 12425, 33512: 12426, 33513: 12427, 33514: 12428, 33515: 12429, 33516: 12430, 33517: 12431, 33518: 12432, 33519: 12433, 33520: 12434, 33521: 12435, 33600: 12449, 33601: 12450, 33602: 12451, 33603: 12452, 33604: 12453, 33605: 12454, 33606: 12455, 33607: 12456, 33608: 12457, 33609: 12458, 33610: 12459, 33611: 12460, 33612: 12461, 33613: 12462, 33614: 12463, 33615: 12464, 33616: 12465, 33617: 12466, 33618: 12467, 33619: 12468, 33620: 12469, 33621: 12470, 33622: 12471, 33623: 12472, 33624: 12473, 33625: 12474, 33626: 12475, 33627: 12476, 33628: 12477, 33629: 12478, 33630: 12479, 33631: 12480, 33632: 12481, 33633: 12482, 33634: 12483, 33635: 12484, 33636: 12485, 33637: 12486, 33638: 12487, 33639: 12488, 33640: 12489, 33641: 12490, 33642: 12491, 33643: 12492, 33644: 12493, 33645: 12494, 33646: 12495, 33647: 12496, 33648: 12497, 33649: 12498, 33650: 12499, 33651: 12500, 33652: 12501, 33653: 12502, 33654: 12503, 33655: 12504, 33656: 12505, 33657: 12506, 33658: 12507, 33659: 12508, 33660: 12509, 33661: 12510, 33662: 12511, 33664: 12512, 33665: 12513, 33666: 12514, 33667: 12515, 33668: 12516, 33669: 12517, 33670: 12518, 33671: 12519, 33672: 12520, 33673: 12521, 33674: 12522, 33675: 12523, 33676: 12524, 33677: 12525, 33678: 12526, 33679: 12527, 33680: 12528, 33681: 12529, 33682: 12530, 33683: 12531, 33684: 12532, 33685: 12533, 33686: 12534, 33695: 913, 33696: 914, 33697: 915, 33698: 916, 33699: 917, 33700: 918, 33701: 919, 33702: 920, 33703: 921, 33704: 922, 33705: 923, 33706: 924, 33707: 925, 33708: 926, 33709: 927, 33710: 928, 33711: 929, 33712: 931, 33713: 932, 33714: 933, 33715: 934, 33716: 935, 33717: 936, 33718: 937, 33727: 945, 33728: 946, 33729: 947, 33730: 948, 33731: 949, 33732: 950, 33733: 951, 33734: 952, 33735: 953, 33736: 954, 33737: 955, 33738: 956, 33739: 957, 33740: 958, 33741: 959, 33742: 960, 33743: 961, 33744: 963, 33745: 964, 33746: 965, 33747: 966, 33748: 967, 33749: 968, 33750: 969, 33856: 1040, 33857: 1041, 33858: 1042, 33859: 1043, 33860: 1044, 33861: 1045, 33862: 1025, 33863: 1046, 33864: 1047, 33865: 1048, 33866: 1049, 33867: 1050, 33868: 1051, 33869: 1052, 33870: 1053, 33871: 1054, 33872: 1055, 33873: 1056, 33874: 1057, 33875: 1058, 33876: 1059, 33877: 1060, 33878: 1061, 33879: 1062, 33880: 1063, 33881: 1064, 33882: 1065, 33883: 1066, 33884: 1067, 33885: 1068, 33886: 1069, 33887: 1070, 33888: 1071, 33904: 1072, 33905: 1073, 33906: 1074, 33907: 1075, 33908: 1076, 33909: 1077, 33910: 1105, 33911: 1078, 33912: 1079, 33913: 1080, 33914: 1081, 33915: 1082, 33916: 1083, 33917: 1084, 33918: 1085, 33920: 1086, 33921: 1087, 33922: 1088, 33923: 1089, 33924: 1090, 33925: 1091, 33926: 1092, 33927: 1093, 33928: 1094, 33929: 1095, 33930: 1096, 33931: 1097, 33932: 1098, 33933: 1099, 33934: 1100, 33935: 1101, 33936: 1102, 33937: 1103, 33951: 9472, 33952: 9474, 33953: 9484, 33954: 9488, 33955: 9496, 33956: 9492, 33957: 9500, 33958: 9516, 33959: 9508, 33960: 9524, 33961: 9532, 33962: 9473, 33963: 9475, 33964: 9487, 33965: 9491, 33966: 9499, 33967: 9495, 33968: 9507, 33969: 9523, 33970: 9515, 33971: 9531, 33972: 9547, 33973: 9504, 33974: 9519, 33975: 9512, 33976: 9527, 33977: 9535, 33978: 9501, 33979: 9520, 33980: 9509, 33981: 9528, 33982: 9538, 34624: 9312, 34625: 9313, 34626: 9314, 34627: 9315, 34628: 9316, 34629: 9317, 34630: 9318, 34631: 9319, 34632: 9320, 34633: 9321, 34634: 9322, 34635: 9323, 34636: 9324, 34637: 9325, 34638: 9326, 34639: 9327, 34640: 9328, 34641: 9329, 34642: 9330, 34643: 9331, 34644: 8544, 34645: 8545, 34646: 8546, 34647: 8547, 34648: 8548, 34649: 8549, 34650: 8550, 34651: 8551, 34652: 8552, 34653: 8553, 34655: 13129, 34656: 13076, 34657: 13090, 34658: 13133, 34659: 13080, 34660: 13095, 34661: 13059, 34662: 13110, 34663: 13137, 34664: 13143, 34665: 13069, 34666: 13094, 34667: 13091, 34668: 13099, 34669: 13130, 34670: 13115, 34671: 13212, 34672: 13213, 34673: 13214, 34674: 13198, 34675: 13199, 34676: 13252, 34677: 13217, 34686: 13179, 34688: 12317, 34689: 12319, 34690: 8470, 34691: 13261, 34692: 8481, 34693: 12964, 34694: 12965, 34695: 12966, 34696: 12967, 34697: 12968, 34698: 12849, 34699: 12850, 34700: 12857, 34701: 13182, 34702: 13181, 34703: 13180, 34704: 8786, 34705: 8801, 34706: 8747, 34707: 8750, 34708: 8721, 34709: 8730, 34710: 8869, 34711: 8736, 34712: 8735, 34713: 8895, 34714: 8757, 34715: 8745, 34716: 8746, 34975: 20124, 34976: 21782, 34977: 23043, 34978: 38463, 34979: 21696, 34980: 24859, 34981: 25384, 34982: 23030, 34983: 36898, 34984: 33909, 34985: 33564, 34986: 31312, 34987: 24746, 34988: 25569, 34989: 28197, 34990: 26093, 34991: 33894, 34992: 33446, 34993: 39925, 34994: 26771, 34995: 22311, 34996: 26017, 34997: 25201, 34998: 23451, 34999: 22992, 35e3: 34427, 35001: 39156, 35002: 32098, 35003: 32190, 35004: 39822, 35005: 25110, 35006: 31903, 35007: 34999, 35008: 23433, 35009: 24245, 35010: 25353, 35011: 26263, 35012: 26696, 35013: 38343, 35014: 38797, 35015: 26447, 35016: 20197, 35017: 20234, 35018: 20301, 35019: 20381, 35020: 20553, 35021: 22258, 35022: 22839, 35023: 22996, 35024: 23041, 35025: 23561, 35026: 24799, 35027: 24847, 35028: 24944, 35029: 26131, 35030: 26885, 35031: 28858, 35032: 30031, 35033: 30064, 35034: 31227, 35035: 32173, 35036: 32239, 35037: 32963, 35038: 33806, 35039: 34915, 35040: 35586, 35041: 36949, 35042: 36986, 35043: 21307, 35044: 20117, 35045: 20133, 35046: 22495, 35047: 32946, 35048: 37057, 35049: 30959, 35050: 19968, 35051: 22769, 35052: 28322, 35053: 36920, 35054: 31282, 35055: 33576, 35056: 33419, 35057: 39983, 35058: 20801, 35059: 21360, 35060: 21693, 35061: 21729, 35062: 22240, 35063: 23035, 35064: 24341, 35065: 39154, 35066: 28139, 35067: 32996, 35068: 34093, 35136: 38498, 35137: 38512, 35138: 38560, 35139: 38907, 35140: 21515, 35141: 21491, 35142: 23431, 35143: 28879, 35144: 32701, 35145: 36802, 35146: 38632, 35147: 21359, 35148: 40284, 35149: 31418, 35150: 19985, 35151: 30867, 35152: 33276, 35153: 28198, 35154: 22040, 35155: 21764, 35156: 27421, 35157: 34074, 35158: 39995, 35159: 23013, 35160: 21417, 35161: 28006, 35162: 29916, 35163: 38287, 35164: 22082, 35165: 20113, 35166: 36939, 35167: 38642, 35168: 33615, 35169: 39180, 35170: 21473, 35171: 21942, 35172: 23344, 35173: 24433, 35174: 26144, 35175: 26355, 35176: 26628, 35177: 27704, 35178: 27891, 35179: 27945, 35180: 29787, 35181: 30408, 35182: 31310, 35183: 38964, 35184: 33521, 35185: 34907, 35186: 35424, 35187: 37613, 35188: 28082, 35189: 30123, 35190: 30410, 35191: 39365, 35192: 24742, 35193: 35585, 35194: 36234, 35195: 38322, 35196: 27022, 35197: 21421, 35198: 20870, 35200: 22290, 35201: 22576, 35202: 22852, 35203: 23476, 35204: 24310, 35205: 24616, 35206: 25513, 35207: 25588, 35208: 27839, 35209: 28436, 35210: 28814, 35211: 28948, 35212: 29017, 35213: 29141, 35214: 29503, 35215: 32257, 35216: 33398, 35217: 33489, 35218: 34199, 35219: 36960, 35220: 37467, 35221: 40219, 35222: 22633, 35223: 26044, 35224: 27738, 35225: 29989, 35226: 20985, 35227: 22830, 35228: 22885, 35229: 24448, 35230: 24540, 35231: 25276, 35232: 26106, 35233: 27178, 35234: 27431, 35235: 27572, 35236: 29579, 35237: 32705, 35238: 35158, 35239: 40236, 35240: 40206, 35241: 40644, 35242: 23713, 35243: 27798, 35244: 33659, 35245: 20740, 35246: 23627, 35247: 25014, 35248: 33222, 35249: 26742, 35250: 29281, 35251: 20057, 35252: 20474, 35253: 21368, 35254: 24681, 35255: 28201, 35256: 31311, 35257: 38899, 35258: 19979, 35259: 21270, 35260: 20206, 35261: 20309, 35262: 20285, 35263: 20385, 35264: 20339, 35265: 21152, 35266: 21487, 35267: 22025, 35268: 22799, 35269: 23233, 35270: 23478, 35271: 23521, 35272: 31185, 35273: 26247, 35274: 26524, 35275: 26550, 35276: 27468, 35277: 27827, 35278: 28779, 35279: 29634, 35280: 31117, 35281: 31166, 35282: 31292, 35283: 31623, 35284: 33457, 35285: 33499, 35286: 33540, 35287: 33655, 35288: 33775, 35289: 33747, 35290: 34662, 35291: 35506, 35292: 22057, 35293: 36008, 35294: 36838, 35295: 36942, 35296: 38686, 35297: 34442, 35298: 20420, 35299: 23784, 35300: 25105, 35301: 29273, 35302: 30011, 35303: 33253, 35304: 33469, 35305: 34558, 35306: 36032, 35307: 38597, 35308: 39187, 35309: 39381, 35310: 20171, 35311: 20250, 35312: 35299, 35313: 22238, 35314: 22602, 35315: 22730, 35316: 24315, 35317: 24555, 35318: 24618, 35319: 24724, 35320: 24674, 35321: 25040, 35322: 25106, 35323: 25296, 35324: 25913, 35392: 39745, 35393: 26214, 35394: 26800, 35395: 28023, 35396: 28784, 35397: 30028, 35398: 30342, 35399: 32117, 35400: 33445, 35401: 34809, 35402: 38283, 35403: 38542, 35404: 35997, 35405: 20977, 35406: 21182, 35407: 22806, 35408: 21683, 35409: 23475, 35410: 23830, 35411: 24936, 35412: 27010, 35413: 28079, 35414: 30861, 35415: 33995, 35416: 34903, 35417: 35442, 35418: 37799, 35419: 39608, 35420: 28012, 35421: 39336, 35422: 34521, 35423: 22435, 35424: 26623, 35425: 34510, 35426: 37390, 35427: 21123, 35428: 22151, 35429: 21508, 35430: 24275, 35431: 25313, 35432: 25785, 35433: 26684, 35434: 26680, 35435: 27579, 35436: 29554, 35437: 30906, 35438: 31339, 35439: 35226, 35440: 35282, 35441: 36203, 35442: 36611, 35443: 37101, 35444: 38307, 35445: 38548, 35446: 38761, 35447: 23398, 35448: 23731, 35449: 27005, 35450: 38989, 35451: 38990, 35452: 25499, 35453: 31520, 35454: 27179, 35456: 27263, 35457: 26806, 35458: 39949, 35459: 28511, 35460: 21106, 35461: 21917, 35462: 24688, 35463: 25324, 35464: 27963, 35465: 28167, 35466: 28369, 35467: 33883, 35468: 35088, 35469: 36676, 35470: 19988, 35471: 39993, 35472: 21494, 35473: 26907, 35474: 27194, 35475: 38788, 35476: 26666, 35477: 20828, 35478: 31427, 35479: 33970, 35480: 37340, 35481: 37772, 35482: 22107, 35483: 40232, 35484: 26658, 35485: 33541, 35486: 33841, 35487: 31909, 35488: 21e3, 35489: 33477, 35490: 29926, 35491: 20094, 35492: 20355, 35493: 20896, 35494: 23506, 35495: 21002, 35496: 21208, 35497: 21223, 35498: 24059, 35499: 21914, 35500: 22570, 35501: 23014, 35502: 23436, 35503: 23448, 35504: 23515, 35505: 24178, 35506: 24185, 35507: 24739, 35508: 24863, 35509: 24931, 35510: 25022, 35511: 25563, 35512: 25954, 35513: 26577, 35514: 26707, 35515: 26874, 35516: 27454, 35517: 27475, 35518: 27735, 35519: 28450, 35520: 28567, 35521: 28485, 35522: 29872, 35523: 29976, 35524: 30435, 35525: 30475, 35526: 31487, 35527: 31649, 35528: 31777, 35529: 32233, 35530: 32566, 35531: 32752, 35532: 32925, 35533: 33382, 35534: 33694, 35535: 35251, 35536: 35532, 35537: 36011, 35538: 36996, 35539: 37969, 35540: 38291, 35541: 38289, 35542: 38306, 35543: 38501, 35544: 38867, 35545: 39208, 35546: 33304, 35547: 20024, 35548: 21547, 35549: 23736, 35550: 24012, 35551: 29609, 35552: 30284, 35553: 30524, 35554: 23721, 35555: 32747, 35556: 36107, 35557: 38593, 35558: 38929, 35559: 38996, 35560: 39e3, 35561: 20225, 35562: 20238, 35563: 21361, 35564: 21916, 35565: 22120, 35566: 22522, 35567: 22855, 35568: 23305, 35569: 23492, 35570: 23696, 35571: 24076, 35572: 24190, 35573: 24524, 35574: 25582, 35575: 26426, 35576: 26071, 35577: 26082, 35578: 26399, 35579: 26827, 35580: 26820, 35648: 27231, 35649: 24112, 35650: 27589, 35651: 27671, 35652: 27773, 35653: 30079, 35654: 31048, 35655: 23395, 35656: 31232, 35657: 32e3, 35658: 24509, 35659: 35215, 35660: 35352, 35661: 36020, 35662: 36215, 35663: 36556, 35664: 36637, 35665: 39138, 35666: 39438, 35667: 39740, 35668: 20096, 35669: 20605, 35670: 20736, 35671: 22931, 35672: 23452, 35673: 25135, 35674: 25216, 35675: 25836, 35676: 27450, 35677: 29344, 35678: 30097, 35679: 31047, 35680: 32681, 35681: 34811, 35682: 35516, 35683: 35696, 35684: 25516, 35685: 33738, 35686: 38816, 35687: 21513, 35688: 21507, 35689: 21931, 35690: 26708, 35691: 27224, 35692: 35440, 35693: 30759, 35694: 26485, 35695: 40653, 35696: 21364, 35697: 23458, 35698: 33050, 35699: 34384, 35700: 36870, 35701: 19992, 35702: 20037, 35703: 20167, 35704: 20241, 35705: 21450, 35706: 21560, 35707: 23470, 35708: 24339, 35709: 24613, 35710: 25937, 35712: 26429, 35713: 27714, 35714: 27762, 35715: 27875, 35716: 28792, 35717: 29699, 35718: 31350, 35719: 31406, 35720: 31496, 35721: 32026, 35722: 31998, 35723: 32102, 35724: 26087, 35725: 29275, 35726: 21435, 35727: 23621, 35728: 24040, 35729: 25298, 35730: 25312, 35731: 25369, 35732: 28192, 35733: 34394, 35734: 35377, 35735: 36317, 35736: 37624, 35737: 28417, 35738: 31142, 35739: 39770, 35740: 20136, 35741: 20139, 35742: 20140, 35743: 20379, 35744: 20384, 35745: 20689, 35746: 20807, 35747: 31478, 35748: 20849, 35749: 20982, 35750: 21332, 35751: 21281, 35752: 21375, 35753: 21483, 35754: 21932, 35755: 22659, 35756: 23777, 35757: 24375, 35758: 24394, 35759: 24623, 35760: 24656, 35761: 24685, 35762: 25375, 35763: 25945, 35764: 27211, 35765: 27841, 35766: 29378, 35767: 29421, 35768: 30703, 35769: 33016, 35770: 33029, 35771: 33288, 35772: 34126, 35773: 37111, 35774: 37857, 35775: 38911, 35776: 39255, 35777: 39514, 35778: 20208, 35779: 20957, 35780: 23597, 35781: 26241, 35782: 26989, 35783: 23616, 35784: 26354, 35785: 26997, 35786: 29577, 35787: 26704, 35788: 31873, 35789: 20677, 35790: 21220, 35791: 22343, 35792: 24062, 35793: 37670, 35794: 26020, 35795: 27427, 35796: 27453, 35797: 29748, 35798: 31105, 35799: 31165, 35800: 31563, 35801: 32202, 35802: 33465, 35803: 33740, 35804: 34943, 35805: 35167, 35806: 35641, 35807: 36817, 35808: 37329, 35809: 21535, 35810: 37504, 35811: 20061, 35812: 20534, 35813: 21477, 35814: 21306, 35815: 29399, 35816: 29590, 35817: 30697, 35818: 33510, 35819: 36527, 35820: 39366, 35821: 39368, 35822: 39378, 35823: 20855, 35824: 24858, 35825: 34398, 35826: 21936, 35827: 31354, 35828: 20598, 35829: 23507, 35830: 36935, 35831: 38533, 35832: 20018, 35833: 27355, 35834: 37351, 35835: 23633, 35836: 23624, 35904: 25496, 35905: 31391, 35906: 27795, 35907: 38772, 35908: 36705, 35909: 31402, 35910: 29066, 35911: 38536, 35912: 31874, 35913: 26647, 35914: 32368, 35915: 26705, 35916: 37740, 35917: 21234, 35918: 21531, 35919: 34219, 35920: 35347, 35921: 32676, 35922: 36557, 35923: 37089, 35924: 21350, 35925: 34952, 35926: 31041, 35927: 20418, 35928: 20670, 35929: 21009, 35930: 20804, 35931: 21843, 35932: 22317, 35933: 29674, 35934: 22411, 35935: 22865, 35936: 24418, 35937: 24452, 35938: 24693, 35939: 24950, 35940: 24935, 35941: 25001, 35942: 25522, 35943: 25658, 35944: 25964, 35945: 26223, 35946: 26690, 35947: 28179, 35948: 30054, 35949: 31293, 35950: 31995, 35951: 32076, 35952: 32153, 35953: 32331, 35954: 32619, 35955: 33550, 35956: 33610, 35957: 34509, 35958: 35336, 35959: 35427, 35960: 35686, 35961: 36605, 35962: 38938, 35963: 40335, 35964: 33464, 35965: 36814, 35966: 39912, 35968: 21127, 35969: 25119, 35970: 25731, 35971: 28608, 35972: 38553, 35973: 26689, 35974: 20625, 35975: 27424, 35976: 27770, 35977: 28500, 35978: 31348, 35979: 32080, 35980: 34880, 35981: 35363, 35982: 26376, 35983: 20214, 35984: 20537, 35985: 20518, 35986: 20581, 35987: 20860, 35988: 21048, 35989: 21091, 35990: 21927, 35991: 22287, 35992: 22533, 35993: 23244, 35994: 24314, 35995: 25010, 35996: 25080, 35997: 25331, 35998: 25458, 35999: 26908, 36e3: 27177, 36001: 29309, 36002: 29356, 36003: 29486, 36004: 30740, 36005: 30831, 36006: 32121, 36007: 30476, 36008: 32937, 36009: 35211, 36010: 35609, 36011: 36066, 36012: 36562, 36013: 36963, 36014: 37749, 36015: 38522, 36016: 38997, 36017: 39443, 36018: 40568, 36019: 20803, 36020: 21407, 36021: 21427, 36022: 24187, 36023: 24358, 36024: 28187, 36025: 28304, 36026: 29572, 36027: 29694, 36028: 32067, 36029: 33335, 36030: 35328, 36031: 35578, 36032: 38480, 36033: 20046, 36034: 20491, 36035: 21476, 36036: 21628, 36037: 22266, 36038: 22993, 36039: 23396, 36040: 24049, 36041: 24235, 36042: 24359, 36043: 25144, 36044: 25925, 36045: 26543, 36046: 28246, 36047: 29392, 36048: 31946, 36049: 34996, 36050: 32929, 36051: 32993, 36052: 33776, 36053: 34382, 36054: 35463, 36055: 36328, 36056: 37431, 36057: 38599, 36058: 39015, 36059: 40723, 36060: 20116, 36061: 20114, 36062: 20237, 36063: 21320, 36064: 21577, 36065: 21566, 36066: 23087, 36067: 24460, 36068: 24481, 36069: 24735, 36070: 26791, 36071: 27278, 36072: 29786, 36073: 30849, 36074: 35486, 36075: 35492, 36076: 35703, 36077: 37264, 36078: 20062, 36079: 39881, 36080: 20132, 36081: 20348, 36082: 20399, 36083: 20505, 36084: 20502, 36085: 20809, 36086: 20844, 36087: 21151, 36088: 21177, 36089: 21246, 36090: 21402, 36091: 21475, 36092: 21521, 36160: 21518, 36161: 21897, 36162: 22353, 36163: 22434, 36164: 22909, 36165: 23380, 36166: 23389, 36167: 23439, 36168: 24037, 36169: 24039, 36170: 24055, 36171: 24184, 36172: 24195, 36173: 24218, 36174: 24247, 36175: 24344, 36176: 24658, 36177: 24908, 36178: 25239, 36179: 25304, 36180: 25511, 36181: 25915, 36182: 26114, 36183: 26179, 36184: 26356, 36185: 26477, 36186: 26657, 36187: 26775, 36188: 27083, 36189: 27743, 36190: 27946, 36191: 28009, 36192: 28207, 36193: 28317, 36194: 30002, 36195: 30343, 36196: 30828, 36197: 31295, 36198: 31968, 36199: 32005, 36200: 32024, 36201: 32094, 36202: 32177, 36203: 32789, 36204: 32771, 36205: 32943, 36206: 32945, 36207: 33108, 36208: 33167, 36209: 33322, 36210: 33618, 36211: 34892, 36212: 34913, 36213: 35611, 36214: 36002, 36215: 36092, 36216: 37066, 36217: 37237, 36218: 37489, 36219: 30783, 36220: 37628, 36221: 38308, 36222: 38477, 36224: 38917, 36225: 39321, 36226: 39640, 36227: 40251, 36228: 21083, 36229: 21163, 36230: 21495, 36231: 21512, 36232: 22741, 36233: 25335, 36234: 28640, 36235: 35946, 36236: 36703, 36237: 40633, 36238: 20811, 36239: 21051, 36240: 21578, 36241: 22269, 36242: 31296, 36243: 37239, 36244: 40288, 36245: 40658, 36246: 29508, 36247: 28425, 36248: 33136, 36249: 29969, 36250: 24573, 36251: 24794, 36252: 39592, 36253: 29403, 36254: 36796, 36255: 27492, 36256: 38915, 36257: 20170, 36258: 22256, 36259: 22372, 36260: 22718, 36261: 23130, 36262: 24680, 36263: 25031, 36264: 26127, 36265: 26118, 36266: 26681, 36267: 26801, 36268: 28151, 36269: 30165, 36270: 32058, 36271: 33390, 36272: 39746, 36273: 20123, 36274: 20304, 36275: 21449, 36276: 21766, 36277: 23919, 36278: 24038, 36279: 24046, 36280: 26619, 36281: 27801, 36282: 29811, 36283: 30722, 36284: 35408, 36285: 37782, 36286: 35039, 36287: 22352, 36288: 24231, 36289: 25387, 36290: 20661, 36291: 20652, 36292: 20877, 36293: 26368, 36294: 21705, 36295: 22622, 36296: 22971, 36297: 23472, 36298: 24425, 36299: 25165, 36300: 25505, 36301: 26685, 36302: 27507, 36303: 28168, 36304: 28797, 36305: 37319, 36306: 29312, 36307: 30741, 36308: 30758, 36309: 31085, 36310: 25998, 36311: 32048, 36312: 33756, 36313: 35009, 36314: 36617, 36315: 38555, 36316: 21092, 36317: 22312, 36318: 26448, 36319: 32618, 36320: 36001, 36321: 20916, 36322: 22338, 36323: 38442, 36324: 22586, 36325: 27018, 36326: 32948, 36327: 21682, 36328: 23822, 36329: 22524, 36330: 30869, 36331: 40442, 36332: 20316, 36333: 21066, 36334: 21643, 36335: 25662, 36336: 26152, 36337: 26388, 36338: 26613, 36339: 31364, 36340: 31574, 36341: 32034, 36342: 37679, 36343: 26716, 36344: 39853, 36345: 31545, 36346: 21273, 36347: 20874, 36348: 21047, 36416: 23519, 36417: 25334, 36418: 25774, 36419: 25830, 36420: 26413, 36421: 27578, 36422: 34217, 36423: 38609, 36424: 30352, 36425: 39894, 36426: 25420, 36427: 37638, 36428: 39851, 36429: 30399, 36430: 26194, 36431: 19977, 36432: 20632, 36433: 21442, 36434: 23665, 36435: 24808, 36436: 25746, 36437: 25955, 36438: 26719, 36439: 29158, 36440: 29642, 36441: 29987, 36442: 31639, 36443: 32386, 36444: 34453, 36445: 35715, 36446: 36059, 36447: 37240, 36448: 39184, 36449: 26028, 36450: 26283, 36451: 27531, 36452: 20181, 36453: 20180, 36454: 20282, 36455: 20351, 36456: 21050, 36457: 21496, 36458: 21490, 36459: 21987, 36460: 22235, 36461: 22763, 36462: 22987, 36463: 22985, 36464: 23039, 36465: 23376, 36466: 23629, 36467: 24066, 36468: 24107, 36469: 24535, 36470: 24605, 36471: 25351, 36472: 25903, 36473: 23388, 36474: 26031, 36475: 26045, 36476: 26088, 36477: 26525, 36478: 27490, 36480: 27515, 36481: 27663, 36482: 29509, 36483: 31049, 36484: 31169, 36485: 31992, 36486: 32025, 36487: 32043, 36488: 32930, 36489: 33026, 36490: 33267, 36491: 35222, 36492: 35422, 36493: 35433, 36494: 35430, 36495: 35468, 36496: 35566, 36497: 36039, 36498: 36060, 36499: 38604, 36500: 39164, 36501: 27503, 36502: 20107, 36503: 20284, 36504: 20365, 36505: 20816, 36506: 23383, 36507: 23546, 36508: 24904, 36509: 25345, 36510: 26178, 36511: 27425, 36512: 28363, 36513: 27835, 36514: 29246, 36515: 29885, 36516: 30164, 36517: 30913, 36518: 31034, 36519: 32780, 36520: 32819, 36521: 33258, 36522: 33940, 36523: 36766, 36524: 27728, 36525: 40575, 36526: 24335, 36527: 35672, 36528: 40235, 36529: 31482, 36530: 36600, 36531: 23437, 36532: 38635, 36533: 19971, 36534: 21489, 36535: 22519, 36536: 22833, 36537: 23241, 36538: 23460, 36539: 24713, 36540: 28287, 36541: 28422, 36542: 30142, 36543: 36074, 36544: 23455, 36545: 34048, 36546: 31712, 36547: 20594, 36548: 26612, 36549: 33437, 36550: 23649, 36551: 34122, 36552: 32286, 36553: 33294, 36554: 20889, 36555: 23556, 36556: 25448, 36557: 36198, 36558: 26012, 36559: 29038, 36560: 31038, 36561: 32023, 36562: 32773, 36563: 35613, 36564: 36554, 36565: 36974, 36566: 34503, 36567: 37034, 36568: 20511, 36569: 21242, 36570: 23610, 36571: 26451, 36572: 28796, 36573: 29237, 36574: 37196, 36575: 37320, 36576: 37675, 36577: 33509, 36578: 23490, 36579: 24369, 36580: 24825, 36581: 20027, 36582: 21462, 36583: 23432, 36584: 25163, 36585: 26417, 36586: 27530, 36587: 29417, 36588: 29664, 36589: 31278, 36590: 33131, 36591: 36259, 36592: 37202, 36593: 39318, 36594: 20754, 36595: 21463, 36596: 21610, 36597: 23551, 36598: 25480, 36599: 27193, 36600: 32172, 36601: 38656, 36602: 22234, 36603: 21454, 36604: 21608, 36672: 23447, 36673: 23601, 36674: 24030, 36675: 20462, 36676: 24833, 36677: 25342, 36678: 27954, 36679: 31168, 36680: 31179, 36681: 32066, 36682: 32333, 36683: 32722, 36684: 33261, 36685: 33311, 36686: 33936, 36687: 34886, 36688: 35186, 36689: 35728, 36690: 36468, 36691: 36655, 36692: 36913, 36693: 37195, 36694: 37228, 36695: 38598, 36696: 37276, 36697: 20160, 36698: 20303, 36699: 20805, 36700: 21313, 36701: 24467, 36702: 25102, 36703: 26580, 36704: 27713, 36705: 28171, 36706: 29539, 36707: 32294, 36708: 37325, 36709: 37507, 36710: 21460, 36711: 22809, 36712: 23487, 36713: 28113, 36714: 31069, 36715: 32302, 36716: 31899, 36717: 22654, 36718: 29087, 36719: 20986, 36720: 34899, 36721: 36848, 36722: 20426, 36723: 23803, 36724: 26149, 36725: 30636, 36726: 31459, 36727: 33308, 36728: 39423, 36729: 20934, 36730: 24490, 36731: 26092, 36732: 26991, 36733: 27529, 36734: 28147, 36736: 28310, 36737: 28516, 36738: 30462, 36739: 32020, 36740: 24033, 36741: 36981, 36742: 37255, 36743: 38918, 36744: 20966, 36745: 21021, 36746: 25152, 36747: 26257, 36748: 26329, 36749: 28186, 36750: 24246, 36751: 32210, 36752: 32626, 36753: 26360, 36754: 34223, 36755: 34295, 36756: 35576, 36757: 21161, 36758: 21465, 36759: 22899, 36760: 24207, 36761: 24464, 36762: 24661, 36763: 37604, 36764: 38500, 36765: 20663, 36766: 20767, 36767: 21213, 36768: 21280, 36769: 21319, 36770: 21484, 36771: 21736, 36772: 21830, 36773: 21809, 36774: 22039, 36775: 22888, 36776: 22974, 36777: 23100, 36778: 23477, 36779: 23558, 36780: 23567, 36781: 23569, 36782: 23578, 36783: 24196, 36784: 24202, 36785: 24288, 36786: 24432, 36787: 25215, 36788: 25220, 36789: 25307, 36790: 25484, 36791: 25463, 36792: 26119, 36793: 26124, 36794: 26157, 36795: 26230, 36796: 26494, 36797: 26786, 36798: 27167, 36799: 27189, 36800: 27836, 36801: 28040, 36802: 28169, 36803: 28248, 36804: 28988, 36805: 28966, 36806: 29031, 36807: 30151, 36808: 30465, 36809: 30813, 36810: 30977, 36811: 31077, 36812: 31216, 36813: 31456, 36814: 31505, 36815: 31911, 36816: 32057, 36817: 32918, 36818: 33750, 36819: 33931, 36820: 34121, 36821: 34909, 36822: 35059, 36823: 35359, 36824: 35388, 36825: 35412, 36826: 35443, 36827: 35937, 36828: 36062, 36829: 37284, 36830: 37478, 36831: 37758, 36832: 37912, 36833: 38556, 36834: 38808, 36835: 19978, 36836: 19976, 36837: 19998, 36838: 20055, 36839: 20887, 36840: 21104, 36841: 22478, 36842: 22580, 36843: 22732, 36844: 23330, 36845: 24120, 36846: 24773, 36847: 25854, 36848: 26465, 36849: 26454, 36850: 27972, 36851: 29366, 36852: 30067, 36853: 31331, 36854: 33976, 36855: 35698, 36856: 37304, 36857: 37664, 36858: 22065, 36859: 22516, 36860: 39166, 36928: 25325, 36929: 26893, 36930: 27542, 36931: 29165, 36932: 32340, 36933: 32887, 36934: 33394, 36935: 35302, 36936: 39135, 36937: 34645, 36938: 36785, 36939: 23611, 36940: 20280, 36941: 20449, 36942: 20405, 36943: 21767, 36944: 23072, 36945: 23517, 36946: 23529, 36947: 24515, 36948: 24910, 36949: 25391, 36950: 26032, 36951: 26187, 36952: 26862, 36953: 27035, 36954: 28024, 36955: 28145, 36956: 30003, 36957: 30137, 36958: 30495, 36959: 31070, 36960: 31206, 36961: 32051, 36962: 33251, 36963: 33455, 36964: 34218, 36965: 35242, 36966: 35386, 36967: 36523, 36968: 36763, 36969: 36914, 36970: 37341, 36971: 38663, 36972: 20154, 36973: 20161, 36974: 20995, 36975: 22645, 36976: 22764, 36977: 23563, 36978: 29978, 36979: 23613, 36980: 33102, 36981: 35338, 36982: 36805, 36983: 38499, 36984: 38765, 36985: 31525, 36986: 35535, 36987: 38920, 36988: 37218, 36989: 22259, 36990: 21416, 36992: 36887, 36993: 21561, 36994: 22402, 36995: 24101, 36996: 25512, 36997: 27700, 36998: 28810, 36999: 30561, 37e3: 31883, 37001: 32736, 37002: 34928, 37003: 36930, 37004: 37204, 37005: 37648, 37006: 37656, 37007: 38543, 37008: 29790, 37009: 39620, 37010: 23815, 37011: 23913, 37012: 25968, 37013: 26530, 37014: 36264, 37015: 38619, 37016: 25454, 37017: 26441, 37018: 26905, 37019: 33733, 37020: 38935, 37021: 38592, 37022: 35070, 37023: 28548, 37024: 25722, 37025: 23544, 37026: 19990, 37027: 28716, 37028: 30045, 37029: 26159, 37030: 20932, 37031: 21046, 37032: 21218, 37033: 22995, 37034: 24449, 37035: 24615, 37036: 25104, 37037: 25919, 37038: 25972, 37039: 26143, 37040: 26228, 37041: 26866, 37042: 26646, 37043: 27491, 37044: 28165, 37045: 29298, 37046: 29983, 37047: 30427, 37048: 31934, 37049: 32854, 37050: 22768, 37051: 35069, 37052: 35199, 37053: 35488, 37054: 35475, 37055: 35531, 37056: 36893, 37057: 37266, 37058: 38738, 37059: 38745, 37060: 25993, 37061: 31246, 37062: 33030, 37063: 38587, 37064: 24109, 37065: 24796, 37066: 25114, 37067: 26021, 37068: 26132, 37069: 26512, 37070: 30707, 37071: 31309, 37072: 31821, 37073: 32318, 37074: 33034, 37075: 36012, 37076: 36196, 37077: 36321, 37078: 36447, 37079: 30889, 37080: 20999, 37081: 25305, 37082: 25509, 37083: 25666, 37084: 25240, 37085: 35373, 37086: 31363, 37087: 31680, 37088: 35500, 37089: 38634, 37090: 32118, 37091: 33292, 37092: 34633, 37093: 20185, 37094: 20808, 37095: 21315, 37096: 21344, 37097: 23459, 37098: 23554, 37099: 23574, 37100: 24029, 37101: 25126, 37102: 25159, 37103: 25776, 37104: 26643, 37105: 26676, 37106: 27849, 37107: 27973, 37108: 27927, 37109: 26579, 37110: 28508, 37111: 29006, 37112: 29053, 37113: 26059, 37114: 31359, 37115: 31661, 37116: 32218, 37184: 32330, 37185: 32680, 37186: 33146, 37187: 33307, 37188: 33337, 37189: 34214, 37190: 35438, 37191: 36046, 37192: 36341, 37193: 36984, 37194: 36983, 37195: 37549, 37196: 37521, 37197: 38275, 37198: 39854, 37199: 21069, 37200: 21892, 37201: 28472, 37202: 28982, 37203: 20840, 37204: 31109, 37205: 32341, 37206: 33203, 37207: 31950, 37208: 22092, 37209: 22609, 37210: 23720, 37211: 25514, 37212: 26366, 37213: 26365, 37214: 26970, 37215: 29401, 37216: 30095, 37217: 30094, 37218: 30990, 37219: 31062, 37220: 31199, 37221: 31895, 37222: 32032, 37223: 32068, 37224: 34311, 37225: 35380, 37226: 38459, 37227: 36961, 37228: 40736, 37229: 20711, 37230: 21109, 37231: 21452, 37232: 21474, 37233: 20489, 37234: 21930, 37235: 22766, 37236: 22863, 37237: 29245, 37238: 23435, 37239: 23652, 37240: 21277, 37241: 24803, 37242: 24819, 37243: 25436, 37244: 25475, 37245: 25407, 37246: 25531, 37248: 25805, 37249: 26089, 37250: 26361, 37251: 24035, 37252: 27085, 37253: 27133, 37254: 28437, 37255: 29157, 37256: 20105, 37257: 30185, 37258: 30456, 37259: 31379, 37260: 31967, 37261: 32207, 37262: 32156, 37263: 32865, 37264: 33609, 37265: 33624, 37266: 33900, 37267: 33980, 37268: 34299, 37269: 35013, 37270: 36208, 37271: 36865, 37272: 36973, 37273: 37783, 37274: 38684, 37275: 39442, 37276: 20687, 37277: 22679, 37278: 24974, 37279: 33235, 37280: 34101, 37281: 36104, 37282: 36896, 37283: 20419, 37284: 20596, 37285: 21063, 37286: 21363, 37287: 24687, 37288: 25417, 37289: 26463, 37290: 28204, 37291: 36275, 37292: 36895, 37293: 20439, 37294: 23646, 37295: 36042, 37296: 26063, 37297: 32154, 37298: 21330, 37299: 34966, 37300: 20854, 37301: 25539, 37302: 23384, 37303: 23403, 37304: 23562, 37305: 25613, 37306: 26449, 37307: 36956, 37308: 20182, 37309: 22810, 37310: 22826, 37311: 27760, 37312: 35409, 37313: 21822, 37314: 22549, 37315: 22949, 37316: 24816, 37317: 25171, 37318: 26561, 37319: 33333, 37320: 26965, 37321: 38464, 37322: 39364, 37323: 39464, 37324: 20307, 37325: 22534, 37326: 23550, 37327: 32784, 37328: 23729, 37329: 24111, 37330: 24453, 37331: 24608, 37332: 24907, 37333: 25140, 37334: 26367, 37335: 27888, 37336: 28382, 37337: 32974, 37338: 33151, 37339: 33492, 37340: 34955, 37341: 36024, 37342: 36864, 37343: 36910, 37344: 38538, 37345: 40667, 37346: 39899, 37347: 20195, 37348: 21488, 37349: 22823, 37350: 31532, 37351: 37261, 37352: 38988, 37353: 40441, 37354: 28381, 37355: 28711, 37356: 21331, 37357: 21828, 37358: 23429, 37359: 25176, 37360: 25246, 37361: 25299, 37362: 27810, 37363: 28655, 37364: 29730, 37365: 35351, 37366: 37944, 37367: 28609, 37368: 35582, 37369: 33592, 37370: 20967, 37371: 34552, 37372: 21482, 37440: 21481, 37441: 20294, 37442: 36948, 37443: 36784, 37444: 22890, 37445: 33073, 37446: 24061, 37447: 31466, 37448: 36799, 37449: 26842, 37450: 35895, 37451: 29432, 37452: 40008, 37453: 27197, 37454: 35504, 37455: 20025, 37456: 21336, 37457: 22022, 37458: 22374, 37459: 25285, 37460: 25506, 37461: 26086, 37462: 27470, 37463: 28129, 37464: 28251, 37465: 28845, 37466: 30701, 37467: 31471, 37468: 31658, 37469: 32187, 37470: 32829, 37471: 32966, 37472: 34507, 37473: 35477, 37474: 37723, 37475: 22243, 37476: 22727, 37477: 24382, 37478: 26029, 37479: 26262, 37480: 27264, 37481: 27573, 37482: 30007, 37483: 35527, 37484: 20516, 37485: 30693, 37486: 22320, 37487: 24347, 37488: 24677, 37489: 26234, 37490: 27744, 37491: 30196, 37492: 31258, 37493: 32622, 37494: 33268, 37495: 34584, 37496: 36933, 37497: 39347, 37498: 31689, 37499: 30044, 37500: 31481, 37501: 31569, 37502: 33988, 37504: 36880, 37505: 31209, 37506: 31378, 37507: 33590, 37508: 23265, 37509: 30528, 37510: 20013, 37511: 20210, 37512: 23449, 37513: 24544, 37514: 25277, 37515: 26172, 37516: 26609, 37517: 27880, 37518: 34411, 37519: 34935, 37520: 35387, 37521: 37198, 37522: 37619, 37523: 39376, 37524: 27159, 37525: 28710, 37526: 29482, 37527: 33511, 37528: 33879, 37529: 36015, 37530: 19969, 37531: 20806, 37532: 20939, 37533: 21899, 37534: 23541, 37535: 24086, 37536: 24115, 37537: 24193, 37538: 24340, 37539: 24373, 37540: 24427, 37541: 24500, 37542: 25074, 37543: 25361, 37544: 26274, 37545: 26397, 37546: 28526, 37547: 29266, 37548: 30010, 37549: 30522, 37550: 32884, 37551: 33081, 37552: 33144, 37553: 34678, 37554: 35519, 37555: 35548, 37556: 36229, 37557: 36339, 37558: 37530, 37559: 38263, 37560: 38914, 37561: 40165, 37562: 21189, 37563: 25431, 37564: 30452, 37565: 26389, 37566: 27784, 37567: 29645, 37568: 36035, 37569: 37806, 37570: 38515, 37571: 27941, 37572: 22684, 37573: 26894, 37574: 27084, 37575: 36861, 37576: 37786, 37577: 30171, 37578: 36890, 37579: 22618, 37580: 26626, 37581: 25524, 37582: 27131, 37583: 20291, 37584: 28460, 37585: 26584, 37586: 36795, 37587: 34086, 37588: 32180, 37589: 37716, 37590: 26943, 37591: 28528, 37592: 22378, 37593: 22775, 37594: 23340, 37595: 32044, 37596: 29226, 37597: 21514, 37598: 37347, 37599: 40372, 37600: 20141, 37601: 20302, 37602: 20572, 37603: 20597, 37604: 21059, 37605: 35998, 37606: 21576, 37607: 22564, 37608: 23450, 37609: 24093, 37610: 24213, 37611: 24237, 37612: 24311, 37613: 24351, 37614: 24716, 37615: 25269, 37616: 25402, 37617: 25552, 37618: 26799, 37619: 27712, 37620: 30855, 37621: 31118, 37622: 31243, 37623: 32224, 37624: 33351, 37625: 35330, 37626: 35558, 37627: 36420, 37628: 36883, 37696: 37048, 37697: 37165, 37698: 37336, 37699: 40718, 37700: 27877, 37701: 25688, 37702: 25826, 37703: 25973, 37704: 28404, 37705: 30340, 37706: 31515, 37707: 36969, 37708: 37841, 37709: 28346, 37710: 21746, 37711: 24505, 37712: 25764, 37713: 36685, 37714: 36845, 37715: 37444, 37716: 20856, 37717: 22635, 37718: 22825, 37719: 23637, 37720: 24215, 37721: 28155, 37722: 32399, 37723: 29980, 37724: 36028, 37725: 36578, 37726: 39003, 37727: 28857, 37728: 20253, 37729: 27583, 37730: 28593, 37731: 3e4, 37732: 38651, 37733: 20814, 37734: 21520, 37735: 22581, 37736: 22615, 37737: 22956, 37738: 23648, 37739: 24466, 37740: 26007, 37741: 26460, 37742: 28193, 37743: 30331, 37744: 33759, 37745: 36077, 37746: 36884, 37747: 37117, 37748: 37709, 37749: 30757, 37750: 30778, 37751: 21162, 37752: 24230, 37753: 22303, 37754: 22900, 37755: 24594, 37756: 20498, 37757: 20826, 37758: 20908, 37760: 20941, 37761: 20992, 37762: 21776, 37763: 22612, 37764: 22616, 37765: 22871, 37766: 23445, 37767: 23798, 37768: 23947, 37769: 24764, 37770: 25237, 37771: 25645, 37772: 26481, 37773: 26691, 37774: 26812, 37775: 26847, 37776: 30423, 37777: 28120, 37778: 28271, 37779: 28059, 37780: 28783, 37781: 29128, 37782: 24403, 37783: 30168, 37784: 31095, 37785: 31561, 37786: 31572, 37787: 31570, 37788: 31958, 37789: 32113, 37790: 21040, 37791: 33891, 37792: 34153, 37793: 34276, 37794: 35342, 37795: 35588, 37796: 35910, 37797: 36367, 37798: 36867, 37799: 36879, 37800: 37913, 37801: 38518, 37802: 38957, 37803: 39472, 37804: 38360, 37805: 20685, 37806: 21205, 37807: 21516, 37808: 22530, 37809: 23566, 37810: 24999, 37811: 25758, 37812: 27934, 37813: 30643, 37814: 31461, 37815: 33012, 37816: 33796, 37817: 36947, 37818: 37509, 37819: 23776, 37820: 40199, 37821: 21311, 37822: 24471, 37823: 24499, 37824: 28060, 37825: 29305, 37826: 30563, 37827: 31167, 37828: 31716, 37829: 27602, 37830: 29420, 37831: 35501, 37832: 26627, 37833: 27233, 37834: 20984, 37835: 31361, 37836: 26932, 37837: 23626, 37838: 40182, 37839: 33515, 37840: 23493, 37841: 37193, 37842: 28702, 37843: 22136, 37844: 23663, 37845: 24775, 37846: 25958, 37847: 27788, 37848: 35930, 37849: 36929, 37850: 38931, 37851: 21585, 37852: 26311, 37853: 37389, 37854: 22856, 37855: 37027, 37856: 20869, 37857: 20045, 37858: 20970, 37859: 34201, 37860: 35598, 37861: 28760, 37862: 25466, 37863: 37707, 37864: 26978, 37865: 39348, 37866: 32260, 37867: 30071, 37868: 21335, 37869: 26976, 37870: 36575, 37871: 38627, 37872: 27741, 37873: 20108, 37874: 23612, 37875: 24336, 37876: 36841, 37877: 21250, 37878: 36049, 37879: 32905, 37880: 34425, 37881: 24319, 37882: 26085, 37883: 20083, 37884: 20837, 37952: 22914, 37953: 23615, 37954: 38894, 37955: 20219, 37956: 22922, 37957: 24525, 37958: 35469, 37959: 28641, 37960: 31152, 37961: 31074, 37962: 23527, 37963: 33905, 37964: 29483, 37965: 29105, 37966: 24180, 37967: 24565, 37968: 25467, 37969: 25754, 37970: 29123, 37971: 31896, 37972: 20035, 37973: 24316, 37974: 20043, 37975: 22492, 37976: 22178, 37977: 24745, 37978: 28611, 37979: 32013, 37980: 33021, 37981: 33075, 37982: 33215, 37983: 36786, 37984: 35223, 37985: 34468, 37986: 24052, 37987: 25226, 37988: 25773, 37989: 35207, 37990: 26487, 37991: 27874, 37992: 27966, 37993: 29750, 37994: 30772, 37995: 23110, 37996: 32629, 37997: 33453, 37998: 39340, 37999: 20467, 38e3: 24259, 38001: 25309, 38002: 25490, 38003: 25943, 38004: 26479, 38005: 30403, 38006: 29260, 38007: 32972, 38008: 32954, 38009: 36649, 38010: 37197, 38011: 20493, 38012: 22521, 38013: 23186, 38014: 26757, 38016: 26995, 38017: 29028, 38018: 29437, 38019: 36023, 38020: 22770, 38021: 36064, 38022: 38506, 38023: 36889, 38024: 34687, 38025: 31204, 38026: 30695, 38027: 33833, 38028: 20271, 38029: 21093, 38030: 21338, 38031: 25293, 38032: 26575, 38033: 27850, 38034: 30333, 38035: 31636, 38036: 31893, 38037: 33334, 38038: 34180, 38039: 36843, 38040: 26333, 38041: 28448, 38042: 29190, 38043: 32283, 38044: 33707, 38045: 39361, 38046: 40614, 38047: 20989, 38048: 31665, 38049: 30834, 38050: 31672, 38051: 32903, 38052: 31560, 38053: 27368, 38054: 24161, 38055: 32908, 38056: 30033, 38057: 30048, 38058: 20843, 38059: 37474, 38060: 28300, 38061: 30330, 38062: 37271, 38063: 39658, 38064: 20240, 38065: 32624, 38066: 25244, 38067: 31567, 38068: 38309, 38069: 40169, 38070: 22138, 38071: 22617, 38072: 34532, 38073: 38588, 38074: 20276, 38075: 21028, 38076: 21322, 38077: 21453, 38078: 21467, 38079: 24070, 38080: 25644, 38081: 26001, 38082: 26495, 38083: 27710, 38084: 27726, 38085: 29256, 38086: 29359, 38087: 29677, 38088: 30036, 38089: 32321, 38090: 33324, 38091: 34281, 38092: 36009, 38093: 31684, 38094: 37318, 38095: 29033, 38096: 38930, 38097: 39151, 38098: 25405, 38099: 26217, 38100: 30058, 38101: 30436, 38102: 30928, 38103: 34115, 38104: 34542, 38105: 21290, 38106: 21329, 38107: 21542, 38108: 22915, 38109: 24199, 38110: 24444, 38111: 24754, 38112: 25161, 38113: 25209, 38114: 25259, 38115: 26e3, 38116: 27604, 38117: 27852, 38118: 30130, 38119: 30382, 38120: 30865, 38121: 31192, 38122: 32203, 38123: 32631, 38124: 32933, 38125: 34987, 38126: 35513, 38127: 36027, 38128: 36991, 38129: 38750, 38130: 39131, 38131: 27147, 38132: 31800, 38133: 20633, 38134: 23614, 38135: 24494, 38136: 26503, 38137: 27608, 38138: 29749, 38139: 30473, 38140: 32654, 38208: 40763, 38209: 26570, 38210: 31255, 38211: 21305, 38212: 30091, 38213: 39661, 38214: 24422, 38215: 33181, 38216: 33777, 38217: 32920, 38218: 24380, 38219: 24517, 38220: 30050, 38221: 31558, 38222: 36924, 38223: 26727, 38224: 23019, 38225: 23195, 38226: 32016, 38227: 30334, 38228: 35628, 38229: 20469, 38230: 24426, 38231: 27161, 38232: 27703, 38233: 28418, 38234: 29922, 38235: 31080, 38236: 34920, 38237: 35413, 38238: 35961, 38239: 24287, 38240: 25551, 38241: 30149, 38242: 31186, 38243: 33495, 38244: 37672, 38245: 37618, 38246: 33948, 38247: 34541, 38248: 39981, 38249: 21697, 38250: 24428, 38251: 25996, 38252: 27996, 38253: 28693, 38254: 36007, 38255: 36051, 38256: 38971, 38257: 25935, 38258: 29942, 38259: 19981, 38260: 20184, 38261: 22496, 38262: 22827, 38263: 23142, 38264: 23500, 38265: 20904, 38266: 24067, 38267: 24220, 38268: 24598, 38269: 25206, 38270: 25975, 38272: 26023, 38273: 26222, 38274: 28014, 38275: 29238, 38276: 31526, 38277: 33104, 38278: 33178, 38279: 33433, 38280: 35676, 38281: 36e3, 38282: 36070, 38283: 36212, 38284: 38428, 38285: 38468, 38286: 20398, 38287: 25771, 38288: 27494, 38289: 33310, 38290: 33889, 38291: 34154, 38292: 37096, 38293: 23553, 38294: 26963, 38295: 39080, 38296: 33914, 38297: 34135, 38298: 20239, 38299: 21103, 38300: 24489, 38301: 24133, 38302: 26381, 38303: 31119, 38304: 33145, 38305: 35079, 38306: 35206, 38307: 28149, 38308: 24343, 38309: 25173, 38310: 27832, 38311: 20175, 38312: 29289, 38313: 39826, 38314: 20998, 38315: 21563, 38316: 22132, 38317: 22707, 38318: 24996, 38319: 25198, 38320: 28954, 38321: 22894, 38322: 31881, 38323: 31966, 38324: 32027, 38325: 38640, 38326: 25991, 38327: 32862, 38328: 19993, 38329: 20341, 38330: 20853, 38331: 22592, 38332: 24163, 38333: 24179, 38334: 24330, 38335: 26564, 38336: 20006, 38337: 34109, 38338: 38281, 38339: 38491, 38340: 31859, 38341: 38913, 38342: 20731, 38343: 22721, 38344: 30294, 38345: 30887, 38346: 21029, 38347: 30629, 38348: 34065, 38349: 31622, 38350: 20559, 38351: 22793, 38352: 29255, 38353: 31687, 38354: 32232, 38355: 36794, 38356: 36820, 38357: 36941, 38358: 20415, 38359: 21193, 38360: 23081, 38361: 24321, 38362: 38829, 38363: 20445, 38364: 33303, 38365: 37610, 38366: 22275, 38367: 25429, 38368: 27497, 38369: 29995, 38370: 35036, 38371: 36628, 38372: 31298, 38373: 21215, 38374: 22675, 38375: 24917, 38376: 25098, 38377: 26286, 38378: 27597, 38379: 31807, 38380: 33769, 38381: 20515, 38382: 20472, 38383: 21253, 38384: 21574, 38385: 22577, 38386: 22857, 38387: 23453, 38388: 23792, 38389: 23791, 38390: 23849, 38391: 24214, 38392: 25265, 38393: 25447, 38394: 25918, 38395: 26041, 38396: 26379, 38464: 27861, 38465: 27873, 38466: 28921, 38467: 30770, 38468: 32299, 38469: 32990, 38470: 33459, 38471: 33804, 38472: 34028, 38473: 34562, 38474: 35090, 38475: 35370, 38476: 35914, 38477: 37030, 38478: 37586, 38479: 39165, 38480: 40179, 38481: 40300, 38482: 20047, 38483: 20129, 38484: 20621, 38485: 21078, 38486: 22346, 38487: 22952, 38488: 24125, 38489: 24536, 38490: 24537, 38491: 25151, 38492: 26292, 38493: 26395, 38494: 26576, 38495: 26834, 38496: 20882, 38497: 32033, 38498: 32938, 38499: 33192, 38500: 35584, 38501: 35980, 38502: 36031, 38503: 37502, 38504: 38450, 38505: 21536, 38506: 38956, 38507: 21271, 38508: 20693, 38509: 21340, 38510: 22696, 38511: 25778, 38512: 26420, 38513: 29287, 38514: 30566, 38515: 31302, 38516: 37350, 38517: 21187, 38518: 27809, 38519: 27526, 38520: 22528, 38521: 24140, 38522: 22868, 38523: 26412, 38524: 32763, 38525: 20961, 38526: 30406, 38528: 25705, 38529: 30952, 38530: 39764, 38531: 40635, 38532: 22475, 38533: 22969, 38534: 26151, 38535: 26522, 38536: 27598, 38537: 21737, 38538: 27097, 38539: 24149, 38540: 33180, 38541: 26517, 38542: 39850, 38543: 26622, 38544: 40018, 38545: 26717, 38546: 20134, 38547: 20451, 38548: 21448, 38549: 25273, 38550: 26411, 38551: 27819, 38552: 36804, 38553: 20397, 38554: 32365, 38555: 40639, 38556: 19975, 38557: 24930, 38558: 28288, 38559: 28459, 38560: 34067, 38561: 21619, 38562: 26410, 38563: 39749, 38564: 24051, 38565: 31637, 38566: 23724, 38567: 23494, 38568: 34588, 38569: 28234, 38570: 34001, 38571: 31252, 38572: 33032, 38573: 22937, 38574: 31885, 38575: 27665, 38576: 30496, 38577: 21209, 38578: 22818, 38579: 28961, 38580: 29279, 38581: 30683, 38582: 38695, 38583: 40289, 38584: 26891, 38585: 23167, 38586: 23064, 38587: 20901, 38588: 21517, 38589: 21629, 38590: 26126, 38591: 30431, 38592: 36855, 38593: 37528, 38594: 40180, 38595: 23018, 38596: 29277, 38597: 28357, 38598: 20813, 38599: 26825, 38600: 32191, 38601: 32236, 38602: 38754, 38603: 40634, 38604: 25720, 38605: 27169, 38606: 33538, 38607: 22916, 38608: 23391, 38609: 27611, 38610: 29467, 38611: 30450, 38612: 32178, 38613: 32791, 38614: 33945, 38615: 20786, 38616: 26408, 38617: 40665, 38618: 30446, 38619: 26466, 38620: 21247, 38621: 39173, 38622: 23588, 38623: 25147, 38624: 31870, 38625: 36016, 38626: 21839, 38627: 24758, 38628: 32011, 38629: 38272, 38630: 21249, 38631: 20063, 38632: 20918, 38633: 22812, 38634: 29242, 38635: 32822, 38636: 37326, 38637: 24357, 38638: 30690, 38639: 21380, 38640: 24441, 38641: 32004, 38642: 34220, 38643: 35379, 38644: 36493, 38645: 38742, 38646: 26611, 38647: 34222, 38648: 37971, 38649: 24841, 38650: 24840, 38651: 27833, 38652: 30290, 38720: 35565, 38721: 36664, 38722: 21807, 38723: 20305, 38724: 20778, 38725: 21191, 38726: 21451, 38727: 23461, 38728: 24189, 38729: 24736, 38730: 24962, 38731: 25558, 38732: 26377, 38733: 26586, 38734: 28263, 38735: 28044, 38736: 29494, 38737: 29495, 38738: 30001, 38739: 31056, 38740: 35029, 38741: 35480, 38742: 36938, 38743: 37009, 38744: 37109, 38745: 38596, 38746: 34701, 38747: 22805, 38748: 20104, 38749: 20313, 38750: 19982, 38751: 35465, 38752: 36671, 38753: 38928, 38754: 20653, 38755: 24188, 38756: 22934, 38757: 23481, 38758: 24248, 38759: 25562, 38760: 25594, 38761: 25793, 38762: 26332, 38763: 26954, 38764: 27096, 38765: 27915, 38766: 28342, 38767: 29076, 38768: 29992, 38769: 31407, 38770: 32650, 38771: 32768, 38772: 33865, 38773: 33993, 38774: 35201, 38775: 35617, 38776: 36362, 38777: 36965, 38778: 38525, 38779: 39178, 38780: 24958, 38781: 25233, 38782: 27442, 38784: 27779, 38785: 28020, 38786: 32716, 38787: 32764, 38788: 28096, 38789: 32645, 38790: 34746, 38791: 35064, 38792: 26469, 38793: 33713, 38794: 38972, 38795: 38647, 38796: 27931, 38797: 32097, 38798: 33853, 38799: 37226, 38800: 20081, 38801: 21365, 38802: 23888, 38803: 27396, 38804: 28651, 38805: 34253, 38806: 34349, 38807: 35239, 38808: 21033, 38809: 21519, 38810: 23653, 38811: 26446, 38812: 26792, 38813: 29702, 38814: 29827, 38815: 30178, 38816: 35023, 38817: 35041, 38818: 37324, 38819: 38626, 38820: 38520, 38821: 24459, 38822: 29575, 38823: 31435, 38824: 33870, 38825: 25504, 38826: 30053, 38827: 21129, 38828: 27969, 38829: 28316, 38830: 29705, 38831: 30041, 38832: 30827, 38833: 31890, 38834: 38534, 38835: 31452, 38836: 40845, 38837: 20406, 38838: 24942, 38839: 26053, 38840: 34396, 38841: 20102, 38842: 20142, 38843: 20698, 38844: 20001, 38845: 20940, 38846: 23534, 38847: 26009, 38848: 26753, 38849: 28092, 38850: 29471, 38851: 30274, 38852: 30637, 38853: 31260, 38854: 31975, 38855: 33391, 38856: 35538, 38857: 36988, 38858: 37327, 38859: 38517, 38860: 38936, 38861: 21147, 38862: 32209, 38863: 20523, 38864: 21400, 38865: 26519, 38866: 28107, 38867: 29136, 38868: 29747, 38869: 33256, 38870: 36650, 38871: 38563, 38872: 40023, 38873: 40607, 38874: 29792, 38875: 22593, 38876: 28057, 38877: 32047, 38878: 39006, 38879: 20196, 38880: 20278, 38881: 20363, 38882: 20919, 38883: 21169, 38884: 23994, 38885: 24604, 38886: 29618, 38887: 31036, 38888: 33491, 38889: 37428, 38890: 38583, 38891: 38646, 38892: 38666, 38893: 40599, 38894: 40802, 38895: 26278, 38896: 27508, 38897: 21015, 38898: 21155, 38899: 28872, 38900: 35010, 38901: 24265, 38902: 24651, 38903: 24976, 38904: 28451, 38905: 29001, 38906: 31806, 38907: 32244, 38908: 32879, 38976: 34030, 38977: 36899, 38978: 37676, 38979: 21570, 38980: 39791, 38981: 27347, 38982: 28809, 38983: 36034, 38984: 36335, 38985: 38706, 38986: 21172, 38987: 23105, 38988: 24266, 38989: 24324, 38990: 26391, 38991: 27004, 38992: 27028, 38993: 28010, 38994: 28431, 38995: 29282, 38996: 29436, 38997: 31725, 38998: 32769, 38999: 32894, 39e3: 34635, 39001: 37070, 39002: 20845, 39003: 40595, 39004: 31108, 39005: 32907, 39006: 37682, 39007: 35542, 39008: 20525, 39009: 21644, 39010: 35441, 39011: 27498, 39012: 36036, 39013: 33031, 39014: 24785, 39015: 26528, 39016: 40434, 39017: 20121, 39018: 20120, 39019: 39952, 39020: 35435, 39021: 34241, 39022: 34152, 39023: 26880, 39024: 28286, 39025: 30871, 39026: 33109, 39071: 24332, 39072: 19984, 39073: 19989, 39074: 20010, 39075: 20017, 39076: 20022, 39077: 20028, 39078: 20031, 39079: 20034, 39080: 20054, 39081: 20056, 39082: 20098, 39083: 20101, 39084: 35947, 39085: 20106, 39086: 33298, 39087: 24333, 39088: 20110, 39089: 20126, 39090: 20127, 39091: 20128, 39092: 20130, 39093: 20144, 39094: 20147, 39095: 20150, 39096: 20174, 39097: 20173, 39098: 20164, 39099: 20166, 39100: 20162, 39101: 20183, 39102: 20190, 39103: 20205, 39104: 20191, 39105: 20215, 39106: 20233, 39107: 20314, 39108: 20272, 39109: 20315, 39110: 20317, 39111: 20311, 39112: 20295, 39113: 20342, 39114: 20360, 39115: 20367, 39116: 20376, 39117: 20347, 39118: 20329, 39119: 20336, 39120: 20369, 39121: 20335, 39122: 20358, 39123: 20374, 39124: 20760, 39125: 20436, 39126: 20447, 39127: 20430, 39128: 20440, 39129: 20443, 39130: 20433, 39131: 20442, 39132: 20432, 39133: 20452, 39134: 20453, 39135: 20506, 39136: 20520, 39137: 20500, 39138: 20522, 39139: 20517, 39140: 20485, 39141: 20252, 39142: 20470, 39143: 20513, 39144: 20521, 39145: 20524, 39146: 20478, 39147: 20463, 39148: 20497, 39149: 20486, 39150: 20547, 39151: 20551, 39152: 26371, 39153: 20565, 39154: 20560, 39155: 20552, 39156: 20570, 39157: 20566, 39158: 20588, 39159: 20600, 39160: 20608, 39161: 20634, 39162: 20613, 39163: 20660, 39164: 20658, 39232: 20681, 39233: 20682, 39234: 20659, 39235: 20674, 39236: 20694, 39237: 20702, 39238: 20709, 39239: 20717, 39240: 20707, 39241: 20718, 39242: 20729, 39243: 20725, 39244: 20745, 39245: 20737, 39246: 20738, 39247: 20758, 39248: 20757, 39249: 20756, 39250: 20762, 39251: 20769, 39252: 20794, 39253: 20791, 39254: 20796, 39255: 20795, 39256: 20799, 39257: 20800, 39258: 20818, 39259: 20812, 39260: 20820, 39261: 20834, 39262: 31480, 39263: 20841, 39264: 20842, 39265: 20846, 39266: 20864, 39267: 20866, 39268: 22232, 39269: 20876, 39270: 20873, 39271: 20879, 39272: 20881, 39273: 20883, 39274: 20885, 39275: 20886, 39276: 20900, 39277: 20902, 39278: 20898, 39279: 20905, 39280: 20906, 39281: 20907, 39282: 20915, 39283: 20913, 39284: 20914, 39285: 20912, 39286: 20917, 39287: 20925, 39288: 20933, 39289: 20937, 39290: 20955, 39291: 20960, 39292: 34389, 39293: 20969, 39294: 20973, 39296: 20976, 39297: 20981, 39298: 20990, 39299: 20996, 39300: 21003, 39301: 21012, 39302: 21006, 39303: 21031, 39304: 21034, 39305: 21038, 39306: 21043, 39307: 21049, 39308: 21071, 39309: 21060, 39310: 21067, 39311: 21068, 39312: 21086, 39313: 21076, 39314: 21098, 39315: 21108, 39316: 21097, 39317: 21107, 39318: 21119, 39319: 21117, 39320: 21133, 39321: 21140, 39322: 21138, 39323: 21105, 39324: 21128, 39325: 21137, 39326: 36776, 39327: 36775, 39328: 21164, 39329: 21165, 39330: 21180, 39331: 21173, 39332: 21185, 39333: 21197, 39334: 21207, 39335: 21214, 39336: 21219, 39337: 21222, 39338: 39149, 39339: 21216, 39340: 21235, 39341: 21237, 39342: 21240, 39343: 21241, 39344: 21254, 39345: 21256, 39346: 30008, 39347: 21261, 39348: 21264, 39349: 21263, 39350: 21269, 39351: 21274, 39352: 21283, 39353: 21295, 39354: 21297, 39355: 21299, 39356: 21304, 39357: 21312, 39358: 21318, 39359: 21317, 39360: 19991, 39361: 21321, 39362: 21325, 39363: 20950, 39364: 21342, 39365: 21353, 39366: 21358, 39367: 22808, 39368: 21371, 39369: 21367, 39370: 21378, 39371: 21398, 39372: 21408, 39373: 21414, 39374: 21413, 39375: 21422, 39376: 21424, 39377: 21430, 39378: 21443, 39379: 31762, 39380: 38617, 39381: 21471, 39382: 26364, 39383: 29166, 39384: 21486, 39385: 21480, 39386: 21485, 39387: 21498, 39388: 21505, 39389: 21565, 39390: 21568, 39391: 21548, 39392: 21549, 39393: 21564, 39394: 21550, 39395: 21558, 39396: 21545, 39397: 21533, 39398: 21582, 39399: 21647, 39400: 21621, 39401: 21646, 39402: 21599, 39403: 21617, 39404: 21623, 39405: 21616, 39406: 21650, 39407: 21627, 39408: 21632, 39409: 21622, 39410: 21636, 39411: 21648, 39412: 21638, 39413: 21703, 39414: 21666, 39415: 21688, 39416: 21669, 39417: 21676, 39418: 21700, 39419: 21704, 39420: 21672, 39488: 21675, 39489: 21698, 39490: 21668, 39491: 21694, 39492: 21692, 39493: 21720, 39494: 21733, 39495: 21734, 39496: 21775, 39497: 21780, 39498: 21757, 39499: 21742, 39500: 21741, 39501: 21754, 39502: 21730, 39503: 21817, 39504: 21824, 39505: 21859, 39506: 21836, 39507: 21806, 39508: 21852, 39509: 21829, 39510: 21846, 39511: 21847, 39512: 21816, 39513: 21811, 39514: 21853, 39515: 21913, 39516: 21888, 39517: 21679, 39518: 21898, 39519: 21919, 39520: 21883, 39521: 21886, 39522: 21912, 39523: 21918, 39524: 21934, 39525: 21884, 39526: 21891, 39527: 21929, 39528: 21895, 39529: 21928, 39530: 21978, 39531: 21957, 39532: 21983, 39533: 21956, 39534: 21980, 39535: 21988, 39536: 21972, 39537: 22036, 39538: 22007, 39539: 22038, 39540: 22014, 39541: 22013, 39542: 22043, 39543: 22009, 39544: 22094, 39545: 22096, 39546: 29151, 39547: 22068, 39548: 22070, 39549: 22066, 39550: 22072, 39552: 22123, 39553: 22116, 39554: 22063, 39555: 22124, 39556: 22122, 39557: 22150, 39558: 22144, 39559: 22154, 39560: 22176, 39561: 22164, 39562: 22159, 39563: 22181, 39564: 22190, 39565: 22198, 39566: 22196, 39567: 22210, 39568: 22204, 39569: 22209, 39570: 22211, 39571: 22208, 39572: 22216, 39573: 22222, 39574: 22225, 39575: 22227, 39576: 22231, 39577: 22254, 39578: 22265, 39579: 22272, 39580: 22271, 39581: 22276, 39582: 22281, 39583: 22280, 39584: 22283, 39585: 22285, 39586: 22291, 39587: 22296, 39588: 22294, 39589: 21959, 39590: 22300, 39591: 22310, 39592: 22327, 39593: 22328, 39594: 22350, 39595: 22331, 39596: 22336, 39597: 22351, 39598: 22377, 39599: 22464, 39600: 22408, 39601: 22369, 39602: 22399, 39603: 22409, 39604: 22419, 39605: 22432, 39606: 22451, 39607: 22436, 39608: 22442, 39609: 22448, 39610: 22467, 39611: 22470, 39612: 22484, 39613: 22482, 39614: 22483, 39615: 22538, 39616: 22486, 39617: 22499, 39618: 22539, 39619: 22553, 39620: 22557, 39621: 22642, 39622: 22561, 39623: 22626, 39624: 22603, 39625: 22640, 39626: 27584, 39627: 22610, 39628: 22589, 39629: 22649, 39630: 22661, 39631: 22713, 39632: 22687, 39633: 22699, 39634: 22714, 39635: 22750, 39636: 22715, 39637: 22712, 39638: 22702, 39639: 22725, 39640: 22739, 39641: 22737, 39642: 22743, 39643: 22745, 39644: 22744, 39645: 22757, 39646: 22748, 39647: 22756, 39648: 22751, 39649: 22767, 39650: 22778, 39651: 22777, 39652: 22779, 39653: 22780, 39654: 22781, 39655: 22786, 39656: 22794, 39657: 22800, 39658: 22811, 39659: 26790, 39660: 22821, 39661: 22828, 39662: 22829, 39663: 22834, 39664: 22840, 39665: 22846, 39666: 31442, 39667: 22869, 39668: 22864, 39669: 22862, 39670: 22874, 39671: 22872, 39672: 22882, 39673: 22880, 39674: 22887, 39675: 22892, 39676: 22889, 39744: 22904, 39745: 22913, 39746: 22941, 39747: 20318, 39748: 20395, 39749: 22947, 39750: 22962, 39751: 22982, 39752: 23016, 39753: 23004, 39754: 22925, 39755: 23001, 39756: 23002, 39757: 23077, 39758: 23071, 39759: 23057, 39760: 23068, 39761: 23049, 39762: 23066, 39763: 23104, 39764: 23148, 39765: 23113, 39766: 23093, 39767: 23094, 39768: 23138, 39769: 23146, 39770: 23194, 39771: 23228, 39772: 23230, 39773: 23243, 39774: 23234, 39775: 23229, 39776: 23267, 39777: 23255, 39778: 23270, 39779: 23273, 39780: 23254, 39781: 23290, 39782: 23291, 39783: 23308, 39784: 23307, 39785: 23318, 39786: 23346, 39787: 23248, 39788: 23338, 39789: 23350, 39790: 23358, 39791: 23363, 39792: 23365, 39793: 23360, 39794: 23377, 39795: 23381, 39796: 23386, 39797: 23387, 39798: 23397, 39799: 23401, 39800: 23408, 39801: 23411, 39802: 23413, 39803: 23416, 39804: 25992, 39805: 23418, 39806: 23424, 39808: 23427, 39809: 23462, 39810: 23480, 39811: 23491, 39812: 23495, 39813: 23497, 39814: 23508, 39815: 23504, 39816: 23524, 39817: 23526, 39818: 23522, 39819: 23518, 39820: 23525, 39821: 23531, 39822: 23536, 39823: 23542, 39824: 23539, 39825: 23557, 39826: 23559, 39827: 23560, 39828: 23565, 39829: 23571, 39830: 23584, 39831: 23586, 39832: 23592, 39833: 23608, 39834: 23609, 39835: 23617, 39836: 23622, 39837: 23630, 39838: 23635, 39839: 23632, 39840: 23631, 39841: 23409, 39842: 23660, 39843: 23662, 39844: 20066, 39845: 23670, 39846: 23673, 39847: 23692, 39848: 23697, 39849: 23700, 39850: 22939, 39851: 23723, 39852: 23739, 39853: 23734, 39854: 23740, 39855: 23735, 39856: 23749, 39857: 23742, 39858: 23751, 39859: 23769, 39860: 23785, 39861: 23805, 39862: 23802, 39863: 23789, 39864: 23948, 39865: 23786, 39866: 23819, 39867: 23829, 39868: 23831, 39869: 23900, 39870: 23839, 39871: 23835, 39872: 23825, 39873: 23828, 39874: 23842, 39875: 23834, 39876: 23833, 39877: 23832, 39878: 23884, 39879: 23890, 39880: 23886, 39881: 23883, 39882: 23916, 39883: 23923, 39884: 23926, 39885: 23943, 39886: 23940, 39887: 23938, 39888: 23970, 39889: 23965, 39890: 23980, 39891: 23982, 39892: 23997, 39893: 23952, 39894: 23991, 39895: 23996, 39896: 24009, 39897: 24013, 39898: 24019, 39899: 24018, 39900: 24022, 39901: 24027, 39902: 24043, 39903: 24050, 39904: 24053, 39905: 24075, 39906: 24090, 39907: 24089, 39908: 24081, 39909: 24091, 39910: 24118, 39911: 24119, 39912: 24132, 39913: 24131, 39914: 24128, 39915: 24142, 39916: 24151, 39917: 24148, 39918: 24159, 39919: 24162, 39920: 24164, 39921: 24135, 39922: 24181, 39923: 24182, 39924: 24186, 39925: 40636, 39926: 24191, 39927: 24224, 39928: 24257, 39929: 24258, 39930: 24264, 39931: 24272, 39932: 24271, 4e4: 24278, 40001: 24291, 40002: 24285, 40003: 24282, 40004: 24283, 40005: 24290, 40006: 24289, 40007: 24296, 40008: 24297, 40009: 24300, 40010: 24305, 40011: 24307, 40012: 24304, 40013: 24308, 40014: 24312, 40015: 24318, 40016: 24323, 40017: 24329, 40018: 24413, 40019: 24412, 40020: 24331, 40021: 24337, 40022: 24342, 40023: 24361, 40024: 24365, 40025: 24376, 40026: 24385, 40027: 24392, 40028: 24396, 40029: 24398, 40030: 24367, 40031: 24401, 40032: 24406, 40033: 24407, 40034: 24409, 40035: 24417, 40036: 24429, 40037: 24435, 40038: 24439, 40039: 24451, 40040: 24450, 40041: 24447, 40042: 24458, 40043: 24456, 40044: 24465, 40045: 24455, 40046: 24478, 40047: 24473, 40048: 24472, 40049: 24480, 40050: 24488, 40051: 24493, 40052: 24508, 40053: 24534, 40054: 24571, 40055: 24548, 40056: 24568, 40057: 24561, 40058: 24541, 40059: 24755, 40060: 24575, 40061: 24609, 40062: 24672, 40064: 24601, 40065: 24592, 40066: 24617, 40067: 24590, 40068: 24625, 40069: 24603, 40070: 24597, 40071: 24619, 40072: 24614, 40073: 24591, 40074: 24634, 40075: 24666, 40076: 24641, 40077: 24682, 40078: 24695, 40079: 24671, 40080: 24650, 40081: 24646, 40082: 24653, 40083: 24675, 40084: 24643, 40085: 24676, 40086: 24642, 40087: 24684, 40088: 24683, 40089: 24665, 40090: 24705, 40091: 24717, 40092: 24807, 40093: 24707, 40094: 24730, 40095: 24708, 40096: 24731, 40097: 24726, 40098: 24727, 40099: 24722, 40100: 24743, 40101: 24715, 40102: 24801, 40103: 24760, 40104: 24800, 40105: 24787, 40106: 24756, 40107: 24560, 40108: 24765, 40109: 24774, 40110: 24757, 40111: 24792, 40112: 24909, 40113: 24853, 40114: 24838, 40115: 24822, 40116: 24823, 40117: 24832, 40118: 24820, 40119: 24826, 40120: 24835, 40121: 24865, 40122: 24827, 40123: 24817, 40124: 24845, 40125: 24846, 40126: 24903, 40127: 24894, 40128: 24872, 40129: 24871, 40130: 24906, 40131: 24895, 40132: 24892, 40133: 24876, 40134: 24884, 40135: 24893, 40136: 24898, 40137: 24900, 40138: 24947, 40139: 24951, 40140: 24920, 40141: 24921, 40142: 24922, 40143: 24939, 40144: 24948, 40145: 24943, 40146: 24933, 40147: 24945, 40148: 24927, 40149: 24925, 40150: 24915, 40151: 24949, 40152: 24985, 40153: 24982, 40154: 24967, 40155: 25004, 40156: 24980, 40157: 24986, 40158: 24970, 40159: 24977, 40160: 25003, 40161: 25006, 40162: 25036, 40163: 25034, 40164: 25033, 40165: 25079, 40166: 25032, 40167: 25027, 40168: 25030, 40169: 25018, 40170: 25035, 40171: 32633, 40172: 25037, 40173: 25062, 40174: 25059, 40175: 25078, 40176: 25082, 40177: 25076, 40178: 25087, 40179: 25085, 40180: 25084, 40181: 25086, 40182: 25088, 40183: 25096, 40184: 25097, 40185: 25101, 40186: 25100, 40187: 25108, 40188: 25115, 40256: 25118, 40257: 25121, 40258: 25130, 40259: 25134, 40260: 25136, 40261: 25138, 40262: 25139, 40263: 25153, 40264: 25166, 40265: 25182, 40266: 25187, 40267: 25179, 40268: 25184, 40269: 25192, 40270: 25212, 40271: 25218, 40272: 25225, 40273: 25214, 40274: 25234, 40275: 25235, 40276: 25238, 40277: 25300, 40278: 25219, 40279: 25236, 40280: 25303, 40281: 25297, 40282: 25275, 40283: 25295, 40284: 25343, 40285: 25286, 40286: 25812, 40287: 25288, 40288: 25308, 40289: 25292, 40290: 25290, 40291: 25282, 40292: 25287, 40293: 25243, 40294: 25289, 40295: 25356, 40296: 25326, 40297: 25329, 40298: 25383, 40299: 25346, 40300: 25352, 40301: 25327, 40302: 25333, 40303: 25424, 40304: 25406, 40305: 25421, 40306: 25628, 40307: 25423, 40308: 25494, 40309: 25486, 40310: 25472, 40311: 25515, 40312: 25462, 40313: 25507, 40314: 25487, 40315: 25481, 40316: 25503, 40317: 25525, 40318: 25451, 40320: 25449, 40321: 25534, 40322: 25577, 40323: 25536, 40324: 25542, 40325: 25571, 40326: 25545, 40327: 25554, 40328: 25590, 40329: 25540, 40330: 25622, 40331: 25652, 40332: 25606, 40333: 25619, 40334: 25638, 40335: 25654, 40336: 25885, 40337: 25623, 40338: 25640, 40339: 25615, 40340: 25703, 40341: 25711, 40342: 25718, 40343: 25678, 40344: 25898, 40345: 25749, 40346: 25747, 40347: 25765, 40348: 25769, 40349: 25736, 40350: 25788, 40351: 25818, 40352: 25810, 40353: 25797, 40354: 25799, 40355: 25787, 40356: 25816, 40357: 25794, 40358: 25841, 40359: 25831, 40360: 33289, 40361: 25824, 40362: 25825, 40363: 25260, 40364: 25827, 40365: 25839, 40366: 25900, 40367: 25846, 40368: 25844, 40369: 25842, 40370: 25850, 40371: 25856, 40372: 25853, 40373: 25880, 40374: 25884, 40375: 25861, 40376: 25892, 40377: 25891, 40378: 25899, 40379: 25908, 40380: 25909, 40381: 25911, 40382: 25910, 40383: 25912, 40384: 30027, 40385: 25928, 40386: 25942, 40387: 25941, 40388: 25933, 40389: 25944, 40390: 25950, 40391: 25949, 40392: 25970, 40393: 25976, 40394: 25986, 40395: 25987, 40396: 35722, 40397: 26011, 40398: 26015, 40399: 26027, 40400: 26039, 40401: 26051, 40402: 26054, 40403: 26049, 40404: 26052, 40405: 26060, 40406: 26066, 40407: 26075, 40408: 26073, 40409: 26080, 40410: 26081, 40411: 26097, 40412: 26482, 40413: 26122, 40414: 26115, 40415: 26107, 40416: 26483, 40417: 26165, 40418: 26166, 40419: 26164, 40420: 26140, 40421: 26191, 40422: 26180, 40423: 26185, 40424: 26177, 40425: 26206, 40426: 26205, 40427: 26212, 40428: 26215, 40429: 26216, 40430: 26207, 40431: 26210, 40432: 26224, 40433: 26243, 40434: 26248, 40435: 26254, 40436: 26249, 40437: 26244, 40438: 26264, 40439: 26269, 40440: 26305, 40441: 26297, 40442: 26313, 40443: 26302, 40444: 26300, 40512: 26308, 40513: 26296, 40514: 26326, 40515: 26330, 40516: 26336, 40517: 26175, 40518: 26342, 40519: 26345, 40520: 26352, 40521: 26357, 40522: 26359, 40523: 26383, 40524: 26390, 40525: 26398, 40526: 26406, 40527: 26407, 40528: 38712, 40529: 26414, 40530: 26431, 40531: 26422, 40532: 26433, 40533: 26424, 40534: 26423, 40535: 26438, 40536: 26462, 40537: 26464, 40538: 26457, 40539: 26467, 40540: 26468, 40541: 26505, 40542: 26480, 40543: 26537, 40544: 26492, 40545: 26474, 40546: 26508, 40547: 26507, 40548: 26534, 40549: 26529, 40550: 26501, 40551: 26551, 40552: 26607, 40553: 26548, 40554: 26604, 40555: 26547, 40556: 26601, 40557: 26552, 40558: 26596, 40559: 26590, 40560: 26589, 40561: 26594, 40562: 26606, 40563: 26553, 40564: 26574, 40565: 26566, 40566: 26599, 40567: 27292, 40568: 26654, 40569: 26694, 40570: 26665, 40571: 26688, 40572: 26701, 40573: 26674, 40574: 26702, 40576: 26803, 40577: 26667, 40578: 26713, 40579: 26723, 40580: 26743, 40581: 26751, 40582: 26783, 40583: 26767, 40584: 26797, 40585: 26772, 40586: 26781, 40587: 26779, 40588: 26755, 40589: 27310, 40590: 26809, 40591: 26740, 40592: 26805, 40593: 26784, 40594: 26810, 40595: 26895, 40596: 26765, 40597: 26750, 40598: 26881, 40599: 26826, 40600: 26888, 40601: 26840, 40602: 26914, 40603: 26918, 40604: 26849, 40605: 26892, 40606: 26829, 40607: 26836, 40608: 26855, 40609: 26837, 40610: 26934, 40611: 26898, 40612: 26884, 40613: 26839, 40614: 26851, 40615: 26917, 40616: 26873, 40617: 26848, 40618: 26863, 40619: 26920, 40620: 26922, 40621: 26906, 40622: 26915, 40623: 26913, 40624: 26822, 40625: 27001, 40626: 26999, 40627: 26972, 40628: 27e3, 40629: 26987, 40630: 26964, 40631: 27006, 40632: 26990, 40633: 26937, 40634: 26996, 40635: 26941, 40636: 26969, 40637: 26928, 40638: 26977, 40639: 26974, 40640: 26973, 40641: 27009, 40642: 26986, 40643: 27058, 40644: 27054, 40645: 27088, 40646: 27071, 40647: 27073, 40648: 27091, 40649: 27070, 40650: 27086, 40651: 23528, 40652: 27082, 40653: 27101, 40654: 27067, 40655: 27075, 40656: 27047, 40657: 27182, 40658: 27025, 40659: 27040, 40660: 27036, 40661: 27029, 40662: 27060, 40663: 27102, 40664: 27112, 40665: 27138, 40666: 27163, 40667: 27135, 40668: 27402, 40669: 27129, 40670: 27122, 40671: 27111, 40672: 27141, 40673: 27057, 40674: 27166, 40675: 27117, 40676: 27156, 40677: 27115, 40678: 27146, 40679: 27154, 40680: 27329, 40681: 27171, 40682: 27155, 40683: 27204, 40684: 27148, 40685: 27250, 40686: 27190, 40687: 27256, 40688: 27207, 40689: 27234, 40690: 27225, 40691: 27238, 40692: 27208, 40693: 27192, 40694: 27170, 40695: 27280, 40696: 27277, 40697: 27296, 40698: 27268, 40699: 27298, 40700: 27299, 40768: 27287, 40769: 34327, 40770: 27323, 40771: 27331, 40772: 27330, 40773: 27320, 40774: 27315, 40775: 27308, 40776: 27358, 40777: 27345, 40778: 27359, 40779: 27306, 40780: 27354, 40781: 27370, 40782: 27387, 40783: 27397, 40784: 34326, 40785: 27386, 40786: 27410, 40787: 27414, 40788: 39729, 40789: 27423, 40790: 27448, 40791: 27447, 40792: 30428, 40793: 27449, 40794: 39150, 40795: 27463, 40796: 27459, 40797: 27465, 40798: 27472, 40799: 27481, 40800: 27476, 40801: 27483, 40802: 27487, 40803: 27489, 40804: 27512, 40805: 27513, 40806: 27519, 40807: 27520, 40808: 27524, 40809: 27523, 40810: 27533, 40811: 27544, 40812: 27541, 40813: 27550, 40814: 27556, 40815: 27562, 40816: 27563, 40817: 27567, 40818: 27570, 40819: 27569, 40820: 27571, 40821: 27575, 40822: 27580, 40823: 27590, 40824: 27595, 40825: 27603, 40826: 27615, 40827: 27628, 40828: 27627, 40829: 27635, 40830: 27631, 40832: 40638, 40833: 27656, 40834: 27667, 40835: 27668, 40836: 27675, 40837: 27684, 40838: 27683, 40839: 27742, 40840: 27733, 40841: 27746, 40842: 27754, 40843: 27778, 40844: 27789, 40845: 27802, 40846: 27777, 40847: 27803, 40848: 27774, 40849: 27752, 40850: 27763, 40851: 27794, 40852: 27792, 40853: 27844, 40854: 27889, 40855: 27859, 40856: 27837, 40857: 27863, 40858: 27845, 40859: 27869, 40860: 27822, 40861: 27825, 40862: 27838, 40863: 27834, 40864: 27867, 40865: 27887, 40866: 27865, 40867: 27882, 40868: 27935, 40869: 34893, 40870: 27958, 40871: 27947, 40872: 27965, 40873: 27960, 40874: 27929, 40875: 27957, 40876: 27955, 40877: 27922, 40878: 27916, 40879: 28003, 40880: 28051, 40881: 28004, 40882: 27994, 40883: 28025, 40884: 27993, 40885: 28046, 40886: 28053, 40887: 28644, 40888: 28037, 40889: 28153, 40890: 28181, 40891: 28170, 40892: 28085, 40893: 28103, 40894: 28134, 40895: 28088, 40896: 28102, 40897: 28140, 40898: 28126, 40899: 28108, 40900: 28136, 40901: 28114, 40902: 28101, 40903: 28154, 40904: 28121, 40905: 28132, 40906: 28117, 40907: 28138, 40908: 28142, 40909: 28205, 40910: 28270, 40911: 28206, 40912: 28185, 40913: 28274, 40914: 28255, 40915: 28222, 40916: 28195, 40917: 28267, 40918: 28203, 40919: 28278, 40920: 28237, 40921: 28191, 40922: 28227, 40923: 28218, 40924: 28238, 40925: 28196, 40926: 28415, 40927: 28189, 40928: 28216, 40929: 28290, 40930: 28330, 40931: 28312, 40932: 28361, 40933: 28343, 40934: 28371, 40935: 28349, 40936: 28335, 40937: 28356, 40938: 28338, 40939: 28372, 40940: 28373, 40941: 28303, 40942: 28325, 40943: 28354, 40944: 28319, 40945: 28481, 40946: 28433, 40947: 28748, 40948: 28396, 40949: 28408, 40950: 28414, 40951: 28479, 40952: 28402, 40953: 28465, 40954: 28399, 40955: 28466, 40956: 28364, 57408: 28478, 57409: 28435, 57410: 28407, 57411: 28550, 57412: 28538, 57413: 28536, 57414: 28545, 57415: 28544, 57416: 28527, 57417: 28507, 57418: 28659, 57419: 28525, 57420: 28546, 57421: 28540, 57422: 28504, 57423: 28558, 57424: 28561, 57425: 28610, 57426: 28518, 57427: 28595, 57428: 28579, 57429: 28577, 57430: 28580, 57431: 28601, 57432: 28614, 57433: 28586, 57434: 28639, 57435: 28629, 57436: 28652, 57437: 28628, 57438: 28632, 57439: 28657, 57440: 28654, 57441: 28635, 57442: 28681, 57443: 28683, 57444: 28666, 57445: 28689, 57446: 28673, 57447: 28687, 57448: 28670, 57449: 28699, 57450: 28698, 57451: 28532, 57452: 28701, 57453: 28696, 57454: 28703, 57455: 28720, 57456: 28734, 57457: 28722, 57458: 28753, 57459: 28771, 57460: 28825, 57461: 28818, 57462: 28847, 57463: 28913, 57464: 28844, 57465: 28856, 57466: 28851, 57467: 28846, 57468: 28895, 57469: 28875, 57470: 28893, 57472: 28889, 57473: 28937, 57474: 28925, 57475: 28956, 57476: 28953, 57477: 29029, 57478: 29013, 57479: 29064, 57480: 29030, 57481: 29026, 57482: 29004, 57483: 29014, 57484: 29036, 57485: 29071, 57486: 29179, 57487: 29060, 57488: 29077, 57489: 29096, 57490: 29100, 57491: 29143, 57492: 29113, 57493: 29118, 57494: 29138, 57495: 29129, 57496: 29140, 57497: 29134, 57498: 29152, 57499: 29164, 57500: 29159, 57501: 29173, 57502: 29180, 57503: 29177, 57504: 29183, 57505: 29197, 57506: 29200, 57507: 29211, 57508: 29224, 57509: 29229, 57510: 29228, 57511: 29232, 57512: 29234, 57513: 29243, 57514: 29244, 57515: 29247, 57516: 29248, 57517: 29254, 57518: 29259, 57519: 29272, 57520: 29300, 57521: 29310, 57522: 29314, 57523: 29313, 57524: 29319, 57525: 29330, 57526: 29334, 57527: 29346, 57528: 29351, 57529: 29369, 57530: 29362, 57531: 29379, 57532: 29382, 57533: 29380, 57534: 29390, 57535: 29394, 57536: 29410, 57537: 29408, 57538: 29409, 57539: 29433, 57540: 29431, 57541: 20495, 57542: 29463, 57543: 29450, 57544: 29468, 57545: 29462, 57546: 29469, 57547: 29492, 57548: 29487, 57549: 29481, 57550: 29477, 57551: 29502, 57552: 29518, 57553: 29519, 57554: 40664, 57555: 29527, 57556: 29546, 57557: 29544, 57558: 29552, 57559: 29560, 57560: 29557, 57561: 29563, 57562: 29562, 57563: 29640, 57564: 29619, 57565: 29646, 57566: 29627, 57567: 29632, 57568: 29669, 57569: 29678, 57570: 29662, 57571: 29858, 57572: 29701, 57573: 29807, 57574: 29733, 57575: 29688, 57576: 29746, 57577: 29754, 57578: 29781, 57579: 29759, 57580: 29791, 57581: 29785, 57582: 29761, 57583: 29788, 57584: 29801, 57585: 29808, 57586: 29795, 57587: 29802, 57588: 29814, 57589: 29822, 57590: 29835, 57591: 29854, 57592: 29863, 57593: 29898, 57594: 29903, 57595: 29908, 57596: 29681, 57664: 29920, 57665: 29923, 57666: 29927, 57667: 29929, 57668: 29934, 57669: 29938, 57670: 29936, 57671: 29937, 57672: 29944, 57673: 29943, 57674: 29956, 57675: 29955, 57676: 29957, 57677: 29964, 57678: 29966, 57679: 29965, 57680: 29973, 57681: 29971, 57682: 29982, 57683: 29990, 57684: 29996, 57685: 30012, 57686: 30020, 57687: 30029, 57688: 30026, 57689: 30025, 57690: 30043, 57691: 30022, 57692: 30042, 57693: 30057, 57694: 30052, 57695: 30055, 57696: 30059, 57697: 30061, 57698: 30072, 57699: 30070, 57700: 30086, 57701: 30087, 57702: 30068, 57703: 30090, 57704: 30089, 57705: 30082, 57706: 30100, 57707: 30106, 57708: 30109, 57709: 30117, 57710: 30115, 57711: 30146, 57712: 30131, 57713: 30147, 57714: 30133, 57715: 30141, 57716: 30136, 57717: 30140, 57718: 30129, 57719: 30157, 57720: 30154, 57721: 30162, 57722: 30169, 57723: 30179, 57724: 30174, 57725: 30206, 57726: 30207, 57728: 30204, 57729: 30209, 57730: 30192, 57731: 30202, 57732: 30194, 57733: 30195, 57734: 30219, 57735: 30221, 57736: 30217, 57737: 30239, 57738: 30247, 57739: 30240, 57740: 30241, 57741: 30242, 57742: 30244, 57743: 30260, 57744: 30256, 57745: 30267, 57746: 30279, 57747: 30280, 57748: 30278, 57749: 30300, 57750: 30296, 57751: 30305, 57752: 30306, 57753: 30312, 57754: 30313, 57755: 30314, 57756: 30311, 57757: 30316, 57758: 30320, 57759: 30322, 57760: 30326, 57761: 30328, 57762: 30332, 57763: 30336, 57764: 30339, 57765: 30344, 57766: 30347, 57767: 30350, 57768: 30358, 57769: 30355, 57770: 30361, 57771: 30362, 57772: 30384, 57773: 30388, 57774: 30392, 57775: 30393, 57776: 30394, 57777: 30402, 57778: 30413, 57779: 30422, 57780: 30418, 57781: 30430, 57782: 30433, 57783: 30437, 57784: 30439, 57785: 30442, 57786: 34351, 57787: 30459, 57788: 30472, 57789: 30471, 57790: 30468, 57791: 30505, 57792: 30500, 57793: 30494, 57794: 30501, 57795: 30502, 57796: 30491, 57797: 30519, 57798: 30520, 57799: 30535, 57800: 30554, 57801: 30568, 57802: 30571, 57803: 30555, 57804: 30565, 57805: 30591, 57806: 30590, 57807: 30585, 57808: 30606, 57809: 30603, 57810: 30609, 57811: 30624, 57812: 30622, 57813: 30640, 57814: 30646, 57815: 30649, 57816: 30655, 57817: 30652, 57818: 30653, 57819: 30651, 57820: 30663, 57821: 30669, 57822: 30679, 57823: 30682, 57824: 30684, 57825: 30691, 57826: 30702, 57827: 30716, 57828: 30732, 57829: 30738, 57830: 31014, 57831: 30752, 57832: 31018, 57833: 30789, 57834: 30862, 57835: 30836, 57836: 30854, 57837: 30844, 57838: 30874, 57839: 30860, 57840: 30883, 57841: 30901, 57842: 30890, 57843: 30895, 57844: 30929, 57845: 30918, 57846: 30923, 57847: 30932, 57848: 30910, 57849: 30908, 57850: 30917, 57851: 30922, 57852: 30956, 57920: 30951, 57921: 30938, 57922: 30973, 57923: 30964, 57924: 30983, 57925: 30994, 57926: 30993, 57927: 31001, 57928: 31020, 57929: 31019, 57930: 31040, 57931: 31072, 57932: 31063, 57933: 31071, 57934: 31066, 57935: 31061, 57936: 31059, 57937: 31098, 57938: 31103, 57939: 31114, 57940: 31133, 57941: 31143, 57942: 40779, 57943: 31146, 57944: 31150, 57945: 31155, 57946: 31161, 57947: 31162, 57948: 31177, 57949: 31189, 57950: 31207, 57951: 31212, 57952: 31201, 57953: 31203, 57954: 31240, 57955: 31245, 57956: 31256, 57957: 31257, 57958: 31264, 57959: 31263, 57960: 31104, 57961: 31281, 57962: 31291, 57963: 31294, 57964: 31287, 57965: 31299, 57966: 31319, 57967: 31305, 57968: 31329, 57969: 31330, 57970: 31337, 57971: 40861, 57972: 31344, 57973: 31353, 57974: 31357, 57975: 31368, 57976: 31383, 57977: 31381, 57978: 31384, 57979: 31382, 57980: 31401, 57981: 31432, 57982: 31408, 57984: 31414, 57985: 31429, 57986: 31428, 57987: 31423, 57988: 36995, 57989: 31431, 57990: 31434, 57991: 31437, 57992: 31439, 57993: 31445, 57994: 31443, 57995: 31449, 57996: 31450, 57997: 31453, 57998: 31457, 57999: 31458, 58e3: 31462, 58001: 31469, 58002: 31472, 58003: 31490, 58004: 31503, 58005: 31498, 58006: 31494, 58007: 31539, 58008: 31512, 58009: 31513, 58010: 31518, 58011: 31541, 58012: 31528, 58013: 31542, 58014: 31568, 58015: 31610, 58016: 31492, 58017: 31565, 58018: 31499, 58019: 31564, 58020: 31557, 58021: 31605, 58022: 31589, 58023: 31604, 58024: 31591, 58025: 31600, 58026: 31601, 58027: 31596, 58028: 31598, 58029: 31645, 58030: 31640, 58031: 31647, 58032: 31629, 58033: 31644, 58034: 31642, 58035: 31627, 58036: 31634, 58037: 31631, 58038: 31581, 58039: 31641, 58040: 31691, 58041: 31681, 58042: 31692, 58043: 31695, 58044: 31668, 58045: 31686, 58046: 31709, 58047: 31721, 58048: 31761, 58049: 31764, 58050: 31718, 58051: 31717, 58052: 31840, 58053: 31744, 58054: 31751, 58055: 31763, 58056: 31731, 58057: 31735, 58058: 31767, 58059: 31757, 58060: 31734, 58061: 31779, 58062: 31783, 58063: 31786, 58064: 31775, 58065: 31799, 58066: 31787, 58067: 31805, 58068: 31820, 58069: 31811, 58070: 31828, 58071: 31823, 58072: 31808, 58073: 31824, 58074: 31832, 58075: 31839, 58076: 31844, 58077: 31830, 58078: 31845, 58079: 31852, 58080: 31861, 58081: 31875, 58082: 31888, 58083: 31908, 58084: 31917, 58085: 31906, 58086: 31915, 58087: 31905, 58088: 31912, 58089: 31923, 58090: 31922, 58091: 31921, 58092: 31918, 58093: 31929, 58094: 31933, 58095: 31936, 58096: 31941, 58097: 31938, 58098: 31960, 58099: 31954, 58100: 31964, 58101: 31970, 58102: 39739, 58103: 31983, 58104: 31986, 58105: 31988, 58106: 31990, 58107: 31994, 58108: 32006, 58176: 32002, 58177: 32028, 58178: 32021, 58179: 32010, 58180: 32069, 58181: 32075, 58182: 32046, 58183: 32050, 58184: 32063, 58185: 32053, 58186: 32070, 58187: 32115, 58188: 32086, 58189: 32078, 58190: 32114, 58191: 32104, 58192: 32110, 58193: 32079, 58194: 32099, 58195: 32147, 58196: 32137, 58197: 32091, 58198: 32143, 58199: 32125, 58200: 32155, 58201: 32186, 58202: 32174, 58203: 32163, 58204: 32181, 58205: 32199, 58206: 32189, 58207: 32171, 58208: 32317, 58209: 32162, 58210: 32175, 58211: 32220, 58212: 32184, 58213: 32159, 58214: 32176, 58215: 32216, 58216: 32221, 58217: 32228, 58218: 32222, 58219: 32251, 58220: 32242, 58221: 32225, 58222: 32261, 58223: 32266, 58224: 32291, 58225: 32289, 58226: 32274, 58227: 32305, 58228: 32287, 58229: 32265, 58230: 32267, 58231: 32290, 58232: 32326, 58233: 32358, 58234: 32315, 58235: 32309, 58236: 32313, 58237: 32323, 58238: 32311, 58240: 32306, 58241: 32314, 58242: 32359, 58243: 32349, 58244: 32342, 58245: 32350, 58246: 32345, 58247: 32346, 58248: 32377, 58249: 32362, 58250: 32361, 58251: 32380, 58252: 32379, 58253: 32387, 58254: 32213, 58255: 32381, 58256: 36782, 58257: 32383, 58258: 32392, 58259: 32393, 58260: 32396, 58261: 32402, 58262: 32400, 58263: 32403, 58264: 32404, 58265: 32406, 58266: 32398, 58267: 32411, 58268: 32412, 58269: 32568, 58270: 32570, 58271: 32581, 58272: 32588, 58273: 32589, 58274: 32590, 58275: 32592, 58276: 32593, 58277: 32597, 58278: 32596, 58279: 32600, 58280: 32607, 58281: 32608, 58282: 32616, 58283: 32617, 58284: 32615, 58285: 32632, 58286: 32642, 58287: 32646, 58288: 32643, 58289: 32648, 58290: 32647, 58291: 32652, 58292: 32660, 58293: 32670, 58294: 32669, 58295: 32666, 58296: 32675, 58297: 32687, 58298: 32690, 58299: 32697, 58300: 32686, 58301: 32694, 58302: 32696, 58303: 35697, 58304: 32709, 58305: 32710, 58306: 32714, 58307: 32725, 58308: 32724, 58309: 32737, 58310: 32742, 58311: 32745, 58312: 32755, 58313: 32761, 58314: 39132, 58315: 32774, 58316: 32772, 58317: 32779, 58318: 32786, 58319: 32792, 58320: 32793, 58321: 32796, 58322: 32801, 58323: 32808, 58324: 32831, 58325: 32827, 58326: 32842, 58327: 32838, 58328: 32850, 58329: 32856, 58330: 32858, 58331: 32863, 58332: 32866, 58333: 32872, 58334: 32883, 58335: 32882, 58336: 32880, 58337: 32886, 58338: 32889, 58339: 32893, 58340: 32895, 58341: 32900, 58342: 32902, 58343: 32901, 58344: 32923, 58345: 32915, 58346: 32922, 58347: 32941, 58348: 20880, 58349: 32940, 58350: 32987, 58351: 32997, 58352: 32985, 58353: 32989, 58354: 32964, 58355: 32986, 58356: 32982, 58357: 33033, 58358: 33007, 58359: 33009, 58360: 33051, 58361: 33065, 58362: 33059, 58363: 33071, 58364: 33099, 58432: 38539, 58433: 33094, 58434: 33086, 58435: 33107, 58436: 33105, 58437: 33020, 58438: 33137, 58439: 33134, 58440: 33125, 58441: 33126, 58442: 33140, 58443: 33155, 58444: 33160, 58445: 33162, 58446: 33152, 58447: 33154, 58448: 33184, 58449: 33173, 58450: 33188, 58451: 33187, 58452: 33119, 58453: 33171, 58454: 33193, 58455: 33200, 58456: 33205, 58457: 33214, 58458: 33208, 58459: 33213, 58460: 33216, 58461: 33218, 58462: 33210, 58463: 33225, 58464: 33229, 58465: 33233, 58466: 33241, 58467: 33240, 58468: 33224, 58469: 33242, 58470: 33247, 58471: 33248, 58472: 33255, 58473: 33274, 58474: 33275, 58475: 33278, 58476: 33281, 58477: 33282, 58478: 33285, 58479: 33287, 58480: 33290, 58481: 33293, 58482: 33296, 58483: 33302, 58484: 33321, 58485: 33323, 58486: 33336, 58487: 33331, 58488: 33344, 58489: 33369, 58490: 33368, 58491: 33373, 58492: 33370, 58493: 33375, 58494: 33380, 58496: 33378, 58497: 33384, 58498: 33386, 58499: 33387, 58500: 33326, 58501: 33393, 58502: 33399, 58503: 33400, 58504: 33406, 58505: 33421, 58506: 33426, 58507: 33451, 58508: 33439, 58509: 33467, 58510: 33452, 58511: 33505, 58512: 33507, 58513: 33503, 58514: 33490, 58515: 33524, 58516: 33523, 58517: 33530, 58518: 33683, 58519: 33539, 58520: 33531, 58521: 33529, 58522: 33502, 58523: 33542, 58524: 33500, 58525: 33545, 58526: 33497, 58527: 33589, 58528: 33588, 58529: 33558, 58530: 33586, 58531: 33585, 58532: 33600, 58533: 33593, 58534: 33616, 58535: 33605, 58536: 33583, 58537: 33579, 58538: 33559, 58539: 33560, 58540: 33669, 58541: 33690, 58542: 33706, 58543: 33695, 58544: 33698, 58545: 33686, 58546: 33571, 58547: 33678, 58548: 33671, 58549: 33674, 58550: 33660, 58551: 33717, 58552: 33651, 58553: 33653, 58554: 33696, 58555: 33673, 58556: 33704, 58557: 33780, 58558: 33811, 58559: 33771, 58560: 33742, 58561: 33789, 58562: 33795, 58563: 33752, 58564: 33803, 58565: 33729, 58566: 33783, 58567: 33799, 58568: 33760, 58569: 33778, 58570: 33805, 58571: 33826, 58572: 33824, 58573: 33725, 58574: 33848, 58575: 34054, 58576: 33787, 58577: 33901, 58578: 33834, 58579: 33852, 58580: 34138, 58581: 33924, 58582: 33911, 58583: 33899, 58584: 33965, 58585: 33902, 58586: 33922, 58587: 33897, 58588: 33862, 58589: 33836, 58590: 33903, 58591: 33913, 58592: 33845, 58593: 33994, 58594: 33890, 58595: 33977, 58596: 33983, 58597: 33951, 58598: 34009, 58599: 33997, 58600: 33979, 58601: 34010, 58602: 34e3, 58603: 33985, 58604: 33990, 58605: 34006, 58606: 33953, 58607: 34081, 58608: 34047, 58609: 34036, 58610: 34071, 58611: 34072, 58612: 34092, 58613: 34079, 58614: 34069, 58615: 34068, 58616: 34044, 58617: 34112, 58618: 34147, 58619: 34136, 58620: 34120, 58688: 34113, 58689: 34306, 58690: 34123, 58691: 34133, 58692: 34176, 58693: 34212, 58694: 34184, 58695: 34193, 58696: 34186, 58697: 34216, 58698: 34157, 58699: 34196, 58700: 34203, 58701: 34282, 58702: 34183, 58703: 34204, 58704: 34167, 58705: 34174, 58706: 34192, 58707: 34249, 58708: 34234, 58709: 34255, 58710: 34233, 58711: 34256, 58712: 34261, 58713: 34269, 58714: 34277, 58715: 34268, 58716: 34297, 58717: 34314, 58718: 34323, 58719: 34315, 58720: 34302, 58721: 34298, 58722: 34310, 58723: 34338, 58724: 34330, 58725: 34352, 58726: 34367, 58727: 34381, 58728: 20053, 58729: 34388, 58730: 34399, 58731: 34407, 58732: 34417, 58733: 34451, 58734: 34467, 58735: 34473, 58736: 34474, 58737: 34443, 58738: 34444, 58739: 34486, 58740: 34479, 58741: 34500, 58742: 34502, 58743: 34480, 58744: 34505, 58745: 34851, 58746: 34475, 58747: 34516, 58748: 34526, 58749: 34537, 58750: 34540, 58752: 34527, 58753: 34523, 58754: 34543, 58755: 34578, 58756: 34566, 58757: 34568, 58758: 34560, 58759: 34563, 58760: 34555, 58761: 34577, 58762: 34569, 58763: 34573, 58764: 34553, 58765: 34570, 58766: 34612, 58767: 34623, 58768: 34615, 58769: 34619, 58770: 34597, 58771: 34601, 58772: 34586, 58773: 34656, 58774: 34655, 58775: 34680, 58776: 34636, 58777: 34638, 58778: 34676, 58779: 34647, 58780: 34664, 58781: 34670, 58782: 34649, 58783: 34643, 58784: 34659, 58785: 34666, 58786: 34821, 58787: 34722, 58788: 34719, 58789: 34690, 58790: 34735, 58791: 34763, 58792: 34749, 58793: 34752, 58794: 34768, 58795: 38614, 58796: 34731, 58797: 34756, 58798: 34739, 58799: 34759, 58800: 34758, 58801: 34747, 58802: 34799, 58803: 34802, 58804: 34784, 58805: 34831, 58806: 34829, 58807: 34814, 58808: 34806, 58809: 34807, 58810: 34830, 58811: 34770, 58812: 34833, 58813: 34838, 58814: 34837, 58815: 34850, 58816: 34849, 58817: 34865, 58818: 34870, 58819: 34873, 58820: 34855, 58821: 34875, 58822: 34884, 58823: 34882, 58824: 34898, 58825: 34905, 58826: 34910, 58827: 34914, 58828: 34923, 58829: 34945, 58830: 34942, 58831: 34974, 58832: 34933, 58833: 34941, 58834: 34997, 58835: 34930, 58836: 34946, 58837: 34967, 58838: 34962, 58839: 34990, 58840: 34969, 58841: 34978, 58842: 34957, 58843: 34980, 58844: 34992, 58845: 35007, 58846: 34993, 58847: 35011, 58848: 35012, 58849: 35028, 58850: 35032, 58851: 35033, 58852: 35037, 58853: 35065, 58854: 35074, 58855: 35068, 58856: 35060, 58857: 35048, 58858: 35058, 58859: 35076, 58860: 35084, 58861: 35082, 58862: 35091, 58863: 35139, 58864: 35102, 58865: 35109, 58866: 35114, 58867: 35115, 58868: 35137, 58869: 35140, 58870: 35131, 58871: 35126, 58872: 35128, 58873: 35148, 58874: 35101, 58875: 35168, 58876: 35166, 58944: 35174, 58945: 35172, 58946: 35181, 58947: 35178, 58948: 35183, 58949: 35188, 58950: 35191, 58951: 35198, 58952: 35203, 58953: 35208, 58954: 35210, 58955: 35219, 58956: 35224, 58957: 35233, 58958: 35241, 58959: 35238, 58960: 35244, 58961: 35247, 58962: 35250, 58963: 35258, 58964: 35261, 58965: 35263, 58966: 35264, 58967: 35290, 58968: 35292, 58969: 35293, 58970: 35303, 58971: 35316, 58972: 35320, 58973: 35331, 58974: 35350, 58975: 35344, 58976: 35340, 58977: 35355, 58978: 35357, 58979: 35365, 58980: 35382, 58981: 35393, 58982: 35419, 58983: 35410, 58984: 35398, 58985: 35400, 58986: 35452, 58987: 35437, 58988: 35436, 58989: 35426, 58990: 35461, 58991: 35458, 58992: 35460, 58993: 35496, 58994: 35489, 58995: 35473, 58996: 35493, 58997: 35494, 58998: 35482, 58999: 35491, 59e3: 35524, 59001: 35533, 59002: 35522, 59003: 35546, 59004: 35563, 59005: 35571, 59006: 35559, 59008: 35556, 59009: 35569, 59010: 35604, 59011: 35552, 59012: 35554, 59013: 35575, 59014: 35550, 59015: 35547, 59016: 35596, 59017: 35591, 59018: 35610, 59019: 35553, 59020: 35606, 59021: 35600, 59022: 35607, 59023: 35616, 59024: 35635, 59025: 38827, 59026: 35622, 59027: 35627, 59028: 35646, 59029: 35624, 59030: 35649, 59031: 35660, 59032: 35663, 59033: 35662, 59034: 35657, 59035: 35670, 59036: 35675, 59037: 35674, 59038: 35691, 59039: 35679, 59040: 35692, 59041: 35695, 59042: 35700, 59043: 35709, 59044: 35712, 59045: 35724, 59046: 35726, 59047: 35730, 59048: 35731, 59049: 35734, 59050: 35737, 59051: 35738, 59052: 35898, 59053: 35905, 59054: 35903, 59055: 35912, 59056: 35916, 59057: 35918, 59058: 35920, 59059: 35925, 59060: 35938, 59061: 35948, 59062: 35960, 59063: 35962, 59064: 35970, 59065: 35977, 59066: 35973, 59067: 35978, 59068: 35981, 59069: 35982, 59070: 35988, 59071: 35964, 59072: 35992, 59073: 25117, 59074: 36013, 59075: 36010, 59076: 36029, 59077: 36018, 59078: 36019, 59079: 36014, 59080: 36022, 59081: 36040, 59082: 36033, 59083: 36068, 59084: 36067, 59085: 36058, 59086: 36093, 59087: 36090, 59088: 36091, 59089: 36100, 59090: 36101, 59091: 36106, 59092: 36103, 59093: 36111, 59094: 36109, 59095: 36112, 59096: 40782, 59097: 36115, 59098: 36045, 59099: 36116, 59100: 36118, 59101: 36199, 59102: 36205, 59103: 36209, 59104: 36211, 59105: 36225, 59106: 36249, 59107: 36290, 59108: 36286, 59109: 36282, 59110: 36303, 59111: 36314, 59112: 36310, 59113: 36300, 59114: 36315, 59115: 36299, 59116: 36330, 59117: 36331, 59118: 36319, 59119: 36323, 59120: 36348, 59121: 36360, 59122: 36361, 59123: 36351, 59124: 36381, 59125: 36382, 59126: 36368, 59127: 36383, 59128: 36418, 59129: 36405, 59130: 36400, 59131: 36404, 59132: 36426, 59200: 36423, 59201: 36425, 59202: 36428, 59203: 36432, 59204: 36424, 59205: 36441, 59206: 36452, 59207: 36448, 59208: 36394, 59209: 36451, 59210: 36437, 59211: 36470, 59212: 36466, 59213: 36476, 59214: 36481, 59215: 36487, 59216: 36485, 59217: 36484, 59218: 36491, 59219: 36490, 59220: 36499, 59221: 36497, 59222: 36500, 59223: 36505, 59224: 36522, 59225: 36513, 59226: 36524, 59227: 36528, 59228: 36550, 59229: 36529, 59230: 36542, 59231: 36549, 59232: 36552, 59233: 36555, 59234: 36571, 59235: 36579, 59236: 36604, 59237: 36603, 59238: 36587, 59239: 36606, 59240: 36618, 59241: 36613, 59242: 36629, 59243: 36626, 59244: 36633, 59245: 36627, 59246: 36636, 59247: 36639, 59248: 36635, 59249: 36620, 59250: 36646, 59251: 36659, 59252: 36667, 59253: 36665, 59254: 36677, 59255: 36674, 59256: 36670, 59257: 36684, 59258: 36681, 59259: 36678, 59260: 36686, 59261: 36695, 59262: 36700, 59264: 36706, 59265: 36707, 59266: 36708, 59267: 36764, 59268: 36767, 59269: 36771, 59270: 36781, 59271: 36783, 59272: 36791, 59273: 36826, 59274: 36837, 59275: 36834, 59276: 36842, 59277: 36847, 59278: 36999, 59279: 36852, 59280: 36869, 59281: 36857, 59282: 36858, 59283: 36881, 59284: 36885, 59285: 36897, 59286: 36877, 59287: 36894, 59288: 36886, 59289: 36875, 59290: 36903, 59291: 36918, 59292: 36917, 59293: 36921, 59294: 36856, 59295: 36943, 59296: 36944, 59297: 36945, 59298: 36946, 59299: 36878, 59300: 36937, 59301: 36926, 59302: 36950, 59303: 36952, 59304: 36958, 59305: 36968, 59306: 36975, 59307: 36982, 59308: 38568, 59309: 36978, 59310: 36994, 59311: 36989, 59312: 36993, 59313: 36992, 59314: 37002, 59315: 37001, 59316: 37007, 59317: 37032, 59318: 37039, 59319: 37041, 59320: 37045, 59321: 37090, 59322: 37092, 59323: 25160, 59324: 37083, 59325: 37122, 59326: 37138, 59327: 37145, 59328: 37170, 59329: 37168, 59330: 37194, 59331: 37206, 59332: 37208, 59333: 37219, 59334: 37221, 59335: 37225, 59336: 37235, 59337: 37234, 59338: 37259, 59339: 37257, 59340: 37250, 59341: 37282, 59342: 37291, 59343: 37295, 59344: 37290, 59345: 37301, 59346: 37300, 59347: 37306, 59348: 37312, 59349: 37313, 59350: 37321, 59351: 37323, 59352: 37328, 59353: 37334, 59354: 37343, 59355: 37345, 59356: 37339, 59357: 37372, 59358: 37365, 59359: 37366, 59360: 37406, 59361: 37375, 59362: 37396, 59363: 37420, 59364: 37397, 59365: 37393, 59366: 37470, 59367: 37463, 59368: 37445, 59369: 37449, 59370: 37476, 59371: 37448, 59372: 37525, 59373: 37439, 59374: 37451, 59375: 37456, 59376: 37532, 59377: 37526, 59378: 37523, 59379: 37531, 59380: 37466, 59381: 37583, 59382: 37561, 59383: 37559, 59384: 37609, 59385: 37647, 59386: 37626, 59387: 37700, 59388: 37678, 59456: 37657, 59457: 37666, 59458: 37658, 59459: 37667, 59460: 37690, 59461: 37685, 59462: 37691, 59463: 37724, 59464: 37728, 59465: 37756, 59466: 37742, 59467: 37718, 59468: 37808, 59469: 37804, 59470: 37805, 59471: 37780, 59472: 37817, 59473: 37846, 59474: 37847, 59475: 37864, 59476: 37861, 59477: 37848, 59478: 37827, 59479: 37853, 59480: 37840, 59481: 37832, 59482: 37860, 59483: 37914, 59484: 37908, 59485: 37907, 59486: 37891, 59487: 37895, 59488: 37904, 59489: 37942, 59490: 37931, 59491: 37941, 59492: 37921, 59493: 37946, 59494: 37953, 59495: 37970, 59496: 37956, 59497: 37979, 59498: 37984, 59499: 37986, 59500: 37982, 59501: 37994, 59502: 37417, 59503: 38e3, 59504: 38005, 59505: 38007, 59506: 38013, 59507: 37978, 59508: 38012, 59509: 38014, 59510: 38017, 59511: 38015, 59512: 38274, 59513: 38279, 59514: 38282, 59515: 38292, 59516: 38294, 59517: 38296, 59518: 38297, 59520: 38304, 59521: 38312, 59522: 38311, 59523: 38317, 59524: 38332, 59525: 38331, 59526: 38329, 59527: 38334, 59528: 38346, 59529: 28662, 59530: 38339, 59531: 38349, 59532: 38348, 59533: 38357, 59534: 38356, 59535: 38358, 59536: 38364, 59537: 38369, 59538: 38373, 59539: 38370, 59540: 38433, 59541: 38440, 59542: 38446, 59543: 38447, 59544: 38466, 59545: 38476, 59546: 38479, 59547: 38475, 59548: 38519, 59549: 38492, 59550: 38494, 59551: 38493, 59552: 38495, 59553: 38502, 59554: 38514, 59555: 38508, 59556: 38541, 59557: 38552, 59558: 38549, 59559: 38551, 59560: 38570, 59561: 38567, 59562: 38577, 59563: 38578, 59564: 38576, 59565: 38580, 59566: 38582, 59567: 38584, 59568: 38585, 59569: 38606, 59570: 38603, 59571: 38601, 59572: 38605, 59573: 35149, 59574: 38620, 59575: 38669, 59576: 38613, 59577: 38649, 59578: 38660, 59579: 38662, 59580: 38664, 59581: 38675, 59582: 38670, 59583: 38673, 59584: 38671, 59585: 38678, 59586: 38681, 59587: 38692, 59588: 38698, 59589: 38704, 59590: 38713, 59591: 38717, 59592: 38718, 59593: 38724, 59594: 38726, 59595: 38728, 59596: 38722, 59597: 38729, 59598: 38748, 59599: 38752, 59600: 38756, 59601: 38758, 59602: 38760, 59603: 21202, 59604: 38763, 59605: 38769, 59606: 38777, 59607: 38789, 59608: 38780, 59609: 38785, 59610: 38778, 59611: 38790, 59612: 38795, 59613: 38799, 59614: 38800, 59615: 38812, 59616: 38824, 59617: 38822, 59618: 38819, 59619: 38835, 59620: 38836, 59621: 38851, 59622: 38854, 59623: 38856, 59624: 38859, 59625: 38876, 59626: 38893, 59627: 40783, 59628: 38898, 59629: 31455, 59630: 38902, 59631: 38901, 59632: 38927, 59633: 38924, 59634: 38968, 59635: 38948, 59636: 38945, 59637: 38967, 59638: 38973, 59639: 38982, 59640: 38991, 59641: 38987, 59642: 39019, 59643: 39023, 59644: 39024, 59712: 39025, 59713: 39028, 59714: 39027, 59715: 39082, 59716: 39087, 59717: 39089, 59718: 39094, 59719: 39108, 59720: 39107, 59721: 39110, 59722: 39145, 59723: 39147, 59724: 39171, 59725: 39177, 59726: 39186, 59727: 39188, 59728: 39192, 59729: 39201, 59730: 39197, 59731: 39198, 59732: 39204, 59733: 39200, 59734: 39212, 59735: 39214, 59736: 39229, 59737: 39230, 59738: 39234, 59739: 39241, 59740: 39237, 59741: 39248, 59742: 39243, 59743: 39249, 59744: 39250, 59745: 39244, 59746: 39253, 59747: 39319, 59748: 39320, 59749: 39333, 59750: 39341, 59751: 39342, 59752: 39356, 59753: 39391, 59754: 39387, 59755: 39389, 59756: 39384, 59757: 39377, 59758: 39405, 59759: 39406, 59760: 39409, 59761: 39410, 59762: 39419, 59763: 39416, 59764: 39425, 59765: 39439, 59766: 39429, 59767: 39394, 59768: 39449, 59769: 39467, 59770: 39479, 59771: 39493, 59772: 39490, 59773: 39488, 59774: 39491, 59776: 39486, 59777: 39509, 59778: 39501, 59779: 39515, 59780: 39511, 59781: 39519, 59782: 39522, 59783: 39525, 59784: 39524, 59785: 39529, 59786: 39531, 59787: 39530, 59788: 39597, 59789: 39600, 59790: 39612, 59791: 39616, 59792: 39631, 59793: 39633, 59794: 39635, 59795: 39636, 59796: 39646, 59797: 39647, 59798: 39650, 59799: 39651, 59800: 39654, 59801: 39663, 59802: 39659, 59803: 39662, 59804: 39668, 59805: 39665, 59806: 39671, 59807: 39675, 59808: 39686, 59809: 39704, 59810: 39706, 59811: 39711, 59812: 39714, 59813: 39715, 59814: 39717, 59815: 39719, 59816: 39720, 59817: 39721, 59818: 39722, 59819: 39726, 59820: 39727, 59821: 39730, 59822: 39748, 59823: 39747, 59824: 39759, 59825: 39757, 59826: 39758, 59827: 39761, 59828: 39768, 59829: 39796, 59830: 39827, 59831: 39811, 59832: 39825, 59833: 39830, 59834: 39831, 59835: 39839, 59836: 39840, 59837: 39848, 59838: 39860, 59839: 39872, 59840: 39882, 59841: 39865, 59842: 39878, 59843: 39887, 59844: 39889, 59845: 39890, 59846: 39907, 59847: 39906, 59848: 39908, 59849: 39892, 59850: 39905, 59851: 39994, 59852: 39922, 59853: 39921, 59854: 39920, 59855: 39957, 59856: 39956, 59857: 39945, 59858: 39955, 59859: 39948, 59860: 39942, 59861: 39944, 59862: 39954, 59863: 39946, 59864: 39940, 59865: 39982, 59866: 39963, 59867: 39973, 59868: 39972, 59869: 39969, 59870: 39984, 59871: 40007, 59872: 39986, 59873: 40006, 59874: 39998, 59875: 40026, 59876: 40032, 59877: 40039, 59878: 40054, 59879: 40056, 59880: 40167, 59881: 40172, 59882: 40176, 59883: 40201, 59884: 40200, 59885: 40171, 59886: 40195, 59887: 40198, 59888: 40234, 59889: 40230, 59890: 40367, 59891: 40227, 59892: 40223, 59893: 40260, 59894: 40213, 59895: 40210, 59896: 40257, 59897: 40255, 59898: 40254, 59899: 40262, 59900: 40264, 59968: 40285, 59969: 40286, 59970: 40292, 59971: 40273, 59972: 40272, 59973: 40281, 59974: 40306, 59975: 40329, 59976: 40327, 59977: 40363, 59978: 40303, 59979: 40314, 59980: 40346, 59981: 40356, 59982: 40361, 59983: 40370, 59984: 40388, 59985: 40385, 59986: 40379, 59987: 40376, 59988: 40378, 59989: 40390, 59990: 40399, 59991: 40386, 59992: 40409, 59993: 40403, 59994: 40440, 59995: 40422, 59996: 40429, 59997: 40431, 59998: 40445, 59999: 40474, 6e4: 40475, 60001: 40478, 60002: 40565, 60003: 40569, 60004: 40573, 60005: 40577, 60006: 40584, 60007: 40587, 60008: 40588, 60009: 40594, 60010: 40597, 60011: 40593, 60012: 40605, 60013: 40613, 60014: 40617, 60015: 40632, 60016: 40618, 60017: 40621, 60018: 38753, 60019: 40652, 60020: 40654, 60021: 40655, 60022: 40656, 60023: 40660, 60024: 40668, 60025: 40670, 60026: 40669, 60027: 40672, 60028: 40677, 60029: 40680, 60030: 40687, 60032: 40692, 60033: 40694, 60034: 40695, 60035: 40697, 60036: 40699, 60037: 40700, 60038: 40701, 60039: 40711, 60040: 40712, 60041: 30391, 60042: 40725, 60043: 40737, 60044: 40748, 60045: 40766, 60046: 40778, 60047: 40786, 60048: 40788, 60049: 40803, 60050: 40799, 60051: 40800, 60052: 40801, 60053: 40806, 60054: 40807, 60055: 40812, 60056: 40810, 60057: 40823, 60058: 40818, 60059: 40822, 60060: 40853, 60061: 40860, 60062: 40864, 60063: 22575, 60064: 27079, 60065: 36953, 60066: 29796, 60067: 20956, 60068: 29081, 60736: 32394, 60737: 35100, 60738: 37704, 60739: 37512, 60740: 34012, 60741: 20425, 60742: 28859, 60743: 26161, 60744: 26824, 60745: 37625, 60746: 26363, 60747: 24389, 60748: 20008, 60749: 20193, 60750: 20220, 60751: 20224, 60752: 20227, 60753: 20281, 60754: 20310, 60755: 20370, 60756: 20362, 60757: 20378, 60758: 20372, 60759: 20429, 60760: 20544, 60761: 20514, 60762: 20479, 60763: 20510, 60764: 20550, 60765: 20592, 60766: 20546, 60767: 20628, 60768: 20724, 60769: 20696, 60770: 20810, 60771: 20836, 60772: 20893, 60773: 20926, 60774: 20972, 60775: 21013, 60776: 21148, 60777: 21158, 60778: 21184, 60779: 21211, 60780: 21248, 60781: 21255, 60782: 21284, 60783: 21362, 60784: 21395, 60785: 21426, 60786: 21469, 60787: 64014, 60788: 21660, 60789: 21642, 60790: 21673, 60791: 21759, 60792: 21894, 60793: 22361, 60794: 22373, 60795: 22444, 60796: 22472, 60797: 22471, 60798: 64015, 60800: 64016, 60801: 22686, 60802: 22706, 60803: 22795, 60804: 22867, 60805: 22875, 60806: 22877, 60807: 22883, 60808: 22948, 60809: 22970, 60810: 23382, 60811: 23488, 60812: 29999, 60813: 23512, 60814: 23532, 60815: 23582, 60816: 23718, 60817: 23738, 60818: 23797, 60819: 23847, 60820: 23891, 60821: 64017, 60822: 23874, 60823: 23917, 60824: 23992, 60825: 23993, 60826: 24016, 60827: 24353, 60828: 24372, 60829: 24423, 60830: 24503, 60831: 24542, 60832: 24669, 60833: 24709, 60834: 24714, 60835: 24798, 60836: 24789, 60837: 24864, 60838: 24818, 60839: 24849, 60840: 24887, 60841: 24880, 60842: 24984, 60843: 25107, 60844: 25254, 60845: 25589, 60846: 25696, 60847: 25757, 60848: 25806, 60849: 25934, 60850: 26112, 60851: 26133, 60852: 26171, 60853: 26121, 60854: 26158, 60855: 26142, 60856: 26148, 60857: 26213, 60858: 26199, 60859: 26201, 60860: 64018, 60861: 26227, 60862: 26265, 60863: 26272, 60864: 26290, 60865: 26303, 60866: 26362, 60867: 26382, 60868: 63785, 60869: 26470, 60870: 26555, 60871: 26706, 60872: 26560, 60873: 26625, 60874: 26692, 60875: 26831, 60876: 64019, 60877: 26984, 60878: 64020, 60879: 27032, 60880: 27106, 60881: 27184, 60882: 27243, 60883: 27206, 60884: 27251, 60885: 27262, 60886: 27362, 60887: 27364, 60888: 27606, 60889: 27711, 60890: 27740, 60891: 27782, 60892: 27759, 60893: 27866, 60894: 27908, 60895: 28039, 60896: 28015, 60897: 28054, 60898: 28076, 60899: 28111, 60900: 28152, 60901: 28146, 60902: 28156, 60903: 28217, 60904: 28252, 60905: 28199, 60906: 28220, 60907: 28351, 60908: 28552, 60909: 28597, 60910: 28661, 60911: 28677, 60912: 28679, 60913: 28712, 60914: 28805, 60915: 28843, 60916: 28943, 60917: 28932, 60918: 29020, 60919: 28998, 60920: 28999, 60921: 64021, 60922: 29121, 60923: 29182, 60924: 29361, 60992: 29374, 60993: 29476, 60994: 64022, 60995: 29559, 60996: 29629, 60997: 29641, 60998: 29654, 60999: 29667, 61e3: 29650, 61001: 29703, 61002: 29685, 61003: 29734, 61004: 29738, 61005: 29737, 61006: 29742, 61007: 29794, 61008: 29833, 61009: 29855, 61010: 29953, 61011: 30063, 61012: 30338, 61013: 30364, 61014: 30366, 61015: 30363, 61016: 30374, 61017: 64023, 61018: 30534, 61019: 21167, 61020: 30753, 61021: 30798, 61022: 30820, 61023: 30842, 61024: 31024, 61025: 64024, 61026: 64025, 61027: 64026, 61028: 31124, 61029: 64027, 61030: 31131, 61031: 31441, 61032: 31463, 61033: 64028, 61034: 31467, 61035: 31646, 61036: 64029, 61037: 32072, 61038: 32092, 61039: 32183, 61040: 32160, 61041: 32214, 61042: 32338, 61043: 32583, 61044: 32673, 61045: 64030, 61046: 33537, 61047: 33634, 61048: 33663, 61049: 33735, 61050: 33782, 61051: 33864, 61052: 33972, 61053: 34131, 61054: 34137, 61056: 34155, 61057: 64031, 61058: 34224, 61059: 64032, 61060: 64033, 61061: 34823, 61062: 35061, 61063: 35346, 61064: 35383, 61065: 35449, 61066: 35495, 61067: 35518, 61068: 35551, 61069: 64034, 61070: 35574, 61071: 35667, 61072: 35711, 61073: 36080, 61074: 36084, 61075: 36114, 61076: 36214, 61077: 64035, 61078: 36559, 61079: 64036, 61080: 64037, 61081: 36967, 61082: 37086, 61083: 64038, 61084: 37141, 61085: 37159, 61086: 37338, 61087: 37335, 61088: 37342, 61089: 37357, 61090: 37358, 61091: 37348, 61092: 37349, 61093: 37382, 61094: 37392, 61095: 37386, 61096: 37434, 61097: 37440, 61098: 37436, 61099: 37454, 61100: 37465, 61101: 37457, 61102: 37433, 61103: 37479, 61104: 37543, 61105: 37495, 61106: 37496, 61107: 37607, 61108: 37591, 61109: 37593, 61110: 37584, 61111: 64039, 61112: 37589, 61113: 37600, 61114: 37587, 61115: 37669, 61116: 37665, 61117: 37627, 61118: 64040, 61119: 37662, 61120: 37631, 61121: 37661, 61122: 37634, 61123: 37744, 61124: 37719, 61125: 37796, 61126: 37830, 61127: 37854, 61128: 37880, 61129: 37937, 61130: 37957, 61131: 37960, 61132: 38290, 61133: 63964, 61134: 64041, 61135: 38557, 61136: 38575, 61137: 38707, 61138: 38715, 61139: 38723, 61140: 38733, 61141: 38735, 61142: 38737, 61143: 38741, 61144: 38999, 61145: 39013, 61146: 64042, 61147: 64043, 61148: 39207, 61149: 64044, 61150: 39326, 61151: 39502, 61152: 39641, 61153: 39644, 61154: 39797, 61155: 39794, 61156: 39823, 61157: 39857, 61158: 39867, 61159: 39936, 61160: 40304, 61161: 40299, 61162: 64045, 61163: 40473, 61164: 40657, 61167: 8560, 61168: 8561, 61169: 8562, 61170: 8563, 61171: 8564, 61172: 8565, 61173: 8566, 61174: 8567, 61175: 8568, 61176: 8569, 61177: 65506, 61178: 65508, 61179: 65287, 61180: 65282, 61504: 57344, 61505: 57345, 61506: 57346, 61507: 57347, 61508: 57348, 61509: 57349, 61510: 57350, 61511: 57351, 61512: 57352, 61513: 57353, 61514: 57354, 61515: 57355, 61516: 57356, 61517: 57357, 61518: 57358, 61519: 57359, 61520: 57360, 61521: 57361, 61522: 57362, 61523: 57363, 61524: 57364, 61525: 57365, 61526: 57366, 61527: 57367, 61528: 57368, 61529: 57369, 61530: 57370, 61531: 57371, 61532: 57372, 61533: 57373, 61534: 57374, 61535: 57375, 61536: 57376, 61537: 57377, 61538: 57378, 61539: 57379, 61540: 57380, 61541: 57381, 61542: 57382, 61543: 57383, 61544: 57384, 61545: 57385, 61546: 57386, 61547: 57387, 61548: 57388, 61549: 57389, 61550: 57390, 61551: 57391, 61552: 57392, 61553: 57393, 61554: 57394, 61555: 57395, 61556: 57396, 61557: 57397, 61558: 57398, 61559: 57399, 61560: 57400, 61561: 57401, 61562: 57402, 61563: 57403, 61564: 57404, 61565: 57405, 61566: 57406, 61568: 57407, 61569: 57408, 61570: 57409, 61571: 57410, 61572: 57411, 61573: 57412, 61574: 57413, 61575: 57414, 61576: 57415, 61577: 57416, 61578: 57417, 61579: 57418, 61580: 57419, 61581: 57420, 61582: 57421, 61583: 57422, 61584: 57423, 61585: 57424, 61586: 57425, 61587: 57426, 61588: 57427, 61589: 57428, 61590: 57429, 61591: 57430, 61592: 57431, 61593: 57432, 61594: 57433, 61595: 57434, 61596: 57435, 61597: 57436, 61598: 57437, 61599: 57438, 61600: 57439, 61601: 57440, 61602: 57441, 61603: 57442, 61604: 57443, 61605: 57444, 61606: 57445, 61607: 57446, 61608: 57447, 61609: 57448, 61610: 57449, 61611: 57450, 61612: 57451, 61613: 57452, 61614: 57453, 61615: 57454, 61616: 57455, 61617: 57456, 61618: 57457, 61619: 57458, 61620: 57459, 61621: 57460, 61622: 57461, 61623: 57462, 61624: 57463, 61625: 57464, 61626: 57465, 61627: 57466, 61628: 57467, 61629: 57468, 61630: 57469, 61631: 57470, 61632: 57471, 61633: 57472, 61634: 57473, 61635: 57474, 61636: 57475, 61637: 57476, 61638: 57477, 61639: 57478, 61640: 57479, 61641: 57480, 61642: 57481, 61643: 57482, 61644: 57483, 61645: 57484, 61646: 57485, 61647: 57486, 61648: 57487, 61649: 57488, 61650: 57489, 61651: 57490, 61652: 57491, 61653: 57492, 61654: 57493, 61655: 57494, 61656: 57495, 61657: 57496, 61658: 57497, 61659: 57498, 61660: 57499, 61661: 57500, 61662: 57501, 61663: 57502, 61664: 57503, 61665: 57504, 61666: 57505, 61667: 57506, 61668: 57507, 61669: 57508, 61670: 57509, 61671: 57510, 61672: 57511, 61673: 57512, 61674: 57513, 61675: 57514, 61676: 57515, 61677: 57516, 61678: 57517, 61679: 57518, 61680: 57519, 61681: 57520, 61682: 57521, 61683: 57522, 61684: 57523, 61685: 57524, 61686: 57525, 61687: 57526, 61688: 57527, 61689: 57528, 61690: 57529, 61691: 57530, 61692: 57531, 61760: 57532, 61761: 57533, 61762: 57534, 61763: 57535, 61764: 57536, 61765: 57537, 61766: 57538, 61767: 57539, 61768: 57540, 61769: 57541, 61770: 57542, 61771: 57543, 61772: 57544, 61773: 57545, 61774: 57546, 61775: 57547, 61776: 57548, 61777: 57549, 61778: 57550, 61779: 57551, 61780: 57552, 61781: 57553, 61782: 57554, 61783: 57555, 61784: 57556, 61785: 57557, 61786: 57558, 61787: 57559, 61788: 57560, 61789: 57561, 61790: 57562, 61791: 57563, 61792: 57564, 61793: 57565, 61794: 57566, 61795: 57567, 61796: 57568, 61797: 57569, 61798: 57570, 61799: 57571, 61800: 57572, 61801: 57573, 61802: 57574, 61803: 57575, 61804: 57576, 61805: 57577, 61806: 57578, 61807: 57579, 61808: 57580, 61809: 57581, 61810: 57582, 61811: 57583, 61812: 57584, 61813: 57585, 61814: 57586, 61815: 57587, 61816: 57588, 61817: 57589, 61818: 57590, 61819: 57591, 61820: 57592, 61821: 57593, 61822: 57594, 61824: 57595, 61825: 57596, 61826: 57597, 61827: 57598, 61828: 57599, 61829: 57600, 61830: 57601, 61831: 57602, 61832: 57603, 61833: 57604, 61834: 57605, 61835: 57606, 61836: 57607, 61837: 57608, 61838: 57609, 61839: 57610, 61840: 57611, 61841: 57612, 61842: 57613, 61843: 57614, 61844: 57615, 61845: 57616, 61846: 57617, 61847: 57618, 61848: 57619, 61849: 57620, 61850: 57621, 61851: 57622, 61852: 57623, 61853: 57624, 61854: 57625, 61855: 57626, 61856: 57627, 61857: 57628, 61858: 57629, 61859: 57630, 61860: 57631, 61861: 57632, 61862: 57633, 61863: 57634, 61864: 57635, 61865: 57636, 61866: 57637, 61867: 57638, 61868: 57639, 61869: 57640, 61870: 57641, 61871: 57642, 61872: 57643, 61873: 57644, 61874: 57645, 61875: 57646, 61876: 57647, 61877: 57648, 61878: 57649, 61879: 57650, 61880: 57651, 61881: 57652, 61882: 57653, 61883: 57654, 61884: 57655, 61885: 57656, 61886: 57657, 61887: 57658, 61888: 57659, 61889: 57660, 61890: 57661, 61891: 57662, 61892: 57663, 61893: 57664, 61894: 57665, 61895: 57666, 61896: 57667, 61897: 57668, 61898: 57669, 61899: 57670, 61900: 57671, 61901: 57672, 61902: 57673, 61903: 57674, 61904: 57675, 61905: 57676, 61906: 57677, 61907: 57678, 61908: 57679, 61909: 57680, 61910: 57681, 61911: 57682, 61912: 57683, 61913: 57684, 61914: 57685, 61915: 57686, 61916: 57687, 61917: 57688, 61918: 57689, 61919: 57690, 61920: 57691, 61921: 57692, 61922: 57693, 61923: 57694, 61924: 57695, 61925: 57696, 61926: 57697, 61927: 57698, 61928: 57699, 61929: 57700, 61930: 57701, 61931: 57702, 61932: 57703, 61933: 57704, 61934: 57705, 61935: 57706, 61936: 57707, 61937: 57708, 61938: 57709, 61939: 57710, 61940: 57711, 61941: 57712, 61942: 57713, 61943: 57714, 61944: 57715, 61945: 57716, 61946: 57717, 61947: 57718, 61948: 57719, 62016: 57720, 62017: 57721, 62018: 57722, 62019: 57723, 62020: 57724, 62021: 57725, 62022: 57726, 62023: 57727, 62024: 57728, 62025: 57729, 62026: 57730, 62027: 57731, 62028: 57732, 62029: 57733, 62030: 57734, 62031: 57735, 62032: 57736, 62033: 57737, 62034: 57738, 62035: 57739, 62036: 57740, 62037: 57741, 62038: 57742, 62039: 57743, 62040: 57744, 62041: 57745, 62042: 57746, 62043: 57747, 62044: 57748, 62045: 57749, 62046: 57750, 62047: 57751, 62048: 57752, 62049: 57753, 62050: 57754, 62051: 57755, 62052: 57756, 62053: 57757, 62054: 57758, 62055: 57759, 62056: 57760, 62057: 57761, 62058: 57762, 62059: 57763, 62060: 57764, 62061: 57765, 62062: 57766, 62063: 57767, 62064: 57768, 62065: 57769, 62066: 57770, 62067: 57771, 62068: 57772, 62069: 57773, 62070: 57774, 62071: 57775, 62072: 57776, 62073: 57777, 62074: 57778, 62075: 57779, 62076: 57780, 62077: 57781, 62078: 57782, 62080: 57783, 62081: 57784, 62082: 57785, 62083: 57786, 62084: 57787, 62085: 57788, 62086: 57789, 62087: 57790, 62088: 57791, 62089: 57792, 62090: 57793, 62091: 57794, 62092: 57795, 62093: 57796, 62094: 57797, 62095: 57798, 62096: 57799, 62097: 57800, 62098: 57801, 62099: 57802, 62100: 57803, 62101: 57804, 62102: 57805, 62103: 57806, 62104: 57807, 62105: 57808, 62106: 57809, 62107: 57810, 62108: 57811, 62109: 57812, 62110: 57813, 62111: 57814, 62112: 57815, 62113: 57816, 62114: 57817, 62115: 57818, 62116: 57819, 62117: 57820, 62118: 57821, 62119: 57822, 62120: 57823, 62121: 57824, 62122: 57825, 62123: 57826, 62124: 57827, 62125: 57828, 62126: 57829, 62127: 57830, 62128: 57831, 62129: 57832, 62130: 57833, 62131: 57834, 62132: 57835, 62133: 57836, 62134: 57837, 62135: 57838, 62136: 57839, 62137: 57840, 62138: 57841, 62139: 57842, 62140: 57843, 62141: 57844, 62142: 57845, 62143: 57846, 62144: 57847, 62145: 57848, 62146: 57849, 62147: 57850, 62148: 57851, 62149: 57852, 62150: 57853, 62151: 57854, 62152: 57855, 62153: 57856, 62154: 57857, 62155: 57858, 62156: 57859, 62157: 57860, 62158: 57861, 62159: 57862, 62160: 57863, 62161: 57864, 62162: 57865, 62163: 57866, 62164: 57867, 62165: 57868, 62166: 57869, 62167: 57870, 62168: 57871, 62169: 57872, 62170: 57873, 62171: 57874, 62172: 57875, 62173: 57876, 62174: 57877, 62175: 57878, 62176: 57879, 62177: 57880, 62178: 57881, 62179: 57882, 62180: 57883, 62181: 57884, 62182: 57885, 62183: 57886, 62184: 57887, 62185: 57888, 62186: 57889, 62187: 57890, 62188: 57891, 62189: 57892, 62190: 57893, 62191: 57894, 62192: 57895, 62193: 57896, 62194: 57897, 62195: 57898, 62196: 57899, 62197: 57900, 62198: 57901, 62199: 57902, 62200: 57903, 62201: 57904, 62202: 57905, 62203: 57906, 62204: 57907, 62272: 57908, 62273: 57909, 62274: 57910, 62275: 57911, 62276: 57912, 62277: 57913, 62278: 57914, 62279: 57915, 62280: 57916, 62281: 57917, 62282: 57918, 62283: 57919, 62284: 57920, 62285: 57921, 62286: 57922, 62287: 57923, 62288: 57924, 62289: 57925, 62290: 57926, 62291: 57927, 62292: 57928, 62293: 57929, 62294: 57930, 62295: 57931, 62296: 57932, 62297: 57933, 62298: 57934, 62299: 57935, 62300: 57936, 62301: 57937, 62302: 57938, 62303: 57939, 62304: 57940, 62305: 57941, 62306: 57942, 62307: 57943, 62308: 57944, 62309: 57945, 62310: 57946, 62311: 57947, 62312: 57948, 62313: 57949, 62314: 57950, 62315: 57951, 62316: 57952, 62317: 57953, 62318: 57954, 62319: 57955, 62320: 57956, 62321: 57957, 62322: 57958, 62323: 57959, 62324: 57960, 62325: 57961, 62326: 57962, 62327: 57963, 62328: 57964, 62329: 57965, 62330: 57966, 62331: 57967, 62332: 57968, 62333: 57969, 62334: 57970, 62336: 57971, 62337: 57972, 62338: 57973, 62339: 57974, 62340: 57975, 62341: 57976, 62342: 57977, 62343: 57978, 62344: 57979, 62345: 57980, 62346: 57981, 62347: 57982, 62348: 57983, 62349: 57984, 62350: 57985, 62351: 57986, 62352: 57987, 62353: 57988, 62354: 57989, 62355: 57990, 62356: 57991, 62357: 57992, 62358: 57993, 62359: 57994, 62360: 57995, 62361: 57996, 62362: 57997, 62363: 57998, 62364: 57999, 62365: 58e3, 62366: 58001, 62367: 58002, 62368: 58003, 62369: 58004, 62370: 58005, 62371: 58006, 62372: 58007, 62373: 58008, 62374: 58009, 62375: 58010, 62376: 58011, 62377: 58012, 62378: 58013, 62379: 58014, 62380: 58015, 62381: 58016, 62382: 58017, 62383: 58018, 62384: 58019, 62385: 58020, 62386: 58021, 62387: 58022, 62388: 58023, 62389: 58024, 62390: 58025, 62391: 58026, 62392: 58027, 62393: 58028, 62394: 58029, 62395: 58030, 62396: 58031, 62397: 58032, 62398: 58033, 62399: 58034, 62400: 58035, 62401: 58036, 62402: 58037, 62403: 58038, 62404: 58039, 62405: 58040, 62406: 58041, 62407: 58042, 62408: 58043, 62409: 58044, 62410: 58045, 62411: 58046, 62412: 58047, 62413: 58048, 62414: 58049, 62415: 58050, 62416: 58051, 62417: 58052, 62418: 58053, 62419: 58054, 62420: 58055, 62421: 58056, 62422: 58057, 62423: 58058, 62424: 58059, 62425: 58060, 62426: 58061, 62427: 58062, 62428: 58063, 62429: 58064, 62430: 58065, 62431: 58066, 62432: 58067, 62433: 58068, 62434: 58069, 62435: 58070, 62436: 58071, 62437: 58072, 62438: 58073, 62439: 58074, 62440: 58075, 62441: 58076, 62442: 58077, 62443: 58078, 62444: 58079, 62445: 58080, 62446: 58081, 62447: 58082, 62448: 58083, 62449: 58084, 62450: 58085, 62451: 58086, 62452: 58087, 62453: 58088, 62454: 58089, 62455: 58090, 62456: 58091, 62457: 58092, 62458: 58093, 62459: 58094, 62460: 58095, 62528: 58096, 62529: 58097, 62530: 58098, 62531: 58099, 62532: 58100, 62533: 58101, 62534: 58102, 62535: 58103, 62536: 58104, 62537: 58105, 62538: 58106, 62539: 58107, 62540: 58108, 62541: 58109, 62542: 58110, 62543: 58111, 62544: 58112, 62545: 58113, 62546: 58114, 62547: 58115, 62548: 58116, 62549: 58117, 62550: 58118, 62551: 58119, 62552: 58120, 62553: 58121, 62554: 58122, 62555: 58123, 62556: 58124, 62557: 58125, 62558: 58126, 62559: 58127, 62560: 58128, 62561: 58129, 62562: 58130, 62563: 58131, 62564: 58132, 62565: 58133, 62566: 58134, 62567: 58135, 62568: 58136, 62569: 58137, 62570: 58138, 62571: 58139, 62572: 58140, 62573: 58141, 62574: 58142, 62575: 58143, 62576: 58144, 62577: 58145, 62578: 58146, 62579: 58147, 62580: 58148, 62581: 58149, 62582: 58150, 62583: 58151, 62584: 58152, 62585: 58153, 62586: 58154, 62587: 58155, 62588: 58156, 62589: 58157, 62590: 58158, 62592: 58159, 62593: 58160, 62594: 58161, 62595: 58162, 62596: 58163, 62597: 58164, 62598: 58165, 62599: 58166, 62600: 58167, 62601: 58168, 62602: 58169, 62603: 58170, 62604: 58171, 62605: 58172, 62606: 58173, 62607: 58174, 62608: 58175, 62609: 58176, 62610: 58177, 62611: 58178, 62612: 58179, 62613: 58180, 62614: 58181, 62615: 58182, 62616: 58183, 62617: 58184, 62618: 58185, 62619: 58186, 62620: 58187, 62621: 58188, 62622: 58189, 62623: 58190, 62624: 58191, 62625: 58192, 62626: 58193, 62627: 58194, 62628: 58195, 62629: 58196, 62630: 58197, 62631: 58198, 62632: 58199, 62633: 58200, 62634: 58201, 62635: 58202, 62636: 58203, 62637: 58204, 62638: 58205, 62639: 58206, 62640: 58207, 62641: 58208, 62642: 58209, 62643: 58210, 62644: 58211, 62645: 58212, 62646: 58213, 62647: 58214, 62648: 58215, 62649: 58216, 62650: 58217, 62651: 58218, 62652: 58219, 62653: 58220, 62654: 58221, 62655: 58222, 62656: 58223, 62657: 58224, 62658: 58225, 62659: 58226, 62660: 58227, 62661: 58228, 62662: 58229, 62663: 58230, 62664: 58231, 62665: 58232, 62666: 58233, 62667: 58234, 62668: 58235, 62669: 58236, 62670: 58237, 62671: 58238, 62672: 58239, 62673: 58240, 62674: 58241, 62675: 58242, 62676: 58243, 62677: 58244, 62678: 58245, 62679: 58246, 62680: 58247, 62681: 58248, 62682: 58249, 62683: 58250, 62684: 58251, 62685: 58252, 62686: 58253, 62687: 58254, 62688: 58255, 62689: 58256, 62690: 58257, 62691: 58258, 62692: 58259, 62693: 58260, 62694: 58261, 62695: 58262, 62696: 58263, 62697: 58264, 62698: 58265, 62699: 58266, 62700: 58267, 62701: 58268, 62702: 58269, 62703: 58270, 62704: 58271, 62705: 58272, 62706: 58273, 62707: 58274, 62708: 58275, 62709: 58276, 62710: 58277, 62711: 58278, 62712: 58279, 62713: 58280, 62714: 58281, 62715: 58282, 62716: 58283, 62784: 58284, 62785: 58285, 62786: 58286, 62787: 58287, 62788: 58288, 62789: 58289, 62790: 58290, 62791: 58291, 62792: 58292, 62793: 58293, 62794: 58294, 62795: 58295, 62796: 58296, 62797: 58297, 62798: 58298, 62799: 58299, 62800: 58300, 62801: 58301, 62802: 58302, 62803: 58303, 62804: 58304, 62805: 58305, 62806: 58306, 62807: 58307, 62808: 58308, 62809: 58309, 62810: 58310, 62811: 58311, 62812: 58312, 62813: 58313, 62814: 58314, 62815: 58315, 62816: 58316, 62817: 58317, 62818: 58318, 62819: 58319, 62820: 58320, 62821: 58321, 62822: 58322, 62823: 58323, 62824: 58324, 62825: 58325, 62826: 58326, 62827: 58327, 62828: 58328, 62829: 58329, 62830: 58330, 62831: 58331, 62832: 58332, 62833: 58333, 62834: 58334, 62835: 58335, 62836: 58336, 62837: 58337, 62838: 58338, 62839: 58339, 62840: 58340, 62841: 58341, 62842: 58342, 62843: 58343, 62844: 58344, 62845: 58345, 62846: 58346, 62848: 58347, 62849: 58348, 62850: 58349, 62851: 58350, 62852: 58351, 62853: 58352, 62854: 58353, 62855: 58354, 62856: 58355, 62857: 58356, 62858: 58357, 62859: 58358, 62860: 58359, 62861: 58360, 62862: 58361, 62863: 58362, 62864: 58363, 62865: 58364, 62866: 58365, 62867: 58366, 62868: 58367, 62869: 58368, 62870: 58369, 62871: 58370, 62872: 58371, 62873: 58372, 62874: 58373, 62875: 58374, 62876: 58375, 62877: 58376, 62878: 58377, 62879: 58378, 62880: 58379, 62881: 58380, 62882: 58381, 62883: 58382, 62884: 58383, 62885: 58384, 62886: 58385, 62887: 58386, 62888: 58387, 62889: 58388, 62890: 58389, 62891: 58390, 62892: 58391, 62893: 58392, 62894: 58393, 62895: 58394, 62896: 58395, 62897: 58396, 62898: 58397, 62899: 58398, 62900: 58399, 62901: 58400, 62902: 58401, 62903: 58402, 62904: 58403, 62905: 58404, 62906: 58405, 62907: 58406, 62908: 58407, 62909: 58408, 62910: 58409, 62911: 58410, 62912: 58411, 62913: 58412, 62914: 58413, 62915: 58414, 62916: 58415, 62917: 58416, 62918: 58417, 62919: 58418, 62920: 58419, 62921: 58420, 62922: 58421, 62923: 58422, 62924: 58423, 62925: 58424, 62926: 58425, 62927: 58426, 62928: 58427, 62929: 58428, 62930: 58429, 62931: 58430, 62932: 58431, 62933: 58432, 62934: 58433, 62935: 58434, 62936: 58435, 62937: 58436, 62938: 58437, 62939: 58438, 62940: 58439, 62941: 58440, 62942: 58441, 62943: 58442, 62944: 58443, 62945: 58444, 62946: 58445, 62947: 58446, 62948: 58447, 62949: 58448, 62950: 58449, 62951: 58450, 62952: 58451, 62953: 58452, 62954: 58453, 62955: 58454, 62956: 58455, 62957: 58456, 62958: 58457, 62959: 58458, 62960: 58459, 62961: 58460, 62962: 58461, 62963: 58462, 62964: 58463, 62965: 58464, 62966: 58465, 62967: 58466, 62968: 58467, 62969: 58468, 62970: 58469, 62971: 58470, 62972: 58471, 63040: 58472, 63041: 58473, 63042: 58474, 63043: 58475, 63044: 58476, 63045: 58477, 63046: 58478, 63047: 58479, 63048: 58480, 63049: 58481, 63050: 58482, 63051: 58483, 63052: 58484, 63053: 58485, 63054: 58486, 63055: 58487, 63056: 58488, 63057: 58489, 63058: 58490, 63059: 58491, 63060: 58492, 63061: 58493, 63062: 58494, 63063: 58495, 63064: 58496, 63065: 58497, 63066: 58498, 63067: 58499, 63068: 58500, 63069: 58501, 63070: 58502, 63071: 58503, 63072: 58504, 63073: 58505, 63074: 58506, 63075: 58507, 63076: 58508, 63077: 58509, 63078: 58510, 63079: 58511, 63080: 58512, 63081: 58513, 63082: 58514, 63083: 58515, 63084: 58516, 63085: 58517, 63086: 58518, 63087: 58519, 63088: 58520, 63089: 58521, 63090: 58522, 63091: 58523, 63092: 58524, 63093: 58525, 63094: 58526, 63095: 58527, 63096: 58528, 63097: 58529, 63098: 58530, 63099: 58531, 63100: 58532, 63101: 58533, 63102: 58534, 63104: 58535, 63105: 58536, 63106: 58537, 63107: 58538, 63108: 58539, 63109: 58540, 63110: 58541, 63111: 58542, 63112: 58543, 63113: 58544, 63114: 58545, 63115: 58546, 63116: 58547, 63117: 58548, 63118: 58549, 63119: 58550, 63120: 58551, 63121: 58552, 63122: 58553, 63123: 58554, 63124: 58555, 63125: 58556, 63126: 58557, 63127: 58558, 63128: 58559, 63129: 58560, 63130: 58561, 63131: 58562, 63132: 58563, 63133: 58564, 63134: 58565, 63135: 58566, 63136: 58567, 63137: 58568, 63138: 58569, 63139: 58570, 63140: 58571, 63141: 58572, 63142: 58573, 63143: 58574, 63144: 58575, 63145: 58576, 63146: 58577, 63147: 58578, 63148: 58579, 63149: 58580, 63150: 58581, 63151: 58582, 63152: 58583, 63153: 58584, 63154: 58585, 63155: 58586, 63156: 58587, 63157: 58588, 63158: 58589, 63159: 58590, 63160: 58591, 63161: 58592, 63162: 58593, 63163: 58594, 63164: 58595, 63165: 58596, 63166: 58597, 63167: 58598, 63168: 58599, 63169: 58600, 63170: 58601, 63171: 58602, 63172: 58603, 63173: 58604, 63174: 58605, 63175: 58606, 63176: 58607, 63177: 58608, 63178: 58609, 63179: 58610, 63180: 58611, 63181: 58612, 63182: 58613, 63183: 58614, 63184: 58615, 63185: 58616, 63186: 58617, 63187: 58618, 63188: 58619, 63189: 58620, 63190: 58621, 63191: 58622, 63192: 58623, 63193: 58624, 63194: 58625, 63195: 58626, 63196: 58627, 63197: 58628, 63198: 58629, 63199: 58630, 63200: 58631, 63201: 58632, 63202: 58633, 63203: 58634, 63204: 58635, 63205: 58636, 63206: 58637, 63207: 58638, 63208: 58639, 63209: 58640, 63210: 58641, 63211: 58642, 63212: 58643, 63213: 58644, 63214: 58645, 63215: 58646, 63216: 58647, 63217: 58648, 63218: 58649, 63219: 58650, 63220: 58651, 63221: 58652, 63222: 58653, 63223: 58654, 63224: 58655, 63225: 58656, 63226: 58657, 63227: 58658, 63228: 58659, 63296: 58660, 63297: 58661, 63298: 58662, 63299: 58663, 63300: 58664, 63301: 58665, 63302: 58666, 63303: 58667, 63304: 58668, 63305: 58669, 63306: 58670, 63307: 58671, 63308: 58672, 63309: 58673, 63310: 58674, 63311: 58675, 63312: 58676, 63313: 58677, 63314: 58678, 63315: 58679, 63316: 58680, 63317: 58681, 63318: 58682, 63319: 58683, 63320: 58684, 63321: 58685, 63322: 58686, 63323: 58687, 63324: 58688, 63325: 58689, 63326: 58690, 63327: 58691, 63328: 58692, 63329: 58693, 63330: 58694, 63331: 58695, 63332: 58696, 63333: 58697, 63334: 58698, 63335: 58699, 63336: 58700, 63337: 58701, 63338: 58702, 63339: 58703, 63340: 58704, 63341: 58705, 63342: 58706, 63343: 58707, 63344: 58708, 63345: 58709, 63346: 58710, 63347: 58711, 63348: 58712, 63349: 58713, 63350: 58714, 63351: 58715, 63352: 58716, 63353: 58717, 63354: 58718, 63355: 58719, 63356: 58720, 63357: 58721, 63358: 58722, 63360: 58723, 63361: 58724, 63362: 58725, 63363: 58726, 63364: 58727, 63365: 58728, 63366: 58729, 63367: 58730, 63368: 58731, 63369: 58732, 63370: 58733, 63371: 58734, 63372: 58735, 63373: 58736, 63374: 58737, 63375: 58738, 63376: 58739, 63377: 58740, 63378: 58741, 63379: 58742, 63380: 58743, 63381: 58744, 63382: 58745, 63383: 58746, 63384: 58747, 63385: 58748, 63386: 58749, 63387: 58750, 63388: 58751, 63389: 58752, 63390: 58753, 63391: 58754, 63392: 58755, 63393: 58756, 63394: 58757, 63395: 58758, 63396: 58759, 63397: 58760, 63398: 58761, 63399: 58762, 63400: 58763, 63401: 58764, 63402: 58765, 63403: 58766, 63404: 58767, 63405: 58768, 63406: 58769, 63407: 58770, 63408: 58771, 63409: 58772, 63410: 58773, 63411: 58774, 63412: 58775, 63413: 58776, 63414: 58777, 63415: 58778, 63416: 58779, 63417: 58780, 63418: 58781, 63419: 58782, 63420: 58783, 63421: 58784, 63422: 58785, 63423: 58786, 63424: 58787, 63425: 58788, 63426: 58789, 63427: 58790, 63428: 58791, 63429: 58792, 63430: 58793, 63431: 58794, 63432: 58795, 63433: 58796, 63434: 58797, 63435: 58798, 63436: 58799, 63437: 58800, 63438: 58801, 63439: 58802, 63440: 58803, 63441: 58804, 63442: 58805, 63443: 58806, 63444: 58807, 63445: 58808, 63446: 58809, 63447: 58810, 63448: 58811, 63449: 58812, 63450: 58813, 63451: 58814, 63452: 58815, 63453: 58816, 63454: 58817, 63455: 58818, 63456: 58819, 63457: 58820, 63458: 58821, 63459: 58822, 63460: 58823, 63461: 58824, 63462: 58825, 63463: 58826, 63464: 58827, 63465: 58828, 63466: 58829, 63467: 58830, 63468: 58831, 63469: 58832, 63470: 58833, 63471: 58834, 63472: 58835, 63473: 58836, 63474: 58837, 63475: 58838, 63476: 58839, 63477: 58840, 63478: 58841, 63479: 58842, 63480: 58843, 63481: 58844, 63482: 58845, 63483: 58846, 63484: 58847, 63552: 58848, 63553: 58849, 63554: 58850, 63555: 58851, 63556: 58852, 63557: 58853, 63558: 58854, 63559: 58855, 63560: 58856, 63561: 58857, 63562: 58858, 63563: 58859, 63564: 58860, 63565: 58861, 63566: 58862, 63567: 58863, 63568: 58864, 63569: 58865, 63570: 58866, 63571: 58867, 63572: 58868, 63573: 58869, 63574: 58870, 63575: 58871, 63576: 58872, 63577: 58873, 63578: 58874, 63579: 58875, 63580: 58876, 63581: 58877, 63582: 58878, 63583: 58879, 63584: 58880, 63585: 58881, 63586: 58882, 63587: 58883, 63588: 58884, 63589: 58885, 63590: 58886, 63591: 58887, 63592: 58888, 63593: 58889, 63594: 58890, 63595: 58891, 63596: 58892, 63597: 58893, 63598: 58894, 63599: 58895, 63600: 58896, 63601: 58897, 63602: 58898, 63603: 58899, 63604: 58900, 63605: 58901, 63606: 58902, 63607: 58903, 63608: 58904, 63609: 58905, 63610: 58906, 63611: 58907, 63612: 58908, 63613: 58909, 63614: 58910, 63616: 58911, 63617: 58912, 63618: 58913, 63619: 58914, 63620: 58915, 63621: 58916, 63622: 58917, 63623: 58918, 63624: 58919, 63625: 58920, 63626: 58921, 63627: 58922, 63628: 58923, 63629: 58924, 63630: 58925, 63631: 58926, 63632: 58927, 63633: 58928, 63634: 58929, 63635: 58930, 63636: 58931, 63637: 58932, 63638: 58933, 63639: 58934, 63640: 58935, 63641: 58936, 63642: 58937, 63643: 58938, 63644: 58939, 63645: 58940, 63646: 58941, 63647: 58942, 63648: 58943, 63649: 58944, 63650: 58945, 63651: 58946, 63652: 58947, 63653: 58948, 63654: 58949, 63655: 58950, 63656: 58951, 63657: 58952, 63658: 58953, 63659: 58954, 63660: 58955, 63661: 58956, 63662: 58957, 63663: 58958, 63664: 58959, 63665: 58960, 63666: 58961, 63667: 58962, 63668: 58963, 63669: 58964, 63670: 58965, 63671: 58966, 63672: 58967, 63673: 58968, 63674: 58969, 63675: 58970, 63676: 58971, 63677: 58972, 63678: 58973, 63679: 58974, 63680: 58975, 63681: 58976, 63682: 58977, 63683: 58978, 63684: 58979, 63685: 58980, 63686: 58981, 63687: 58982, 63688: 58983, 63689: 58984, 63690: 58985, 63691: 58986, 63692: 58987, 63693: 58988, 63694: 58989, 63695: 58990, 63696: 58991, 63697: 58992, 63698: 58993, 63699: 58994, 63700: 58995, 63701: 58996, 63702: 58997, 63703: 58998, 63704: 58999, 63705: 59e3, 63706: 59001, 63707: 59002, 63708: 59003, 63709: 59004, 63710: 59005, 63711: 59006, 63712: 59007, 63713: 59008, 63714: 59009, 63715: 59010, 63716: 59011, 63717: 59012, 63718: 59013, 63719: 59014, 63720: 59015, 63721: 59016, 63722: 59017, 63723: 59018, 63724: 59019, 63725: 59020, 63726: 59021, 63727: 59022, 63728: 59023, 63729: 59024, 63730: 59025, 63731: 59026, 63732: 59027, 63733: 59028, 63734: 59029, 63735: 59030, 63736: 59031, 63737: 59032, 63738: 59033, 63739: 59034, 63740: 59035, 64064: 8560, 64065: 8561, 64066: 8562, 64067: 8563, 64068: 8564, 64069: 8565, 64070: 8566, 64071: 8567, 64072: 8568, 64073: 8569, 64074: 8544, 64075: 8545, 64076: 8546, 64077: 8547, 64078: 8548, 64079: 8549, 64080: 8550, 64081: 8551, 64082: 8552, 64083: 8553, 64084: 65506, 64085: 65508, 64086: 65287, 64087: 65282, 64088: 12849, 64089: 8470, 64090: 8481, 64091: 8757, 64092: 32394, 64093: 35100, 64094: 37704, 64095: 37512, 64096: 34012, 64097: 20425, 64098: 28859, 64099: 26161, 64100: 26824, 64101: 37625, 64102: 26363, 64103: 24389, 64104: 20008, 64105: 20193, 64106: 20220, 64107: 20224, 64108: 20227, 64109: 20281, 64110: 20310, 64111: 20370, 64112: 20362, 64113: 20378, 64114: 20372, 64115: 20429, 64116: 20544, 64117: 20514, 64118: 20479, 64119: 20510, 64120: 20550, 64121: 20592, 64122: 20546, 64123: 20628, 64124: 20724, 64125: 20696, 64126: 20810, 64128: 20836, 64129: 20893, 64130: 20926, 64131: 20972, 64132: 21013, 64133: 21148, 64134: 21158, 64135: 21184, 64136: 21211, 64137: 21248, 64138: 21255, 64139: 21284, 64140: 21362, 64141: 21395, 64142: 21426, 64143: 21469, 64144: 64014, 64145: 21660, 64146: 21642, 64147: 21673, 64148: 21759, 64149: 21894, 64150: 22361, 64151: 22373, 64152: 22444, 64153: 22472, 64154: 22471, 64155: 64015, 64156: 64016, 64157: 22686, 64158: 22706, 64159: 22795, 64160: 22867, 64161: 22875, 64162: 22877, 64163: 22883, 64164: 22948, 64165: 22970, 64166: 23382, 64167: 23488, 64168: 29999, 64169: 23512, 64170: 23532, 64171: 23582, 64172: 23718, 64173: 23738, 64174: 23797, 64175: 23847, 64176: 23891, 64177: 64017, 64178: 23874, 64179: 23917, 64180: 23992, 64181: 23993, 64182: 24016, 64183: 24353, 64184: 24372, 64185: 24423, 64186: 24503, 64187: 24542, 64188: 24669, 64189: 24709, 64190: 24714, 64191: 24798, 64192: 24789, 64193: 24864, 64194: 24818, 64195: 24849, 64196: 24887, 64197: 24880, 64198: 24984, 64199: 25107, 64200: 25254, 64201: 25589, 64202: 25696, 64203: 25757, 64204: 25806, 64205: 25934, 64206: 26112, 64207: 26133, 64208: 26171, 64209: 26121, 64210: 26158, 64211: 26142, 64212: 26148, 64213: 26213, 64214: 26199, 64215: 26201, 64216: 64018, 64217: 26227, 64218: 26265, 64219: 26272, 64220: 26290, 64221: 26303, 64222: 26362, 64223: 26382, 64224: 63785, 64225: 26470, 64226: 26555, 64227: 26706, 64228: 26560, 64229: 26625, 64230: 26692, 64231: 26831, 64232: 64019, 64233: 26984, 64234: 64020, 64235: 27032, 64236: 27106, 64237: 27184, 64238: 27243, 64239: 27206, 64240: 27251, 64241: 27262, 64242: 27362, 64243: 27364, 64244: 27606, 64245: 27711, 64246: 27740, 64247: 27782, 64248: 27759, 64249: 27866, 64250: 27908, 64251: 28039, 64252: 28015, 64320: 28054, 64321: 28076, 64322: 28111, 64323: 28152, 64324: 28146, 64325: 28156, 64326: 28217, 64327: 28252, 64328: 28199, 64329: 28220, 64330: 28351, 64331: 28552, 64332: 28597, 64333: 28661, 64334: 28677, 64335: 28679, 64336: 28712, 64337: 28805, 64338: 28843, 64339: 28943, 64340: 28932, 64341: 29020, 64342: 28998, 64343: 28999, 64344: 64021, 64345: 29121, 64346: 29182, 64347: 29361, 64348: 29374, 64349: 29476, 64350: 64022, 64351: 29559, 64352: 29629, 64353: 29641, 64354: 29654, 64355: 29667, 64356: 29650, 64357: 29703, 64358: 29685, 64359: 29734, 64360: 29738, 64361: 29737, 64362: 29742, 64363: 29794, 64364: 29833, 64365: 29855, 64366: 29953, 64367: 30063, 64368: 30338, 64369: 30364, 64370: 30366, 64371: 30363, 64372: 30374, 64373: 64023, 64374: 30534, 64375: 21167, 64376: 30753, 64377: 30798, 64378: 30820, 64379: 30842, 64380: 31024, 64381: 64024, 64382: 64025, 64384: 64026, 64385: 31124, 64386: 64027, 64387: 31131, 64388: 31441, 64389: 31463, 64390: 64028, 64391: 31467, 64392: 31646, 64393: 64029, 64394: 32072, 64395: 32092, 64396: 32183, 64397: 32160, 64398: 32214, 64399: 32338, 64400: 32583, 64401: 32673, 64402: 64030, 64403: 33537, 64404: 33634, 64405: 33663, 64406: 33735, 64407: 33782, 64408: 33864, 64409: 33972, 64410: 34131, 64411: 34137, 64412: 34155, 64413: 64031, 64414: 34224, 64415: 64032, 64416: 64033, 64417: 34823, 64418: 35061, 64419: 35346, 64420: 35383, 64421: 35449, 64422: 35495, 64423: 35518, 64424: 35551, 64425: 64034, 64426: 35574, 64427: 35667, 64428: 35711, 64429: 36080, 64430: 36084, 64431: 36114, 64432: 36214, 64433: 64035, 64434: 36559, 64435: 64036, 64436: 64037, 64437: 36967, 64438: 37086, 64439: 64038, 64440: 37141, 64441: 37159, 64442: 37338, 64443: 37335, 64444: 37342, 64445: 37357, 64446: 37358, 64447: 37348, 64448: 37349, 64449: 37382, 64450: 37392, 64451: 37386, 64452: 37434, 64453: 37440, 64454: 37436, 64455: 37454, 64456: 37465, 64457: 37457, 64458: 37433, 64459: 37479, 64460: 37543, 64461: 37495, 64462: 37496, 64463: 37607, 64464: 37591, 64465: 37593, 64466: 37584, 64467: 64039, 64468: 37589, 64469: 37600, 64470: 37587, 64471: 37669, 64472: 37665, 64473: 37627, 64474: 64040, 64475: 37662, 64476: 37631, 64477: 37661, 64478: 37634, 64479: 37744, 64480: 37719, 64481: 37796, 64482: 37830, 64483: 37854, 64484: 37880, 64485: 37937, 64486: 37957, 64487: 37960, 64488: 38290, 64489: 63964, 64490: 64041, 64491: 38557, 64492: 38575, 64493: 38707, 64494: 38715, 64495: 38723, 64496: 38733, 64497: 38735, 64498: 38737, 64499: 38741, 64500: 38999, 64501: 39013, 64502: 64042, 64503: 64043, 64504: 39207, 64505: 64044, 64506: 39326, 64507: 39502, 64508: 39641, 64576: 39644, 64577: 39797, 64578: 39794, 64579: 39823, 64580: 39857, 64581: 39867, 64582: 39936, 64583: 40304, 64584: 40299, 64585: 64045, 64586: 40473, 64587: 40657 }; } s2u(uint8Array) { var t = this.s2uTable; var str = ""; var p = 0; while (p < uint8Array.length) { var key = uint8Array[p++]; if (!(key >= 0 && key <= 126 || key >= 161 && key <= 223) && p < uint8Array.length) key = key << 8 | uint8Array[p++]; if (t[key] === void 0) { console.error("unknown char code " + key + "."); return str; } str += String.fromCharCode(t[key]); } return str; } }; var DataViewEx = class { constructor(buffer, littleEndian) { this.dv = new DataView(buffer); this.offset = 0; this.littleEndian = littleEndian !== void 0 ? littleEndian : true; this.encoder = new CharsetEncoder(); } getInt8() { var value = this.dv.getInt8(this.offset); this.offset += 1; return value; } getInt8Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getInt8()); return a; } getUint8() { var value = this.dv.getUint8(this.offset); this.offset += 1; return value; } getUint8Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getUint8()); return a; } getInt16() { var value = this.dv.getInt16(this.offset, this.littleEndian); this.offset += 2; return value; } getInt16Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getInt16()); return a; } getUint16() { var value = this.dv.getUint16(this.offset, this.littleEndian); this.offset += 2; return value; } getUint16Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getUint16()); return a; } getInt32() { var value = this.dv.getInt32(this.offset, this.littleEndian); this.offset += 4; return value; } getInt32Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getInt32()); return a; } getUint32() { var value = this.dv.getUint32(this.offset, this.littleEndian); this.offset += 4; return value; } getUint32Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getUint32()); return a; } getFloat32() { var value = this.dv.getFloat32(this.offset, this.littleEndian); this.offset += 4; return value; } getFloat32Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getFloat32()); return a; } getFloat64() { var value = this.dv.getFloat64(this.offset, this.littleEndian); this.offset += 8; return value; } getFloat64Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getFloat64()); return a; } getIndex(type, isUnsigned) { switch (type) { case 1: return isUnsigned === true ? this.getUint8() : this.getInt8(); case 2: return isUnsigned === true ? this.getUint16() : this.getInt16(); case 4: return this.getInt32(); default: throw "unknown number type " + type + " exception."; } } getIndexArray(type, size, isUnsigned) { var a = []; for (var i = 0; i < size; i++) a.push(this.getIndex(type, isUnsigned)); return a; } getChars(size) { var str = ""; while (size > 0) { var value = this.getUint8(); size--; if (value === 0) break; str += String.fromCharCode(value); } while (size > 0) { this.getUint8(); size--; } return str; } getSjisStringsAsUnicode(size) { var a = []; while (size > 0) { var value = this.getUint8(); size--; if (value === 0) break; a.push(value); } while (size > 0) { this.getUint8(); size--; } return this.encoder.s2u(new Uint8Array(a)); } getUnicodeStrings(size) { var str = ""; while (size > 0) { var value = this.getUint16(); size -= 2; if (value === 0) break; str += String.fromCharCode(value); } while (size > 0) { this.getUint8(); size--; } return str; } getTextBuffer() { var size = this.getUint32(); return this.getUnicodeStrings(size); } }; var DataCreationHelper = class { leftToRightVector3(v) { v[2] = -v[2]; } leftToRightQuaternion(q) { q[0] = -q[0]; q[1] = -q[1]; } leftToRightEuler(r) { r[0] = -r[0]; r[1] = -r[1]; } leftToRightIndexOrder(p) { var tmp = p[2]; p[2] = p[0]; p[0] = tmp; } leftToRightVector3Range(v1, v2) { var tmp = -v2[2]; v2[2] = -v1[2]; v1[2] = tmp; } leftToRightEulerRange(r1, r2) { var tmp1 = -r2[0]; var tmp2 = -r2[1]; r2[0] = -r1[0]; r2[1] = -r1[1]; r1[0] = tmp1; r1[1] = tmp2; } }; var Parser = class { constructor() {} parsePmd(buffer, leftToRight) { var pmd = {}; var dv = new DataViewEx(buffer); pmd.metadata = {}; pmd.metadata.format = "pmd"; pmd.metadata.coordinateSystem = "left"; var parseHeader = function() { var metadata = pmd.metadata; metadata.magic = dv.getChars(3); if (metadata.magic !== "Pmd") throw "PMD file magic is not Pmd, but " + metadata.magic; metadata.version = dv.getFloat32(); metadata.modelName = dv.getSjisStringsAsUnicode(20); metadata.comment = dv.getSjisStringsAsUnicode(256); }; var parseVertices = function() { var parseVertex = function() { var p = {}; p.position = dv.getFloat32Array(3); p.normal = dv.getFloat32Array(3); p.uv = dv.getFloat32Array(2); p.skinIndices = dv.getUint16Array(2); p.skinWeights = [dv.getUint8() / 100]; p.skinWeights.push(1 - p.skinWeights[0]); p.edgeFlag = dv.getUint8(); return p; }; var metadata = pmd.metadata; metadata.vertexCount = dv.getUint32(); pmd.vertices = []; for (var i = 0; i < metadata.vertexCount; i++) pmd.vertices.push(parseVertex()); }; var parseFaces = function() { var parseFace = function() { var p = {}; p.indices = dv.getUint16Array(3); return p; }; var metadata = pmd.metadata; metadata.faceCount = dv.getUint32() / 3; pmd.faces = []; for (var i = 0; i < metadata.faceCount; i++) pmd.faces.push(parseFace()); }; var parseMaterials = function() { var parseMaterial = function() { var p = {}; p.diffuse = dv.getFloat32Array(4); p.shininess = dv.getFloat32(); p.specular = dv.getFloat32Array(3); p.ambient = dv.getFloat32Array(3); p.toonIndex = dv.getInt8(); p.edgeFlag = dv.getUint8(); p.faceCount = dv.getUint32() / 3; p.fileName = dv.getSjisStringsAsUnicode(20); return p; }; var metadata = pmd.metadata; metadata.materialCount = dv.getUint32(); pmd.materials = []; for (var i = 0; i < metadata.materialCount; i++) pmd.materials.push(parseMaterial()); }; var parseBones = function() { var parseBone = function() { var p = {}; p.name = dv.getSjisStringsAsUnicode(20); p.parentIndex = dv.getInt16(); p.tailIndex = dv.getInt16(); p.type = dv.getUint8(); p.ikIndex = dv.getInt16(); p.position = dv.getFloat32Array(3); return p; }; var metadata = pmd.metadata; metadata.boneCount = dv.getUint16(); pmd.bones = []; for (var i = 0; i < metadata.boneCount; i++) pmd.bones.push(parseBone()); }; var parseIks = function() { var parseIk = function() { var p = {}; p.target = dv.getUint16(); p.effector = dv.getUint16(); p.linkCount = dv.getUint8(); p.iteration = dv.getUint16(); p.maxAngle = dv.getFloat32(); p.links = []; for (var i2 = 0; i2 < p.linkCount; i2++) { var link = {}; link.index = dv.getUint16(); p.links.push(link); } return p; }; var metadata = pmd.metadata; metadata.ikCount = dv.getUint16(); pmd.iks = []; for (var i = 0; i < metadata.ikCount; i++) pmd.iks.push(parseIk()); }; var parseMorphs = function() { var parseMorph = function() { var p = {}; p.name = dv.getSjisStringsAsUnicode(20); p.elementCount = dv.getUint32(); p.type = dv.getUint8(); p.elements = []; for (var i2 = 0; i2 < p.elementCount; i2++) p.elements.push({ index: dv.getUint32(), position: dv.getFloat32Array(3) }); return p; }; var metadata = pmd.metadata; metadata.morphCount = dv.getUint16(); pmd.morphs = []; for (var i = 0; i < metadata.morphCount; i++) pmd.morphs.push(parseMorph()); }; var parseMorphFrames = function() { var parseMorphFrame = function() { var p = {}; p.index = dv.getUint16(); return p; }; var metadata = pmd.metadata; metadata.morphFrameCount = dv.getUint8(); pmd.morphFrames = []; for (var i = 0; i < metadata.morphFrameCount; i++) pmd.morphFrames.push(parseMorphFrame()); }; var parseBoneFrameNames = function() { var parseBoneFrameName = function() { var p = {}; p.name = dv.getSjisStringsAsUnicode(50); return p; }; var metadata = pmd.metadata; metadata.boneFrameNameCount = dv.getUint8(); pmd.boneFrameNames = []; for (var i = 0; i < metadata.boneFrameNameCount; i++) pmd.boneFrameNames.push(parseBoneFrameName()); }; var parseBoneFrames = function() { var parseBoneFrame = function() { var p = {}; p.boneIndex = dv.getInt16(); p.frameIndex = dv.getUint8(); return p; }; var metadata = pmd.metadata; metadata.boneFrameCount = dv.getUint32(); pmd.boneFrames = []; for (var i = 0; i < metadata.boneFrameCount; i++) pmd.boneFrames.push(parseBoneFrame()); }; var parseEnglishHeader = function() { var metadata = pmd.metadata; metadata.englishCompatibility = dv.getUint8(); if (metadata.englishCompatibility > 0) { metadata.englishModelName = dv.getSjisStringsAsUnicode(20); metadata.englishComment = dv.getSjisStringsAsUnicode(256); } }; var parseEnglishBoneNames = function() { var parseEnglishBoneName = function() { var p = {}; p.name = dv.getSjisStringsAsUnicode(20); return p; }; var metadata = pmd.metadata; if (metadata.englishCompatibility === 0) return; pmd.englishBoneNames = []; for (var i = 0; i < metadata.boneCount; i++) pmd.englishBoneNames.push(parseEnglishBoneName()); }; var parseEnglishMorphNames = function() { var parseEnglishMorphName = function() { var p = {}; p.name = dv.getSjisStringsAsUnicode(20); return p; }; var metadata = pmd.metadata; if (metadata.englishCompatibility === 0) return; pmd.englishMorphNames = []; for (var i = 0; i < metadata.morphCount - 1; i++) pmd.englishMorphNames.push(parseEnglishMorphName()); }; var parseEnglishBoneFrameNames = function() { var parseEnglishBoneFrameName = function() { var p = {}; p.name = dv.getSjisStringsAsUnicode(50); return p; }; var metadata = pmd.metadata; if (metadata.englishCompatibility === 0) return; pmd.englishBoneFrameNames = []; for (var i = 0; i < metadata.boneFrameNameCount; i++) pmd.englishBoneFrameNames.push(parseEnglishBoneFrameName()); }; var parseToonTextures = function() { var parseToonTexture = function() { var p = {}; p.fileName = dv.getSjisStringsAsUnicode(100); return p; }; pmd.toonTextures = []; for (var i = 0; i < 10; i++) pmd.toonTextures.push(parseToonTexture()); }; var parseRigidBodies = function() { var parseRigidBody = function() { var p = {}; p.name = dv.getSjisStringsAsUnicode(20); p.boneIndex = dv.getInt16(); p.groupIndex = dv.getUint8(); p.groupTarget = dv.getUint16(); p.shapeType = dv.getUint8(); p.width = dv.getFloat32(); p.height = dv.getFloat32(); p.depth = dv.getFloat32(); p.position = dv.getFloat32Array(3); p.rotation = dv.getFloat32Array(3); p.weight = dv.getFloat32(); p.positionDamping = dv.getFloat32(); p.rotationDamping = dv.getFloat32(); p.restitution = dv.getFloat32(); p.friction = dv.getFloat32(); p.type = dv.getUint8(); return p; }; var metadata = pmd.metadata; metadata.rigidBodyCount = dv.getUint32(); pmd.rigidBodies = []; for (var i = 0; i < metadata.rigidBodyCount; i++) pmd.rigidBodies.push(parseRigidBody()); }; var parseConstraints = function() { var parseConstraint = function() { var p = {}; p.name = dv.getSjisStringsAsUnicode(20); p.rigidBodyIndex1 = dv.getUint32(); p.rigidBodyIndex2 = dv.getUint32(); p.position = dv.getFloat32Array(3); p.rotation = dv.getFloat32Array(3); p.translationLimitation1 = dv.getFloat32Array(3); p.translationLimitation2 = dv.getFloat32Array(3); p.rotationLimitation1 = dv.getFloat32Array(3); p.rotationLimitation2 = dv.getFloat32Array(3); p.springPosition = dv.getFloat32Array(3); p.springRotation = dv.getFloat32Array(3); return p; }; var metadata = pmd.metadata; metadata.constraintCount = dv.getUint32(); pmd.constraints = []; for (var i = 0; i < metadata.constraintCount; i++) pmd.constraints.push(parseConstraint()); }; parseHeader(); parseVertices(); parseFaces(); parseMaterials(); parseBones(); parseIks(); parseMorphs(); parseMorphFrames(); parseBoneFrameNames(); parseBoneFrames(); parseEnglishHeader(); parseEnglishBoneNames(); parseEnglishMorphNames(); parseEnglishBoneFrameNames(); parseToonTextures(); parseRigidBodies(); parseConstraints(); if (leftToRight === true) this.leftToRightModel(pmd); return pmd; } parsePmx(buffer, leftToRight) { var pmx = {}; var dv = new DataViewEx(buffer); pmx.metadata = {}; pmx.metadata.format = "pmx"; pmx.metadata.coordinateSystem = "left"; var parseHeader = function() { var metadata = pmx.metadata; metadata.magic = dv.getChars(4); if (metadata.magic !== "PMX ") throw "PMX file magic is not PMX , but " + metadata.magic; metadata.version = dv.getFloat32(); if (metadata.version !== 2 && metadata.version !== 2.1) throw "PMX version " + metadata.version + " is not supported."; metadata.headerSize = dv.getUint8(); metadata.encoding = dv.getUint8(); metadata.additionalUvNum = dv.getUint8(); metadata.vertexIndexSize = dv.getUint8(); metadata.textureIndexSize = dv.getUint8(); metadata.materialIndexSize = dv.getUint8(); metadata.boneIndexSize = dv.getUint8(); metadata.morphIndexSize = dv.getUint8(); metadata.rigidBodyIndexSize = dv.getUint8(); metadata.modelName = dv.getTextBuffer(); metadata.englishModelName = dv.getTextBuffer(); metadata.comment = dv.getTextBuffer(); metadata.englishComment = dv.getTextBuffer(); }; var parseVertices = function() { var parseVertex = function() { var p = {}; p.position = dv.getFloat32Array(3); p.normal = dv.getFloat32Array(3); p.uv = dv.getFloat32Array(2); p.auvs = []; for (var i2 = 0; i2 < pmx.metadata.additionalUvNum; i2++) p.auvs.push(dv.getFloat32Array(4)); p.type = dv.getUint8(); var indexSize = metadata.boneIndexSize; if (p.type === 0) { p.skinIndices = dv.getIndexArray(indexSize, 1); p.skinWeights = [1]; } else if (p.type === 1) { p.skinIndices = dv.getIndexArray(indexSize, 2); p.skinWeights = dv.getFloat32Array(1); p.skinWeights.push(1 - p.skinWeights[0]); } else if (p.type === 2) { p.skinIndices = dv.getIndexArray(indexSize, 4); p.skinWeights = dv.getFloat32Array(4); } else if (p.type === 3) { p.skinIndices = dv.getIndexArray(indexSize, 2); p.skinWeights = dv.getFloat32Array(1); p.skinWeights.push(1 - p.skinWeights[0]); p.skinC = dv.getFloat32Array(3); p.skinR0 = dv.getFloat32Array(3); p.skinR1 = dv.getFloat32Array(3); p.type = 1; } else throw "unsupport bone type " + p.type + " exception."; p.edgeRatio = dv.getFloat32(); return p; }; var metadata = pmx.metadata; metadata.vertexCount = dv.getUint32(); pmx.vertices = []; for (var i = 0; i < metadata.vertexCount; i++) pmx.vertices.push(parseVertex()); }; var parseFaces = function() { var parseFace = function() { var p = {}; p.indices = dv.getIndexArray(metadata.vertexIndexSize, 3, true); return p; }; var metadata = pmx.metadata; metadata.faceCount = dv.getUint32() / 3; pmx.faces = []; for (var i = 0; i < metadata.faceCount; i++) pmx.faces.push(parseFace()); }; var parseTextures = function() { var parseTexture = function() { return dv.getTextBuffer(); }; var metadata = pmx.metadata; metadata.textureCount = dv.getUint32(); pmx.textures = []; for (var i = 0; i < metadata.textureCount; i++) pmx.textures.push(parseTexture()); }; var parseMaterials = function() { var parseMaterial = function() { var p = {}; p.name = dv.getTextBuffer(); p.englishName = dv.getTextBuffer(); p.diffuse = dv.getFloat32Array(4); p.specular = dv.getFloat32Array(3); p.shininess = dv.getFloat32(); p.ambient = dv.getFloat32Array(3); p.flag = dv.getUint8(); p.edgeColor = dv.getFloat32Array(4); p.edgeSize = dv.getFloat32(); p.textureIndex = dv.getIndex(pmx.metadata.textureIndexSize); p.envTextureIndex = dv.getIndex(pmx.metadata.textureIndexSize); p.envFlag = dv.getUint8(); p.toonFlag = dv.getUint8(); if (p.toonFlag === 0) p.toonIndex = dv.getIndex(pmx.metadata.textureIndexSize); else if (p.toonFlag === 1) p.toonIndex = dv.getInt8(); else throw "unknown toon flag " + p.toonFlag + " exception."; p.comment = dv.getTextBuffer(); p.faceCount = dv.getUint32() / 3; return p; }; var metadata = pmx.metadata; metadata.materialCount = dv.getUint32(); pmx.materials = []; for (var i = 0; i < metadata.materialCount; i++) pmx.materials.push(parseMaterial()); }; var parseBones = function() { var parseBone = function() { var p = {}; p.name = dv.getTextBuffer(); p.englishName = dv.getTextBuffer(); p.position = dv.getFloat32Array(3); p.parentIndex = dv.getIndex(pmx.metadata.boneIndexSize); p.transformationClass = dv.getUint32(); p.flag = dv.getUint16(); if (p.flag & 1) p.connectIndex = dv.getIndex(pmx.metadata.boneIndexSize); else p.offsetPosition = dv.getFloat32Array(3); if (p.flag & 256 || p.flag & 512) { var grant = {}; grant.isLocal = (p.flag & 128) !== 0 ? true : false; grant.affectRotation = (p.flag & 256) !== 0 ? true : false; grant.affectPosition = (p.flag & 512) !== 0 ? true : false; grant.parentIndex = dv.getIndex(pmx.metadata.boneIndexSize); grant.ratio = dv.getFloat32(); p.grant = grant; } if (p.flag & 1024) p.fixAxis = dv.getFloat32Array(3); if (p.flag & 2048) { p.localXVector = dv.getFloat32Array(3); p.localZVector = dv.getFloat32Array(3); } if (p.flag & 8192) p.key = dv.getUint32(); if (p.flag & 32) { var ik = {}; ik.effector = dv.getIndex(pmx.metadata.boneIndexSize); ik.target = null; ik.iteration = dv.getUint32(); ik.maxAngle = dv.getFloat32(); ik.linkCount = dv.getUint32(); ik.links = []; for (var i2 = 0; i2 < ik.linkCount; i2++) { var link = {}; link.index = dv.getIndex(pmx.metadata.boneIndexSize); link.angleLimitation = dv.getUint8(); if (link.angleLimitation === 1) { link.lowerLimitationAngle = dv.getFloat32Array(3); link.upperLimitationAngle = dv.getFloat32Array(3); } ik.links.push(link); } p.ik = ik; } return p; }; var metadata = pmx.metadata; metadata.boneCount = dv.getUint32(); pmx.bones = []; for (var i = 0; i < metadata.boneCount; i++) pmx.bones.push(parseBone()); }; var parseMorphs = function() { var parseMorph = function() { var p = {}; p.name = dv.getTextBuffer(); p.englishName = dv.getTextBuffer(); p.panel = dv.getUint8(); p.type = dv.getUint8(); p.elementCount = dv.getUint32(); p.elements = []; for (var i2 = 0; i2 < p.elementCount; i2++) if (p.type === 0) { var m = {}; m.index = dv.getIndex(pmx.metadata.morphIndexSize); m.ratio = dv.getFloat32(); p.elements.push(m); } else if (p.type === 1) { var m = {}; m.index = dv.getIndex(pmx.metadata.vertexIndexSize, true); m.position = dv.getFloat32Array(3); p.elements.push(m); } else if (p.type === 2) { var m = {}; m.index = dv.getIndex(pmx.metadata.boneIndexSize); m.position = dv.getFloat32Array(3); m.rotation = dv.getFloat32Array(4); p.elements.push(m); } else if (p.type === 3) { var m = {}; m.index = dv.getIndex(pmx.metadata.vertexIndexSize, true); m.uv = dv.getFloat32Array(4); p.elements.push(m); } else if (p.type === 4); else if (p.type === 5); else if (p.type === 6); else if (p.type === 7); else if (p.type === 8) { var m = {}; m.index = dv.getIndex(pmx.metadata.materialIndexSize); m.type = dv.getUint8(); m.diffuse = dv.getFloat32Array(4); m.specular = dv.getFloat32Array(3); m.shininess = dv.getFloat32(); m.ambient = dv.getFloat32Array(3); m.edgeColor = dv.getFloat32Array(4); m.edgeSize = dv.getFloat32(); m.textureColor = dv.getFloat32Array(4); m.sphereTextureColor = dv.getFloat32Array(4); m.toonColor = dv.getFloat32Array(4); p.elements.push(m); } return p; }; var metadata = pmx.metadata; metadata.morphCount = dv.getUint32(); pmx.morphs = []; for (var i = 0; i < metadata.morphCount; i++) pmx.morphs.push(parseMorph()); }; var parseFrames = function() { var parseFrame = function() { var p = {}; p.name = dv.getTextBuffer(); p.englishName = dv.getTextBuffer(); p.type = dv.getUint8(); p.elementCount = dv.getUint32(); p.elements = []; for (var i2 = 0; i2 < p.elementCount; i2++) { var e = {}; e.target = dv.getUint8(); e.index = e.target === 0 ? dv.getIndex(pmx.metadata.boneIndexSize) : dv.getIndex(pmx.metadata.morphIndexSize); p.elements.push(e); } return p; }; var metadata = pmx.metadata; metadata.frameCount = dv.getUint32(); pmx.frames = []; for (var i = 0; i < metadata.frameCount; i++) pmx.frames.push(parseFrame()); }; var parseRigidBodies = function() { var parseRigidBody = function() { var p = {}; p.name = dv.getTextBuffer(); p.englishName = dv.getTextBuffer(); p.boneIndex = dv.getIndex(pmx.metadata.boneIndexSize); p.groupIndex = dv.getUint8(); p.groupTarget = dv.getUint16(); p.shapeType = dv.getUint8(); p.width = dv.getFloat32(); p.height = dv.getFloat32(); p.depth = dv.getFloat32(); p.position = dv.getFloat32Array(3); p.rotation = dv.getFloat32Array(3); p.weight = dv.getFloat32(); p.positionDamping = dv.getFloat32(); p.rotationDamping = dv.getFloat32(); p.restitution = dv.getFloat32(); p.friction = dv.getFloat32(); p.type = dv.getUint8(); return p; }; var metadata = pmx.metadata; metadata.rigidBodyCount = dv.getUint32(); pmx.rigidBodies = []; for (var i = 0; i < metadata.rigidBodyCount; i++) pmx.rigidBodies.push(parseRigidBody()); }; var parseConstraints = function() { var parseConstraint = function() { var p = {}; p.name = dv.getTextBuffer(); p.englishName = dv.getTextBuffer(); p.type = dv.getUint8(); p.rigidBodyIndex1 = dv.getIndex(pmx.metadata.rigidBodyIndexSize); p.rigidBodyIndex2 = dv.getIndex(pmx.metadata.rigidBodyIndexSize); p.position = dv.getFloat32Array(3); p.rotation = dv.getFloat32Array(3); p.translationLimitation1 = dv.getFloat32Array(3); p.translationLimitation2 = dv.getFloat32Array(3); p.rotationLimitation1 = dv.getFloat32Array(3); p.rotationLimitation2 = dv.getFloat32Array(3); p.springPosition = dv.getFloat32Array(3); p.springRotation = dv.getFloat32Array(3); return p; }; var metadata = pmx.metadata; metadata.constraintCount = dv.getUint32(); pmx.constraints = []; for (var i = 0; i < metadata.constraintCount; i++) pmx.constraints.push(parseConstraint()); }; parseHeader(); parseVertices(); parseFaces(); parseTextures(); parseMaterials(); parseBones(); parseMorphs(); parseFrames(); parseRigidBodies(); parseConstraints(); if (leftToRight === true) this.leftToRightModel(pmx); return pmx; } parseVmd(buffer, leftToRight) { var vmd = {}; var dv = new DataViewEx(buffer); vmd.metadata = {}; vmd.metadata.coordinateSystem = "left"; var parseHeader = function() { var metadata = vmd.metadata; metadata.magic = dv.getChars(30); if (metadata.magic !== "Vocaloid Motion Data 0002") throw "VMD file magic is not Vocaloid Motion Data 0002, but " + metadata.magic; metadata.name = dv.getSjisStringsAsUnicode(20); }; var parseMotions = function() { var parseMotion = function() { var p = {}; p.boneName = dv.getSjisStringsAsUnicode(15); p.frameNum = dv.getUint32(); p.position = dv.getFloat32Array(3); p.rotation = dv.getFloat32Array(4); p.interpolation = dv.getUint8Array(64); return p; }; var metadata = vmd.metadata; metadata.motionCount = dv.getUint32(); vmd.motions = []; for (var i = 0; i < metadata.motionCount; i++) vmd.motions.push(parseMotion()); }; var parseMorphs = function() { var parseMorph = function() { var p = {}; p.morphName = dv.getSjisStringsAsUnicode(15); p.frameNum = dv.getUint32(); p.weight = dv.getFloat32(); return p; }; var metadata = vmd.metadata; metadata.morphCount = dv.getUint32(); vmd.morphs = []; for (var i = 0; i < metadata.morphCount; i++) vmd.morphs.push(parseMorph()); }; var parseCameras = function() { var parseCamera = function() { var p = {}; p.frameNum = dv.getUint32(); p.distance = dv.getFloat32(); p.position = dv.getFloat32Array(3); p.rotation = dv.getFloat32Array(3); p.interpolation = dv.getUint8Array(24); p.fov = dv.getUint32(); p.perspective = dv.getUint8(); return p; }; var metadata = vmd.metadata; metadata.cameraCount = dv.getUint32(); vmd.cameras = []; for (var i = 0; i < metadata.cameraCount; i++) vmd.cameras.push(parseCamera()); }; parseHeader(); parseMotions(); parseMorphs(); parseCameras(); if (leftToRight === true) this.leftToRightVmd(vmd); return vmd; } parseVpd(text, leftToRight) { var vpd = {}; vpd.metadata = {}; vpd.metadata.coordinateSystem = "left"; vpd.bones = []; var lines = text.replace(/\/\/\w*(\r|\n|\r\n)/g, "").split(/\r|\n|\r\n/); function throwError() { throw "the file seems not vpd file."; } function checkMagic() { if (lines[0] !== "Vocaloid Pose Data file") throwError(); } function parseHeader() { if (lines.length < 4) throwError(); vpd.metadata.parentFile = lines[2]; vpd.metadata.boneCount = parseInt(lines[3]); } function parseBones() { var boneHeaderPattern = /^\s*(Bone[0-9]+)\s*\{\s*(.*)$/; var boneVectorPattern = /^\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*;/; var boneQuaternionPattern = /^\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*;/; var boneFooterPattern = /^\s*}/; var bones = vpd.bones; var n = null; var v = null; var q = null; for (var i = 4; i < lines.length; i++) { var line = lines[i]; var result = line.match(boneHeaderPattern); if (result !== null) { if (n !== null) throwError(); n = result[2]; } result = line.match(boneVectorPattern); if (result !== null) { if (v !== null) throwError(); v = [ parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]) ]; } result = line.match(boneQuaternionPattern); if (result !== null) { if (q !== null) throwError(); q = [ parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]), parseFloat(result[4]) ]; } result = line.match(boneFooterPattern); if (result !== null) { if (n === null || v === null || q === null) throwError(); bones.push({ name: n, translation: v, quaternion: q }); n = null; v = null; q = null; } } if (n !== null || v !== null || q !== null) throwError(); } checkMagic(); parseHeader(); parseBones(); if (leftToRight === true) this.leftToRightVpd(vpd); return vpd; } mergeVmds(vmds) { var v = {}; v.metadata = {}; v.metadata.name = vmds[0].metadata.name; v.metadata.coordinateSystem = vmds[0].metadata.coordinateSystem; v.metadata.motionCount = 0; v.metadata.morphCount = 0; v.metadata.cameraCount = 0; v.motions = []; v.morphs = []; v.cameras = []; for (var i = 0; i < vmds.length; i++) { var v2 = vmds[i]; v.metadata.motionCount += v2.metadata.motionCount; v.metadata.morphCount += v2.metadata.morphCount; v.metadata.cameraCount += v2.metadata.cameraCount; for (var j = 0; j < v2.metadata.motionCount; j++) v.motions.push(v2.motions[j]); for (var j = 0; j < v2.metadata.morphCount; j++) v.morphs.push(v2.morphs[j]); for (var j = 0; j < v2.metadata.cameraCount; j++) v.cameras.push(v2.cameras[j]); } return v; } leftToRightModel(model) { if (model.metadata.coordinateSystem === "right") return; model.metadata.coordinateSystem = "right"; var helper = new DataCreationHelper(); for (var i = 0; i < model.metadata.vertexCount; i++) { helper.leftToRightVector3(model.vertices[i].position); helper.leftToRightVector3(model.vertices[i].normal); } for (var i = 0; i < model.metadata.faceCount; i++) helper.leftToRightIndexOrder(model.faces[i].indices); for (var i = 0; i < model.metadata.boneCount; i++) helper.leftToRightVector3(model.bones[i].position); for (var i = 0; i < model.metadata.morphCount; i++) { var m = model.morphs[i]; if (model.metadata.format === "pmx" && m.type !== 1) continue; for (var j = 0; j < m.elements.length; j++) helper.leftToRightVector3(m.elements[j].position); } for (var i = 0; i < model.metadata.rigidBodyCount; i++) { helper.leftToRightVector3(model.rigidBodies[i].position); helper.leftToRightEuler(model.rigidBodies[i].rotation); } for (var i = 0; i < model.metadata.constraintCount; i++) { helper.leftToRightVector3(model.constraints[i].position); helper.leftToRightEuler(model.constraints[i].rotation); helper.leftToRightVector3Range(model.constraints[i].translationLimitation1, model.constraints[i].translationLimitation2); helper.leftToRightEulerRange(model.constraints[i].rotationLimitation1, model.constraints[i].rotationLimitation2); } } leftToRightVmd(vmd) { if (vmd.metadata.coordinateSystem === "right") return; vmd.metadata.coordinateSystem = "right"; var helper = new DataCreationHelper(); for (var i = 0; i < vmd.metadata.motionCount; i++) { helper.leftToRightVector3(vmd.motions[i].position); helper.leftToRightQuaternion(vmd.motions[i].rotation); } for (var i = 0; i < vmd.metadata.cameraCount; i++) { helper.leftToRightVector3(vmd.cameras[i].position); helper.leftToRightEuler(vmd.cameras[i].rotation); } } leftToRightVpd(vpd) { if (vpd.metadata.coordinateSystem === "right") return; vpd.metadata.coordinateSystem = "right"; var helper = new DataCreationHelper(); for (var i = 0; i < vpd.bones.length; i++) { helper.leftToRightVector3(vpd.bones[i].translation); helper.leftToRightQuaternion(vpd.bones[i].quaternion); } } }; //#endregion //#region node_modules/three-stdlib/exporters/MMDExporter.js var __defProp$50 = Object.defineProperty; var __defNormalProp$50 = (obj, key, value) => key in obj ? __defProp$50(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$50 = (obj, key, value) => { __defNormalProp$50(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var MMDExporter = class { constructor() { __publicField$50(this, "u2sTable"); } parseVpd(skin, outputShiftJis, useOriginalBones) { if (skin.isSkinnedMesh !== true) { console.warn("THREE.MMDExporter: parseVpd() requires SkinnedMesh instance."); return null; } function toStringsFromNumber(num) { if (Math.abs(num) < 1e-6) num = 0; let a = num.toString(); if (a.indexOf(".") === -1) a += "."; a += "000000"; const index = a.indexOf("."); const d = a.slice(0, index); const p = a.slice(index + 1, index + 7); return d + "." + p; } function toStringsFromArray(array2) { const a = []; for (let i = 0, il = array2.length; i < il; i++) a.push(toStringsFromNumber(array2[i])); return a.join(","); } skin.updateMatrixWorld(true); const bones = skin.skeleton.bones; const bones2 = this.getBindBones(skin); const position = new Vector3(); const quaternion = new Quaternion(); const quaternion2 = new Quaternion(); const matrix = new Matrix4(); const array = []; array.push("Vocaloid Pose Data file"); array.push(""); array.push((skin.name !== "" ? skin.name.replace(/\s/g, "_") : "skin") + ".osm;"); array.push(bones.length + ";"); array.push(""); for (let i = 0, il = bones.length; i < il; i++) { const bone = bones[i]; const bone2 = bones2[i]; if (useOriginalBones === true && bone.userData.ik !== void 0 && bone.userData.ik.originalMatrix !== void 0) matrix.fromArray(bone.userData.ik.originalMatrix); else matrix.copy(bone.matrix); position.setFromMatrixPosition(matrix); quaternion.setFromRotationMatrix(matrix); const pArray = position.sub(bone2.position).toArray(); const qArray = quaternion2.copy(bone2.quaternion).conjugate().multiply(quaternion).toArray(); pArray[2] = -pArray[2]; qArray[0] = -qArray[0]; qArray[1] = -qArray[1]; array.push("Bone" + i + "{" + bone.name); array.push(" " + toStringsFromArray(pArray) + ";"); array.push(" " + toStringsFromArray(qArray) + ";"); array.push("}"); array.push(""); } array.push(""); const lines = array.join("\n"); return outputShiftJis === true ? this.unicodeToShiftjis(lines) : lines; } unicodeToShiftjis(str) { if (this.u2sTable === void 0) { const table = new CharsetEncoder().s2uTable; this.u2sTable = {}; const keys = Object.keys(table); for (let i = 0, il = keys.length; i < il; i++) { let key = keys[i]; const value = table[key]; this.u2sTable[value] = parseInt(key); } } const array = []; for (let i = 0, il = str.length; i < il; i++) { const code = str.charCodeAt(i); const value = this.u2sTable[code]; if (value === void 0) throw "cannot convert charcode 0x" + code.toString(16); else if (value > 255) { array.push(value >> 8 & 255); array.push(value & 255); } else array.push(value & 255); } return new Uint8Array(array); } getBindBones(skin) { const poseSkin = skin.clone(); poseSkin.pose(); return poseSkin.skeleton.bones; } }; //#endregion //#region node_modules/three-stdlib/exporters/STLExporter.js var __defProp$49 = Object.defineProperty; var __defNormalProp$49 = (obj, key, value) => key in obj ? __defProp$49(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$49 = (obj, key, value) => { __defNormalProp$49(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var isMesh = (object) => object.isMesh; var STLExporter = class { constructor() { __publicField$49(this, "binary", false); __publicField$49(this, "output", ""); __publicField$49(this, "offset", 80); __publicField$49(this, "objects", []); __publicField$49(this, "triangles", 0); __publicField$49(this, "vA", new Vector3()); __publicField$49(this, "vB", new Vector3()); __publicField$49(this, "vC", new Vector3()); __publicField$49(this, "cb", new Vector3()); __publicField$49(this, "ab", new Vector3()); __publicField$49(this, "normal", new Vector3()); } parse(scene, options) { this.binary = (options == null ? void 0 : options.binary) !== void 0 ? options == null ? void 0 : options.binary : false; scene.traverse((object) => { if (isMesh(object)) { const geometry = object.geometry; if (!geometry.isBufferGeometry) throw new Error("THREE.STLExporter: Geometry is not of type THREE.BufferGeometry."); const index = geometry.index; const positionAttribute = geometry.getAttribute("position") || null; if (!positionAttribute) return; this.triangles += index !== null ? index.count / 3 : positionAttribute.count / 3; this.objects.push({ object3d: object, geometry }); } }); if (this.binary) { const bufferLength = this.triangles * 2 + this.triangles * 3 * 4 * 4 + 80 + 4; const arrayBuffer = new ArrayBuffer(bufferLength); this.output = new DataView(arrayBuffer); this.output.setUint32(this.offset, this.triangles, true); this.offset += 4; } else { this.output = ""; this.output += "solid exported\n"; } for (let i = 0, il = this.objects.length; i < il; i++) { const object = this.objects[i].object3d; const geometry = this.objects[i].geometry; const index = geometry.index; const positionAttribute = geometry.getAttribute("position"); if (index !== null) for (let j = 0; j < index.count; j += 3) { const a = index.getX(j + 0); const b = index.getX(j + 1); const c = index.getX(j + 2); this.writeFace(a, b, c, positionAttribute, object); } else for (let j = 0; j < positionAttribute.count; j += 3) { const a = j + 0; const b = j + 1; const c = j + 2; this.writeFace(a, b, c, positionAttribute, object); } } if (!this.binary) this.output += "endsolid exported\n"; return this.output; } writeFace(a, b, c, positionAttribute, object) { this.vA.fromBufferAttribute(positionAttribute, a); this.vB.fromBufferAttribute(positionAttribute, b); this.vC.fromBufferAttribute(positionAttribute, c); if (object.isSkinnedMesh) { const mesh = object; if ("applyBoneTransform" in mesh) { mesh.applyBoneTransform(a, this.vA); mesh.applyBoneTransform(b, this.vB); mesh.applyBoneTransform(c, this.vC); } else { mesh.boneTransform(a, this.vA); mesh.boneTransform(b, this.vB); mesh.boneTransform(c, this.vC); } } this.vA.applyMatrix4(object.matrixWorld); this.vB.applyMatrix4(object.matrixWorld); this.vC.applyMatrix4(object.matrixWorld); this.writeNormal(this.vA, this.vB, this.vC); this.writeVertex(this.vA); this.writeVertex(this.vB); this.writeVertex(this.vC); if (this.binary && this.output instanceof DataView) { this.output.setUint16(this.offset, 0, true); this.offset += 2; } else { this.output += " endloop\n"; this.output += " endfacet\n"; } } writeNormal(vA, vB, vC) { this.cb.subVectors(vC, vB); this.ab.subVectors(vA, vB); this.cb.cross(this.ab).normalize(); this.normal.copy(this.cb).normalize(); if (this.binary && this.output instanceof DataView) { this.output.setFloat32(this.offset, this.normal.x, true); this.offset += 4; this.output.setFloat32(this.offset, this.normal.y, true); this.offset += 4; this.output.setFloat32(this.offset, this.normal.z, true); this.offset += 4; } else { this.output += ` facet normal ${this.normal.x} ${this.normal.y} ${this.normal.z} `; this.output += " outer loop\n"; } } writeVertex(vertex) { if (this.binary && this.output instanceof DataView) { this.output.setFloat32(this.offset, vertex.x, true); this.offset += 4; this.output.setFloat32(this.offset, vertex.y, true); this.offset += 4; this.output.setFloat32(this.offset, vertex.z, true); this.offset += 4; } else this.output += ` vertex ${vertex.x} ${vertex.y} ${vertex.z} `; } }; //#endregion //#region node_modules/three-stdlib/exporters/OBJExporter.js var __defProp$48 = Object.defineProperty; var __defNormalProp$48 = (obj, key, value) => key in obj ? __defProp$48(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$48 = (obj, key, value) => { __defNormalProp$48(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var OBJExporter = class { constructor() { __publicField$48(this, "output"); __publicField$48(this, "indexVertex"); __publicField$48(this, "indexVertexUvs"); __publicField$48(this, "indexNormals"); __publicField$48(this, "vertex"); __publicField$48(this, "color"); __publicField$48(this, "normal"); __publicField$48(this, "uv"); __publicField$48(this, "face"); this.output = ""; this.indexVertex = 0; this.indexVertexUvs = 0; this.indexNormals = 0; this.vertex = new Vector3(); this.color = new Color(); this.normal = new Vector3(); this.uv = new Vector2(); this.face = []; } parse(object) { object.traverse((child) => { if (child instanceof Mesh && child.isMesh) this.parseMesh(child); if (child instanceof Line && child.isLine) this.parseLine(child); if (child instanceof Points && child.isPoints) this.parsePoints(child); }); return this.output; } parseMesh(mesh) { let nbVertex = 0; let nbNormals = 0; let nbVertexUvs = 0; const geometry = mesh.geometry; const normalMatrixWorld = new Matrix3(); if (!geometry.isBufferGeometry) throw new Error("THREE.OBJExporter: Geometry is not of type THREE.BufferGeometry."); const vertices = geometry.getAttribute("position"); const normals = geometry.getAttribute("normal"); const uvs = geometry.getAttribute("uv"); const indices = geometry.getIndex(); this.output += `o ${mesh.name} `; if (mesh.material && !Array.isArray(mesh.material) && mesh.material.name) this.output += `usemtl ${mesh.material.name} `; if (vertices !== void 0) for (let i = 0, l = vertices.count; i < l; i++, nbVertex++) { this.vertex.x = vertices.getX(i); this.vertex.y = vertices.getY(i); this.vertex.z = vertices.getZ(i); this.vertex.applyMatrix4(mesh.matrixWorld); this.output += `v ${this.vertex.x} ${this.vertex.y} ${this.vertex.z} `; } if (uvs !== void 0) for (let i = 0, l = uvs.count; i < l; i++, nbVertexUvs++) { this.uv.x = uvs.getX(i); this.uv.y = uvs.getY(i); this.output += `vt ${this.uv.x} ${this.uv.y} `; } if (normals !== void 0) { normalMatrixWorld.getNormalMatrix(mesh.matrixWorld); for (let i = 0, l = normals.count; i < l; i++, nbNormals++) { this.normal.x = normals.getX(i); this.normal.y = normals.getY(i); this.normal.z = normals.getZ(i); this.normal.applyMatrix3(normalMatrixWorld).normalize(); this.output += `vn ${this.normal.x} ${this.normal.y} ${this.normal.z} `; } } if (indices !== null) for (let i = 0, l = indices.count; i < l; i += 3) { for (let m = 0; m < 3; m++) { const j = indices.getX(i + m) + 1; this.face[m] = this.indexVertex + j + (normals || uvs ? `/${uvs ? this.indexVertexUvs + j : ""}${normals ? `/${this.indexNormals + j}` : ""}` : ""); } this.output += `f ${this.face.join(" ")} `; } else for (let i = 0, l = vertices.count; i < l; i += 3) { for (let m = 0; m < 3; m++) { const j = i + m + 1; this.face[m] = this.indexVertex + j + (normals || uvs ? `/${uvs ? this.indexVertexUvs + j : ""}${normals ? `/${this.indexNormals + j}` : ""}` : ""); } this.output += `f ${this.face.join(" ")} `; } this.indexVertex += nbVertex; this.indexVertexUvs += nbVertexUvs; this.indexNormals += nbNormals; } parseLine(line) { let nbVertex = 0; const geometry = line.geometry; const type = line.type; if (geometry.isBufferGeometry) throw new Error("THREE.OBJExporter: Geometry is not of type THREE.BufferGeometry."); const vertices = geometry.getAttribute("position"); this.output += `o ${line.name} `; if (vertices !== void 0) for (let i = 0, l = vertices.count; i < l; i++, nbVertex++) { this.vertex.x = vertices.getX(i); this.vertex.y = vertices.getY(i); this.vertex.z = vertices.getZ(i); this.vertex.applyMatrix4(line.matrixWorld); this.output += `v ${this.vertex.x} ${this.vertex.y} ${this.vertex.z} `; } if (type === "Line") { this.output += "l "; for (let j = 1, l = vertices.count; j <= l; j++) this.output += `${this.indexVertex + j} `; this.output += "\n"; } if (type === "LineSegments") for (let j = 1, k = j + 1, l = vertices.count; j < l; j += 2, k = j + 1) this.output += `l ${this.indexVertex + j} ${this.indexVertex + k} `; this.indexVertex += nbVertex; } parsePoints(points) { let nbVertex = 0; const geometry = points.geometry; if (!geometry.isBufferGeometry) throw new Error("THREE.OBJExporter: Geometry is not of type THREE.BufferGeometry."); const vertices = geometry.getAttribute("position"); const colors = geometry.getAttribute("color"); this.output += `o ${points.name} `; if (vertices !== void 0) for (let i = 0, l = vertices.count; i < l; i++, nbVertex++) { this.vertex.fromBufferAttribute(vertices, i); this.vertex.applyMatrix4(points.matrixWorld); this.output += `v ${this.vertex.x} ${this.vertex.y} ${this.vertex.z}`; if (colors !== void 0 && colors instanceof BufferAttribute) { this.color.fromBufferAttribute(colors, i); this.output += ` ${this.color.r} ${this.color.g} ${this.color.b}`; } this.output += "\n"; } this.output += "p "; for (let j = 1, l = vertices.count; j <= l; j++) this.output += `${this.indexVertex + j} `; this.output += "\n"; this.indexVertex += nbVertex; } }; //#endregion //#region node_modules/three-stdlib/environments/RoomEnvironment.js function RoomEnvironment() { const scene = new Scene(); const geometry = new BoxGeometry(); geometry.deleteAttribute("uv"); const roomMaterial = new MeshStandardMaterial({ side: 1 }); const boxMaterial = new MeshStandardMaterial(); const mainLight = new PointLight(16777215, 5, 28, 2); mainLight.position.set(.418, 16.199, .3); scene.add(mainLight); const room = new Mesh(geometry, roomMaterial); room.position.set(-.757, 13.219, .717); room.scale.set(31.713, 28.305, 28.591); scene.add(room); const box1 = new Mesh(geometry, boxMaterial); box1.position.set(-10.906, 2.009, 1.846); box1.rotation.set(0, -.195, 0); box1.scale.set(2.328, 7.905, 4.651); scene.add(box1); const box2 = new Mesh(geometry, boxMaterial); box2.position.set(-5.607, -.754, -.758); box2.rotation.set(0, .994, 0); box2.scale.set(1.97, 1.534, 3.955); scene.add(box2); const box3 = new Mesh(geometry, boxMaterial); box3.position.set(6.167, .857, 7.803); box3.rotation.set(0, .561, 0); box3.scale.set(3.927, 6.285, 3.687); scene.add(box3); const box4 = new Mesh(geometry, boxMaterial); box4.position.set(-2.017, .018, 6.124); box4.rotation.set(0, .333, 0); box4.scale.set(2.002, 4.566, 2.064); scene.add(box4); const box5 = new Mesh(geometry, boxMaterial); box5.position.set(2.291, -.756, -2.621); box5.rotation.set(0, -.286, 0); box5.scale.set(1.546, 1.552, 1.496); scene.add(box5); const box6 = new Mesh(geometry, boxMaterial); box6.position.set(-2.193, -.369, -5.547); box6.rotation.set(0, .516, 0); box6.scale.set(3.875, 3.487, 2.986); scene.add(box6); const light1 = new Mesh(geometry, createAreaLightMaterial(50)); light1.position.set(-16.116, 14.37, 8.208); light1.scale.set(.1, 2.428, 2.739); scene.add(light1); const light2 = new Mesh(geometry, createAreaLightMaterial(50)); light2.position.set(-16.109, 18.021, -8.207); light2.scale.set(.1, 2.425, 2.751); scene.add(light2); const light3 = new Mesh(geometry, createAreaLightMaterial(17)); light3.position.set(14.904, 12.198, -1.832); light3.scale.set(.15, 4.265, 6.331); scene.add(light3); const light4 = new Mesh(geometry, createAreaLightMaterial(43)); light4.position.set(-.462, 8.89, 14.52); light4.scale.set(4.38, 5.441, .088); scene.add(light4); const light5 = new Mesh(geometry, createAreaLightMaterial(20)); light5.position.set(3.235, 11.486, -12.541); light5.scale.set(2.5, 2, .1); scene.add(light5); const light6 = new Mesh(geometry, createAreaLightMaterial(100)); light6.position.set(0, 20, 0); light6.scale.set(1, .1, 1); scene.add(light6); function createAreaLightMaterial(intensity) { const material = new MeshBasicMaterial(); material.color.setScalar(intensity); return material; } return scene; } //#endregion //#region node_modules/three-stdlib/animation/AnimationClipCreator.js var AnimationClipCreator = { CreateRotationAnimation(period, axis = "x") { const times = [0, period]; return new AnimationClip(null, period, [new NumberKeyframeTrack(".rotation[" + axis + "]", times, [0, 360])]); }, CreateScaleAxisAnimation(period, axis = "x") { const times = [0, period]; return new AnimationClip(null, period, [new NumberKeyframeTrack(".scale[" + axis + "]", times, [0, 1])]); }, CreateShakeAnimation(duration, shakeScale) { const times = [], values = [], tmp = new Vector3(); for (let i = 0; i < duration * 10; i++) { times.push(i / 10); tmp.set(Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1).multiply(shakeScale).toArray(values, values.length); } return new AnimationClip(null, duration, [new VectorKeyframeTrack(".position", times, values)]); }, CreatePulsationAnimation(duration, pulseScale) { const times = [], values = [], tmp = new Vector3(); for (let i = 0; i < duration * 10; i++) { times.push(i / 10); const scaleFactor = Math.random() * pulseScale; tmp.set(scaleFactor, scaleFactor, scaleFactor).toArray(values, values.length); } return new AnimationClip(null, duration, [new VectorKeyframeTrack(".scale", times, values)]); }, CreateVisibilityAnimation(duration) { return new AnimationClip(null, duration, [new BooleanKeyframeTrack(".visible", [ 0, duration / 2, duration ], [ true, false, true ])]); }, CreateMaterialColorAnimation(duration, colors) { const times = [], values = [], timeStep = duration / colors.length; for (let i = 0; i < colors.length; i++) { times.push(i * timeStep); const color = colors[i]; values.push(color.r, color.g, color.b); } return new AnimationClip(null, duration, [new ColorKeyframeTrack(".material.color", times, values)]); } }; //#endregion //#region node_modules/three-stdlib/animation/CCDIKSolver.js var _q$2 = /* @__PURE__ */ new Quaternion(); var _targetPos = /* @__PURE__ */ new Vector3(); var _targetVec = /* @__PURE__ */ new Vector3(); var _effectorPos = /* @__PURE__ */ new Vector3(); var _effectorVec = /* @__PURE__ */ new Vector3(); var _linkPos = /* @__PURE__ */ new Vector3(); var _invLinkQ = /* @__PURE__ */ new Quaternion(); var _linkScale = /* @__PURE__ */ new Vector3(); var _axis = /* @__PURE__ */ new Vector3(); var _vector$3 = /* @__PURE__ */ new Vector3(); var _matrix$1 = /* @__PURE__ */ new Matrix4(); var CCDIKSolver = class { /** * @param {THREE.SkinnedMesh} mesh * @param {Array} iks */ constructor(mesh, iks = []) { this.mesh = mesh; this.iks = iks; this._valid(); } /** * Update all IK bones. * * @return {CCDIKSolver} */ update() { const iks = this.iks; for (let i = 0, il = iks.length; i < il; i++) this.updateOne(iks[i]); return this; } /** * Update one IK bone * * @param {Object} ik parameter * @return {CCDIKSolver} */ updateOne(ik) { const bones = this.mesh.skeleton.bones; const math = Math; const effector = bones[ik.effector]; const target = bones[ik.target]; _targetPos.setFromMatrixPosition(target.matrixWorld); const links = ik.links; const iteration = ik.iteration !== void 0 ? ik.iteration : 1; for (let i = 0; i < iteration; i++) { let rotated = false; for (let j = 0, jl = links.length; j < jl; j++) { const link = bones[links[j].index]; if (links[j].enabled === false) break; const limitation = links[j].limitation; const rotationMin = links[j].rotationMin; const rotationMax = links[j].rotationMax; link.matrixWorld.decompose(_linkPos, _invLinkQ, _linkScale); _invLinkQ.invert(); _effectorPos.setFromMatrixPosition(effector.matrixWorld); _effectorVec.subVectors(_effectorPos, _linkPos); _effectorVec.applyQuaternion(_invLinkQ); _effectorVec.normalize(); _targetVec.subVectors(_targetPos, _linkPos); _targetVec.applyQuaternion(_invLinkQ); _targetVec.normalize(); let angle = _targetVec.dot(_effectorVec); if (angle > 1) angle = 1; else if (angle < -1) angle = -1; angle = math.acos(angle); if (angle < 1e-5) continue; if (ik.minAngle !== void 0 && angle < ik.minAngle) angle = ik.minAngle; if (ik.maxAngle !== void 0 && angle > ik.maxAngle) angle = ik.maxAngle; _axis.crossVectors(_effectorVec, _targetVec); _axis.normalize(); _q$2.setFromAxisAngle(_axis, angle); link.quaternion.multiply(_q$2); if (limitation !== void 0) { let c = link.quaternion.w; if (c > 1) c = 1; const c2 = math.sqrt(1 - c * c); link.quaternion.set(limitation.x * c2, limitation.y * c2, limitation.z * c2, c); } if (rotationMin !== void 0) link.rotation.setFromVector3(_vector$3.setFromEuler(link.rotation).max(rotationMin)); if (rotationMax !== void 0) link.rotation.setFromVector3(_vector$3.setFromEuler(link.rotation).min(rotationMax)); link.updateMatrixWorld(true); rotated = true; } if (!rotated) break; } return this; } /** * Creates Helper * * @return {CCDIKHelper} */ createHelper() { return new CCDIKHelper(this.mesh, this.iks); } _valid() { const iks = this.iks; const bones = this.mesh.skeleton.bones; for (let i = 0, il = iks.length; i < il; i++) { const ik = iks[i]; const effector = bones[ik.effector]; const links = ik.links; let link0, link1; link0 = effector; for (let j = 0, jl = links.length; j < jl; j++) { link1 = bones[links[j].index]; if (link0.parent !== link1) console.warn("THREE.CCDIKSolver: bone " + link0.name + " is not the child of bone " + link1.name); link0 = link1; } } } }; function getPosition(bone, matrixWorldInv) { return _vector$3.setFromMatrixPosition(bone.matrixWorld).applyMatrix4(matrixWorldInv); } function setPositionOfBoneToAttributeArray(array, index, bone, matrixWorldInv) { const v = getPosition(bone, matrixWorldInv); array[index * 3 + 0] = v.x; array[index * 3 + 1] = v.y; array[index * 3 + 2] = v.z; } var CCDIKHelper = class extends Object3D { constructor(mesh, iks = [], sphereSize = .25) { super(); this.root = mesh; this.iks = iks; this.matrix.copy(mesh.matrixWorld); this.matrixAutoUpdate = false; this.sphereGeometry = new SphereGeometry(sphereSize, 16, 8); this.targetSphereMaterial = new MeshBasicMaterial({ color: new Color(16746632), depthTest: false, depthWrite: false, transparent: true }); this.effectorSphereMaterial = new MeshBasicMaterial({ color: new Color(8978312), depthTest: false, depthWrite: false, transparent: true }); this.linkSphereMaterial = new MeshBasicMaterial({ color: new Color(8947967), depthTest: false, depthWrite: false, transparent: true }); this.lineMaterial = new LineBasicMaterial({ color: new Color(16711680), depthTest: false, depthWrite: false, transparent: true }); this._init(); } /** * Updates IK bones visualization. */ updateMatrixWorld(force) { const mesh = this.root; if (this.visible) { let offset = 0; const iks = this.iks; const bones = mesh.skeleton.bones; _matrix$1.copy(mesh.matrixWorld).invert(); for (let i = 0, il = iks.length; i < il; i++) { const ik = iks[i]; const targetBone = bones[ik.target]; const effectorBone = bones[ik.effector]; const targetMesh = this.children[offset++]; const effectorMesh = this.children[offset++]; targetMesh.position.copy(getPosition(targetBone, _matrix$1)); effectorMesh.position.copy(getPosition(effectorBone, _matrix$1)); for (let j = 0, jl = ik.links.length; j < jl; j++) { const linkBone = bones[ik.links[j].index]; this.children[offset++].position.copy(getPosition(linkBone, _matrix$1)); } const line = this.children[offset++]; const array = line.geometry.attributes.position.array; setPositionOfBoneToAttributeArray(array, 0, targetBone, _matrix$1); setPositionOfBoneToAttributeArray(array, 1, effectorBone, _matrix$1); for (let j = 0, jl = ik.links.length; j < jl; j++) { const linkBone = bones[ik.links[j].index]; setPositionOfBoneToAttributeArray(array, j + 2, linkBone, _matrix$1); } line.geometry.attributes.position.needsUpdate = true; } } this.matrix.copy(mesh.matrixWorld); super.updateMatrixWorld(force); } /** * Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app. */ dispose() { this.sphereGeometry.dispose(); this.targetSphereMaterial.dispose(); this.effectorSphereMaterial.dispose(); this.linkSphereMaterial.dispose(); this.lineMaterial.dispose(); const children = this.children; for (let i = 0; i < children.length; i++) { const child = children[i]; if (child.isLine) child.geometry.dispose(); } } _init() { const scope = this; const iks = this.iks; function createLineGeometry(ik) { const geometry = new BufferGeometry(); const vertices = new Float32Array((2 + ik.links.length) * 3); geometry.setAttribute("position", new BufferAttribute(vertices, 3)); return geometry; } function createTargetMesh() { return new Mesh(scope.sphereGeometry, scope.targetSphereMaterial); } function createEffectorMesh() { return new Mesh(scope.sphereGeometry, scope.effectorSphereMaterial); } function createLinkMesh() { return new Mesh(scope.sphereGeometry, scope.linkSphereMaterial); } function createLine(ik) { return new Line(createLineGeometry(ik), scope.lineMaterial); } for (let i = 0, il = iks.length; i < il; i++) { const ik = iks[i]; this.add(createTargetMesh()); this.add(createEffectorMesh()); for (let j = 0, jl = ik.links.length; j < jl; j++) this.add(createLinkMesh()); this.add(createLine(ik)); } } }; //#endregion //#region node_modules/three-stdlib/_polyfill/CapsuleGeometry.js var CapsuleGeometry = /* @__PURE__ */ (() => { class CapsuleGeometry2 extends LatheGeometry { constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) { const path = new Path(); path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0); path.absarc(0, length / 2, radius, 0, Math.PI * .5); super(path.getPoints(capSegments), radialSegments); this.type = "CapsuleGeometry"; this.parameters = { radius, height: length, capSegments, radialSegments }; } static fromJSON(data) { return new CapsuleGeometry2(data.radius, data.length, data.capSegments, data.radialSegments); } } return CapsuleGeometry2; })(); //#endregion //#region node_modules/three-stdlib/animation/MMDPhysics.js var MMDPhysics = class { /** * @param {THREE.SkinnedMesh} mesh * @param {Array} rigidBodyParams * @param {Array} (optional) constraintParams * @param {Object} params - (optional) * @param {Number} params.unitStep - Default is 1 / 65. * @param {Integer} params.maxStepNum - Default is 3. * @param {Vector3} params.gravity - Default is ( 0, - 9.8 * 10, 0 ) */ constructor(mesh, rigidBodyParams, constraintParams = [], params = {}) { if (typeof Ammo === "undefined") throw new Error("THREE.MMDPhysics: Import ammo.js https://github.com/kripken/ammo.js"); this.manager = new ResourceManager(); this.mesh = mesh; this.unitStep = params.unitStep !== void 0 ? params.unitStep : 1 / 65; this.maxStepNum = params.maxStepNum !== void 0 ? params.maxStepNum : 3; this.gravity = new Vector3(0, -9.8 * 10, 0); if (params.gravity !== void 0) this.gravity.copy(params.gravity); this.world = params.world !== void 0 ? params.world : null; this.bodies = []; this.constraints = []; this._init(mesh, rigidBodyParams, constraintParams); } /** * Advances Physics calculation and updates bones. * * @param {Number} delta - time in second * @return {MMDPhysics} */ update(delta) { const manager = this.manager; const mesh = this.mesh; let isNonDefaultScale = false; const position = manager.allocThreeVector3(); const quaternion = manager.allocThreeQuaternion(); const scale = manager.allocThreeVector3(); mesh.matrixWorld.decompose(position, quaternion, scale); if (scale.x !== 1 || scale.y !== 1 || scale.z !== 1) isNonDefaultScale = true; let parent; if (isNonDefaultScale) { parent = mesh.parent; if (parent !== null) mesh.parent = null; scale.copy(this.mesh.scale); mesh.scale.set(1, 1, 1); mesh.updateMatrixWorld(true); } this._updateRigidBodies(); this._stepSimulation(delta); this._updateBones(); if (isNonDefaultScale) { if (parent !== null) mesh.parent = parent; mesh.scale.copy(scale); } manager.freeThreeVector3(scale); manager.freeThreeQuaternion(quaternion); manager.freeThreeVector3(position); return this; } /** * Resets rigid bodies transorm to current bone's. * * @return {MMDPhysics} */ reset() { for (let i = 0, il = this.bodies.length; i < il; i++) this.bodies[i].reset(); return this; } /** * Warm ups Rigid bodies. Calculates cycles steps. * * @param {Integer} cycles * @return {MMDPhysics} */ warmup(cycles) { for (let i = 0; i < cycles; i++) this.update(1 / 60); return this; } /** * Sets gravity. * * @param {Vector3} gravity * @return {MMDPhysicsHelper} */ setGravity(gravity) { this.world.setGravity(new Ammo.btVector3(gravity.x, gravity.y, gravity.z)); this.gravity.copy(gravity); return this; } /** * Creates MMDPhysicsHelper * * @return {MMDPhysicsHelper} */ createHelper() { return new MMDPhysicsHelper(this.mesh, this); } _init(mesh, rigidBodyParams, constraintParams) { const manager = this.manager; const parent = mesh.parent; if (parent !== null) mesh.parent = null; const currentPosition = manager.allocThreeVector3(); const currentQuaternion = manager.allocThreeQuaternion(); const currentScale = manager.allocThreeVector3(); currentPosition.copy(mesh.position); currentQuaternion.copy(mesh.quaternion); currentScale.copy(mesh.scale); mesh.position.set(0, 0, 0); mesh.quaternion.set(0, 0, 0, 1); mesh.scale.set(1, 1, 1); mesh.updateMatrixWorld(true); if (this.world === null) { this.world = this._createWorld(); this.setGravity(this.gravity); } this._initRigidBodies(rigidBodyParams); this._initConstraints(constraintParams); if (parent !== null) mesh.parent = parent; mesh.position.copy(currentPosition); mesh.quaternion.copy(currentQuaternion); mesh.scale.copy(currentScale); mesh.updateMatrixWorld(true); this.reset(); manager.freeThreeVector3(currentPosition); manager.freeThreeQuaternion(currentQuaternion); manager.freeThreeVector3(currentScale); } _createWorld() { const config = new Ammo.btDefaultCollisionConfiguration(); const dispatcher = new Ammo.btCollisionDispatcher(config); const cache = new Ammo.btDbvtBroadphase(); const solver = new Ammo.btSequentialImpulseConstraintSolver(); return new Ammo.btDiscreteDynamicsWorld(dispatcher, cache, solver, config); } _initRigidBodies(rigidBodies) { for (let i = 0, il = rigidBodies.length; i < il; i++) this.bodies.push(new RigidBody(this.mesh, this.world, rigidBodies[i], this.manager)); } _initConstraints(constraints) { for (let i = 0, il = constraints.length; i < il; i++) { const params = constraints[i]; const bodyA = this.bodies[params.rigidBodyIndex1]; const bodyB = this.bodies[params.rigidBodyIndex2]; this.constraints.push(new Constraint(this.mesh, this.world, bodyA, bodyB, params, this.manager)); } } _stepSimulation(delta) { const unitStep = this.unitStep; let stepTime = delta; let maxStepNum = (delta / unitStep | 0) + 1; if (stepTime < unitStep) { stepTime = unitStep; maxStepNum = 1; } if (maxStepNum > this.maxStepNum) maxStepNum = this.maxStepNum; this.world.stepSimulation(stepTime, maxStepNum, unitStep); } _updateRigidBodies() { for (let i = 0, il = this.bodies.length; i < il; i++) this.bodies[i].updateFromBone(); } _updateBones() { for (let i = 0, il = this.bodies.length; i < il; i++) this.bodies[i].updateBone(); } }; var ResourceManager = class { constructor() { this.threeVector3s = []; this.threeMatrix4s = []; this.threeQuaternions = []; this.threeEulers = []; this.transforms = []; this.quaternions = []; this.vector3s = []; } allocThreeVector3() { return this.threeVector3s.length > 0 ? this.threeVector3s.pop() : new Vector3(); } freeThreeVector3(v) { this.threeVector3s.push(v); } allocThreeMatrix4() { return this.threeMatrix4s.length > 0 ? this.threeMatrix4s.pop() : new Matrix4(); } freeThreeMatrix4(m) { this.threeMatrix4s.push(m); } allocThreeQuaternion() { return this.threeQuaternions.length > 0 ? this.threeQuaternions.pop() : new Quaternion(); } freeThreeQuaternion(q) { this.threeQuaternions.push(q); } allocThreeEuler() { return this.threeEulers.length > 0 ? this.threeEulers.pop() : new Euler(); } freeThreeEuler(e) { this.threeEulers.push(e); } allocTransform() { return this.transforms.length > 0 ? this.transforms.pop() : new Ammo.btTransform(); } freeTransform(t) { this.transforms.push(t); } allocQuaternion() { return this.quaternions.length > 0 ? this.quaternions.pop() : new Ammo.btQuaternion(); } freeQuaternion(q) { this.quaternions.push(q); } allocVector3() { return this.vector3s.length > 0 ? this.vector3s.pop() : new Ammo.btVector3(); } freeVector3(v) { this.vector3s.push(v); } setIdentity(t) { t.setIdentity(); } getBasis(t) { var q = this.allocQuaternion(); t.getBasis().getRotation(q); return q; } getBasisAsMatrix3(t) { var q = this.getBasis(t); var m = this.quaternionToMatrix3(q); this.freeQuaternion(q); return m; } getOrigin(t) { return t.getOrigin(); } setOrigin(t, v) { t.getOrigin().setValue(v.x(), v.y(), v.z()); } copyOrigin(t1, t2) { var o = t2.getOrigin(); this.setOrigin(t1, o); } setBasis(t, q) { t.setRotation(q); } setBasisFromMatrix3(t, m) { var q = this.matrix3ToQuaternion(m); this.setBasis(t, q); this.freeQuaternion(q); } setOriginFromArray3(t, a) { t.getOrigin().setValue(a[0], a[1], a[2]); } setOriginFromThreeVector3(t, v) { t.getOrigin().setValue(v.x, v.y, v.z); } setBasisFromArray3(t, a) { var thQ = this.allocThreeQuaternion(); var thE = this.allocThreeEuler(); thE.set(a[0], a[1], a[2]); this.setBasisFromThreeQuaternion(t, thQ.setFromEuler(thE)); this.freeThreeEuler(thE); this.freeThreeQuaternion(thQ); } setBasisFromThreeQuaternion(t, a) { var q = this.allocQuaternion(); q.setX(a.x); q.setY(a.y); q.setZ(a.z); q.setW(a.w); this.setBasis(t, q); this.freeQuaternion(q); } multiplyTransforms(t1, t2) { var t = this.allocTransform(); this.setIdentity(t); var m1 = this.getBasisAsMatrix3(t1); var m2 = this.getBasisAsMatrix3(t2); var o1 = this.getOrigin(t1); var o2 = this.getOrigin(t2); var v1 = this.multiplyMatrix3ByVector3(m1, o2); var v2 = this.addVector3(v1, o1); this.setOrigin(t, v2); var m3 = this.multiplyMatrices3(m1, m2); this.setBasisFromMatrix3(t, m3); this.freeVector3(v1); this.freeVector3(v2); return t; } inverseTransform(t) { var t2 = this.allocTransform(); var m1 = this.getBasisAsMatrix3(t); var o = this.getOrigin(t); var m2 = this.transposeMatrix3(m1); var v1 = this.negativeVector3(o); var v2 = this.multiplyMatrix3ByVector3(m2, v1); this.setOrigin(t2, v2); this.setBasisFromMatrix3(t2, m2); this.freeVector3(v1); this.freeVector3(v2); return t2; } multiplyMatrices3(m1, m2) { var m3 = []; var v10 = this.rowOfMatrix3(m1, 0); var v11 = this.rowOfMatrix3(m1, 1); var v12 = this.rowOfMatrix3(m1, 2); var v20 = this.columnOfMatrix3(m2, 0); var v21 = this.columnOfMatrix3(m2, 1); var v22 = this.columnOfMatrix3(m2, 2); m3[0] = this.dotVectors3(v10, v20); m3[1] = this.dotVectors3(v10, v21); m3[2] = this.dotVectors3(v10, v22); m3[3] = this.dotVectors3(v11, v20); m3[4] = this.dotVectors3(v11, v21); m3[5] = this.dotVectors3(v11, v22); m3[6] = this.dotVectors3(v12, v20); m3[7] = this.dotVectors3(v12, v21); m3[8] = this.dotVectors3(v12, v22); this.freeVector3(v10); this.freeVector3(v11); this.freeVector3(v12); this.freeVector3(v20); this.freeVector3(v21); this.freeVector3(v22); return m3; } addVector3(v1, v2) { var v = this.allocVector3(); v.setValue(v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z()); return v; } dotVectors3(v1, v2) { return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z(); } rowOfMatrix3(m, i) { var v = this.allocVector3(); v.setValue(m[i * 3 + 0], m[i * 3 + 1], m[i * 3 + 2]); return v; } columnOfMatrix3(m, i) { var v = this.allocVector3(); v.setValue(m[i + 0], m[i + 3], m[i + 6]); return v; } negativeVector3(v) { var v2 = this.allocVector3(); v2.setValue(-v.x(), -v.y(), -v.z()); return v2; } multiplyMatrix3ByVector3(m, v) { var v4 = this.allocVector3(); var v0 = this.rowOfMatrix3(m, 0); var v1 = this.rowOfMatrix3(m, 1); var v2 = this.rowOfMatrix3(m, 2); var x = this.dotVectors3(v0, v); var y = this.dotVectors3(v1, v); var z = this.dotVectors3(v2, v); v4.setValue(x, y, z); this.freeVector3(v0); this.freeVector3(v1); this.freeVector3(v2); return v4; } transposeMatrix3(m) { var m2 = []; m2[0] = m[0]; m2[1] = m[3]; m2[2] = m[6]; m2[3] = m[1]; m2[4] = m[4]; m2[5] = m[7]; m2[6] = m[2]; m2[7] = m[5]; m2[8] = m[8]; return m2; } quaternionToMatrix3(q) { var m = []; var x = q.x(); var y = q.y(); var z = q.z(); var w = q.w(); var xx = x * x; var yy = y * y; var zz = z * z; var xy = x * y; var yz = y * z; var zx = z * x; var xw = x * w; var yw = y * w; var zw = z * w; m[0] = 1 - 2 * (yy + zz); m[1] = 2 * (xy - zw); m[2] = 2 * (zx + yw); m[3] = 2 * (xy + zw); m[4] = 1 - 2 * (zz + xx); m[5] = 2 * (yz - xw); m[6] = 2 * (zx - yw); m[7] = 2 * (yz + xw); m[8] = 1 - 2 * (xx + yy); return m; } matrix3ToQuaternion(m) { var t = m[0] + m[4] + m[8]; var s, x, y, z, w; if (t > 0) { s = Math.sqrt(t + 1) * 2; w = .25 * s; x = (m[7] - m[5]) / s; y = (m[2] - m[6]) / s; z = (m[3] - m[1]) / s; } else if (m[0] > m[4] && m[0] > m[8]) { s = Math.sqrt(1 + m[0] - m[4] - m[8]) * 2; w = (m[7] - m[5]) / s; x = .25 * s; y = (m[1] + m[3]) / s; z = (m[2] + m[6]) / s; } else if (m[4] > m[8]) { s = Math.sqrt(1 + m[4] - m[0] - m[8]) * 2; w = (m[2] - m[6]) / s; x = (m[1] + m[3]) / s; y = .25 * s; z = (m[5] + m[7]) / s; } else { s = Math.sqrt(1 + m[8] - m[0] - m[4]) * 2; w = (m[3] - m[1]) / s; x = (m[2] + m[6]) / s; y = (m[5] + m[7]) / s; z = .25 * s; } var q = this.allocQuaternion(); q.setX(x); q.setY(y); q.setZ(z); q.setW(w); return q; } }; var RigidBody = class { constructor(mesh, world, params, manager) { this.mesh = mesh; this.world = world; this.params = params; this.manager = manager; this.body = null; this.bone = null; this.boneOffsetForm = null; this.boneOffsetFormInverse = null; this._init(); } /** * Resets rigid body transform to the current bone's. * * @return {RigidBody} */ reset() { this._setTransformFromBone(); return this; } /** * Updates rigid body's transform from the current bone. * * @return {RidigBody} */ updateFromBone() { if (this.params.boneIndex !== -1 && this.params.type === 0) this._setTransformFromBone(); return this; } /** * Updates bone from the current ridid body's transform. * * @return {RidigBody} */ updateBone() { if (this.params.type === 0 || this.params.boneIndex === -1) return this; this._updateBoneRotation(); if (this.params.type === 1) this._updateBonePosition(); this.bone.updateMatrixWorld(true); if (this.params.type === 2) this._setPositionFromBone(); return this; } _init() { function generateShape(p) { switch (p.shapeType) { case 0: return new Ammo.btSphereShape(p.width); case 1: return new Ammo.btBoxShape(new Ammo.btVector3(p.width, p.height, p.depth)); case 2: return new Ammo.btCapsuleShape(p.width, p.height); default: throw new Error("unknown shape type " + p.shapeType); } } const manager = this.manager; const params = this.params; const bones = this.mesh.skeleton.bones; const bone = params.boneIndex === -1 ? new Bone() : bones[params.boneIndex]; const shape = generateShape(params); const weight = params.type === 0 ? 0 : params.weight; const localInertia = manager.allocVector3(); localInertia.setValue(0, 0, 0); if (weight !== 0) shape.calculateLocalInertia(weight, localInertia); const boneOffsetForm = manager.allocTransform(); manager.setIdentity(boneOffsetForm); manager.setOriginFromArray3(boneOffsetForm, params.position); manager.setBasisFromArray3(boneOffsetForm, params.rotation); const vector = manager.allocThreeVector3(); const boneForm = manager.allocTransform(); manager.setIdentity(boneForm); manager.setOriginFromThreeVector3(boneForm, bone.getWorldPosition(vector)); const form = manager.multiplyTransforms(boneForm, boneOffsetForm); const state = new Ammo.btDefaultMotionState(form); const info = new Ammo.btRigidBodyConstructionInfo(weight, state, shape, localInertia); info.set_m_friction(params.friction); info.set_m_restitution(params.restitution); const body = new Ammo.btRigidBody(info); if (params.type === 0) { body.setCollisionFlags(body.getCollisionFlags() | 2); body.setActivationState(4); } body.setDamping(params.positionDamping, params.rotationDamping); body.setSleepingThresholds(0, 0); this.world.addRigidBody(body, 1 << params.groupIndex, params.groupTarget); this.body = body; this.bone = bone; this.boneOffsetForm = boneOffsetForm; this.boneOffsetFormInverse = manager.inverseTransform(boneOffsetForm); manager.freeVector3(localInertia); manager.freeTransform(form); manager.freeTransform(boneForm); manager.freeThreeVector3(vector); } _getBoneTransform() { const manager = this.manager; const p = manager.allocThreeVector3(); const q = manager.allocThreeQuaternion(); const s = manager.allocThreeVector3(); this.bone.matrixWorld.decompose(p, q, s); const tr = manager.allocTransform(); manager.setOriginFromThreeVector3(tr, p); manager.setBasisFromThreeQuaternion(tr, q); const form = manager.multiplyTransforms(tr, this.boneOffsetForm); manager.freeTransform(tr); manager.freeThreeVector3(s); manager.freeThreeQuaternion(q); manager.freeThreeVector3(p); return form; } _getWorldTransformForBone() { const manager = this.manager; const tr = this.body.getCenterOfMassTransform(); return manager.multiplyTransforms(tr, this.boneOffsetFormInverse); } _setTransformFromBone() { const manager = this.manager; const form = this._getBoneTransform(); this.body.setCenterOfMassTransform(form); this.body.getMotionState().setWorldTransform(form); manager.freeTransform(form); } _setPositionFromBone() { const manager = this.manager; const form = this._getBoneTransform(); const tr = manager.allocTransform(); this.body.getMotionState().getWorldTransform(tr); manager.copyOrigin(tr, form); this.body.setCenterOfMassTransform(tr); this.body.getMotionState().setWorldTransform(tr); manager.freeTransform(tr); manager.freeTransform(form); } _updateBoneRotation() { const manager = this.manager; const tr = this._getWorldTransformForBone(); const q = manager.getBasis(tr); const thQ = manager.allocThreeQuaternion(); const thQ2 = manager.allocThreeQuaternion(); const thQ3 = manager.allocThreeQuaternion(); thQ.set(q.x(), q.y(), q.z(), q.w()); thQ2.setFromRotationMatrix(this.bone.matrixWorld); thQ2.conjugate(); thQ2.multiply(thQ); thQ3.setFromRotationMatrix(this.bone.matrix); this.bone.quaternion.copy(thQ2.multiply(thQ3).normalize()); manager.freeThreeQuaternion(thQ); manager.freeThreeQuaternion(thQ2); manager.freeThreeQuaternion(thQ3); manager.freeQuaternion(q); manager.freeTransform(tr); } _updateBonePosition() { const manager = this.manager; const tr = this._getWorldTransformForBone(); const thV = manager.allocThreeVector3(); const o = manager.getOrigin(tr); thV.set(o.x(), o.y(), o.z()); if (this.bone.parent) this.bone.parent.worldToLocal(thV); this.bone.position.copy(thV); manager.freeThreeVector3(thV); manager.freeTransform(tr); } }; var Constraint = class { /** * @param {THREE.SkinnedMesh} mesh * @param {Ammo.btDiscreteDynamicsWorld} world * @param {RigidBody} bodyA * @param {RigidBody} bodyB * @param {Object} params * @param {ResourceManager} manager */ constructor(mesh, world, bodyA, bodyB, params, manager) { this.mesh = mesh; this.world = world; this.bodyA = bodyA; this.bodyB = bodyB; this.params = params; this.manager = manager; this.constraint = null; this._init(); } _init() { const manager = this.manager; const params = this.params; const bodyA = this.bodyA; const bodyB = this.bodyB; const form = manager.allocTransform(); manager.setIdentity(form); manager.setOriginFromArray3(form, params.position); manager.setBasisFromArray3(form, params.rotation); const formA = manager.allocTransform(); const formB = manager.allocTransform(); bodyA.body.getMotionState().getWorldTransform(formA); bodyB.body.getMotionState().getWorldTransform(formB); const formInverseA = manager.inverseTransform(formA); const formInverseB = manager.inverseTransform(formB); const formA2 = manager.multiplyTransforms(formInverseA, form); const formB2 = manager.multiplyTransforms(formInverseB, form); const constraint = new Ammo.btGeneric6DofSpringConstraint(bodyA.body, bodyB.body, formA2, formB2, true); const lll = manager.allocVector3(); const lul = manager.allocVector3(); const all = manager.allocVector3(); const aul = manager.allocVector3(); lll.setValue(params.translationLimitation1[0], params.translationLimitation1[1], params.translationLimitation1[2]); lul.setValue(params.translationLimitation2[0], params.translationLimitation2[1], params.translationLimitation2[2]); all.setValue(params.rotationLimitation1[0], params.rotationLimitation1[1], params.rotationLimitation1[2]); aul.setValue(params.rotationLimitation2[0], params.rotationLimitation2[1], params.rotationLimitation2[2]); constraint.setLinearLowerLimit(lll); constraint.setLinearUpperLimit(lul); constraint.setAngularLowerLimit(all); constraint.setAngularUpperLimit(aul); for (let i = 0; i < 3; i++) if (params.springPosition[i] !== 0) { constraint.enableSpring(i, true); constraint.setStiffness(i, params.springPosition[i]); } for (let i = 0; i < 3; i++) if (params.springRotation[i] !== 0) { constraint.enableSpring(i + 3, true); constraint.setStiffness(i + 3, params.springRotation[i]); } if (constraint.setParam !== void 0) for (let i = 0; i < 6; i++) constraint.setParam(2, .475, i); this.world.addConstraint(constraint, true); this.constraint = constraint; manager.freeTransform(form); manager.freeTransform(formA); manager.freeTransform(formB); manager.freeTransform(formInverseA); manager.freeTransform(formInverseB); manager.freeTransform(formA2); manager.freeTransform(formB2); manager.freeVector3(lll); manager.freeVector3(lul); manager.freeVector3(all); manager.freeVector3(aul); } }; var _position = /* @__PURE__ */ new Vector3(); var _quaternion = /* @__PURE__ */ new Quaternion(); var _scale = /* @__PURE__ */ new Vector3(); var _matrixWorldInv = /* @__PURE__ */ new Matrix4(); var MMDPhysicsHelper = class extends Object3D { /** * Visualize Rigid bodies * * @param {THREE.SkinnedMesh} mesh * @param {Physics} physics */ constructor(mesh, physics) { super(); this.root = mesh; this.physics = physics; this.matrix.copy(mesh.matrixWorld); this.matrixAutoUpdate = false; this.materials = []; this.materials.push(new MeshBasicMaterial({ color: new Color(16746632), wireframe: true, depthTest: false, depthWrite: false, opacity: .25, transparent: true })); this.materials.push(new MeshBasicMaterial({ color: new Color(8978312), wireframe: true, depthTest: false, depthWrite: false, opacity: .25, transparent: true })); this.materials.push(new MeshBasicMaterial({ color: new Color(8947967), wireframe: true, depthTest: false, depthWrite: false, opacity: .25, transparent: true })); this._init(); } /** * Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app. */ dispose() { const materials = this.materials; const children = this.children; for (let i = 0; i < materials.length; i++) materials[i].dispose(); for (let i = 0; i < children.length; i++) { const child = children[i]; if (child.isMesh) child.geometry.dispose(); } } /** * Updates Rigid Bodies visualization. */ updateMatrixWorld(force) { var mesh = this.root; if (this.visible) { var bodies = this.physics.bodies; _matrixWorldInv.copy(mesh.matrixWorld).decompose(_position, _quaternion, _scale).compose(_position, _quaternion, _scale.set(1, 1, 1)).invert(); for (var i = 0, il = bodies.length; i < il; i++) { var body = bodies[i].body; var child = this.children[i]; var tr = body.getCenterOfMassTransform(); var origin = tr.getOrigin(); var rotation = tr.getRotation(); child.position.set(origin.x(), origin.y(), origin.z()).applyMatrix4(_matrixWorldInv); child.quaternion.setFromRotationMatrix(_matrixWorldInv).multiply(_quaternion.set(rotation.x(), rotation.y(), rotation.z(), rotation.w())); } } this.matrix.copy(mesh.matrixWorld).decompose(_position, _quaternion, _scale).compose(_position, _quaternion, _scale.set(1, 1, 1)); super.updateMatrixWorld(force); } _init() { var bodies = this.physics.bodies; function createGeometry(param2) { switch (param2.shapeType) { case 0: return new SphereGeometry(param2.width, 16, 8); case 1: return new BoxGeometry(param2.width * 2, param2.height * 2, param2.depth * 2, 8, 8, 8); case 2: return new CapsuleGeometry(param2.width, param2.height, 8, 16); default: return null; } } for (var i = 0, il = bodies.length; i < il; i++) { var param = bodies[i].params; this.add(new Mesh(createGeometry(param), this.materials[param.type])); } } }; //#endregion //#region node_modules/three-stdlib/animation/MMDAnimationHelper.js var MMDAnimationHelper = class { /** * @param {Object} params - (optional) * @param {boolean} params.sync - Whether animation durations of added objects are synched. Default is true. * @param {Number} params.afterglow - Default is 0.0. * @param {boolean} params.resetPhysicsOnLoop - Default is true. */ constructor(params = {}) { this.meshes = []; this.camera = null; this.cameraTarget = new Object3D(); this.cameraTarget.name = "target"; this.audio = null; this.audioManager = null; this.objects = /* @__PURE__ */ new WeakMap(); this.configuration = { sync: params.sync !== void 0 ? params.sync : true, afterglow: params.afterglow !== void 0 ? params.afterglow : 0, resetPhysicsOnLoop: params.resetPhysicsOnLoop !== void 0 ? params.resetPhysicsOnLoop : true, pmxAnimation: params.pmxAnimation !== void 0 ? params.pmxAnimation : false }; this.enabled = { animation: true, ik: true, grant: true, physics: true, cameraAnimation: true }; this.onBeforePhysics = function() {}; this.sharedPhysics = false; this.masterPhysics = null; } /** * Adds an Three.js Object to helper and setups animation. * The anmation durations of added objects are synched * if this.configuration.sync is true. * * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object * @param {Object} params - (optional) * @param {THREE.AnimationClip|Array} params.animation - Only for THREE.SkinnedMesh and THREE.Camera. Default is undefined. * @param {boolean} params.physics - Only for THREE.SkinnedMesh. Default is true. * @param {Integer} params.warmup - Only for THREE.SkinnedMesh and physics is true. Default is 60. * @param {Number} params.unitStep - Only for THREE.SkinnedMesh and physics is true. Default is 1 / 65. * @param {Integer} params.maxStepNum - Only for THREE.SkinnedMesh and physics is true. Default is 3. * @param {Vector3} params.gravity - Only for THREE.SkinnedMesh and physics is true. Default ( 0, - 9.8 * 10, 0 ). * @param {Number} params.delayTime - Only for THREE.Audio. Default is 0.0. * @return {MMDAnimationHelper} */ add(object, params = {}) { if (object.isSkinnedMesh) this._addMesh(object, params); else if (object.isCamera) this._setupCamera(object, params); else if (object.type === "Audio") this._setupAudio(object, params); else throw new Error("THREE.MMDAnimationHelper.add: accepts only THREE.SkinnedMesh or THREE.Camera or THREE.Audio instance."); if (this.configuration.sync) this._syncDuration(); return this; } /** * Removes an Three.js Object from helper. * * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object * @return {MMDAnimationHelper} */ remove(object) { if (object.isSkinnedMesh) this._removeMesh(object); else if (object.isCamera) this._clearCamera(object); else if (object.type === "Audio") this._clearAudio(object); else throw new Error("THREE.MMDAnimationHelper.remove: accepts only THREE.SkinnedMesh or THREE.Camera or THREE.Audio instance."); if (this.configuration.sync) this._syncDuration(); return this; } /** * Updates the animation. * * @param {Number} delta * @return {MMDAnimationHelper} */ update(delta) { if (this.audioManager !== null) this.audioManager.control(delta); for (let i = 0; i < this.meshes.length; i++) this._animateMesh(this.meshes[i], delta); if (this.sharedPhysics) this._updateSharedPhysics(delta); if (this.camera !== null) this._animateCamera(this.camera, delta); return this; } /** * Changes the pose of SkinnedMesh as VPD specifies. * * @param {THREE.SkinnedMesh} mesh * @param {Object} vpd - VPD content parsed MMDParser * @param {Object} params - (optional) * @param {boolean} params.resetPose - Default is true. * @param {boolean} params.ik - Default is true. * @param {boolean} params.grant - Default is true. * @return {MMDAnimationHelper} */ pose(mesh, vpd, params = {}) { if (params.resetPose !== false) mesh.pose(); const bones = mesh.skeleton.bones; const boneParams = vpd.bones; const boneNameDictionary = {}; for (let i = 0, il = bones.length; i < il; i++) boneNameDictionary[bones[i].name] = i; const vector = new Vector3(); const quaternion = new Quaternion(); for (let i = 0, il = boneParams.length; i < il; i++) { const boneParam = boneParams[i]; const boneIndex = boneNameDictionary[boneParam.name]; if (boneIndex === void 0) continue; const bone = bones[boneIndex]; bone.position.add(vector.fromArray(boneParam.translation)); bone.quaternion.multiply(quaternion.fromArray(boneParam.quaternion)); } mesh.updateMatrixWorld(true); if (this.configuration.pmxAnimation && mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === "pmx") { const sortedBonesData = this._sortBoneDataArray(mesh.geometry.userData.MMD.bones.slice()); const ikSolver = params.ik !== false ? this._createCCDIKSolver(mesh) : null; const grantSolver = params.grant !== false ? this.createGrantSolver(mesh) : null; this._animatePMXMesh(mesh, sortedBonesData, ikSolver, grantSolver); } else { if (params.ik !== false) this._createCCDIKSolver(mesh).update(); if (params.grant !== false) this.createGrantSolver(mesh).update(); } return this; } /** * Enabes/Disables an animation feature. * * @param {string} key * @param {boolean} enabled * @return {MMDAnimationHelper} */ enable(key, enabled) { if (this.enabled[key] === void 0) throw new Error("THREE.MMDAnimationHelper.enable: unknown key " + key); this.enabled[key] = enabled; if (key === "physics") for (let i = 0, il = this.meshes.length; i < il; i++) this._optimizeIK(this.meshes[i], enabled); return this; } /** * Creates an GrantSolver instance. * * @param {THREE.SkinnedMesh} mesh * @return {GrantSolver} */ createGrantSolver(mesh) { return new GrantSolver(mesh, mesh.geometry.userData.MMD.grants); } _addMesh(mesh, params) { if (this.meshes.indexOf(mesh) >= 0) throw new Error("THREE.MMDAnimationHelper._addMesh: SkinnedMesh '" + mesh.name + "' has already been added."); this.meshes.push(mesh); this.objects.set(mesh, { looped: false }); this._setupMeshAnimation(mesh, params.animation); if (params.physics !== false) this._setupMeshPhysics(mesh, params); return this; } _setupCamera(camera, params) { if (this.camera === camera) throw new Error("THREE.MMDAnimationHelper._setupCamera: Camera '" + camera.name + "' has already been set."); if (this.camera) this.clearCamera(this.camera); this.camera = camera; camera.add(this.cameraTarget); this.objects.set(camera, {}); if (params.animation !== void 0) this._setupCameraAnimation(camera, params.animation); return this; } _setupAudio(audio, params) { if (this.audio === audio) throw new Error("THREE.MMDAnimationHelper._setupAudio: Audio '" + audio.name + "' has already been set."); if (this.audio) this.clearAudio(this.audio); this.audio = audio; this.audioManager = new AudioManager(audio, params); this.objects.set(this.audioManager, { duration: this.audioManager.duration }); return this; } _removeMesh(mesh) { let found = false; let writeIndex = 0; for (let i = 0, il = this.meshes.length; i < il; i++) { if (this.meshes[i] === mesh) { this.objects.delete(mesh); found = true; continue; } this.meshes[writeIndex++] = this.meshes[i]; } if (!found) throw new Error("THREE.MMDAnimationHelper._removeMesh: SkinnedMesh '" + mesh.name + "' has not been added yet."); this.meshes.length = writeIndex; return this; } _clearCamera(camera) { if (camera !== this.camera) throw new Error("THREE.MMDAnimationHelper._clearCamera: Camera '" + camera.name + "' has not been set yet."); this.camera.remove(this.cameraTarget); this.objects.delete(this.camera); this.camera = null; return this; } _clearAudio(audio) { if (audio !== this.audio) throw new Error("THREE.MMDAnimationHelper._clearAudio: Audio '" + audio.name + "' has not been set yet."); this.objects.delete(this.audioManager); this.audio = null; this.audioManager = null; return this; } _setupMeshAnimation(mesh, animation) { const objects = this.objects.get(mesh); if (animation !== void 0) { const animations = Array.isArray(animation) ? animation : [animation]; objects.mixer = new AnimationMixer(mesh); for (let i = 0, il = animations.length; i < il; i++) objects.mixer.clipAction(animations[i]).play(); objects.mixer.addEventListener("loop", function(event) { const tracks = event.action._clip.tracks; if (tracks.length > 0 && tracks[0].name.slice(0, 6) !== ".bones") return; objects.looped = true; }); } objects.ikSolver = this._createCCDIKSolver(mesh); objects.grantSolver = this.createGrantSolver(mesh); return this; } _setupCameraAnimation(camera, animation) { const animations = Array.isArray(animation) ? animation : [animation]; const objects = this.objects.get(camera); objects.mixer = new AnimationMixer(camera); for (let i = 0, il = animations.length; i < il; i++) objects.mixer.clipAction(animations[i]).play(); } _setupMeshPhysics(mesh, params) { const objects = this.objects.get(mesh); if (params.world === void 0 && this.sharedPhysics) { const masterPhysics = this._getMasterPhysics(); if (masterPhysics !== null) world = masterPhysics.world; } objects.physics = this._createMMDPhysics(mesh, params); if (objects.mixer && params.animationWarmup !== false) { this._animateMesh(mesh, 0); objects.physics.reset(); } objects.physics.warmup(params.warmup !== void 0 ? params.warmup : 60); this._optimizeIK(mesh, true); } _animateMesh(mesh, delta) { const objects = this.objects.get(mesh); const mixer = objects.mixer; const ikSolver = objects.ikSolver; const grantSolver = objects.grantSolver; const physics = objects.physics; const looped = objects.looped; if (mixer && this.enabled.animation) { this._restoreBones(mesh); mixer.update(delta); this._saveBones(mesh); if (this.configuration.pmxAnimation && mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === "pmx") { if (!objects.sortedBonesData) objects.sortedBonesData = this._sortBoneDataArray(mesh.geometry.userData.MMD.bones.slice()); this._animatePMXMesh(mesh, objects.sortedBonesData, ikSolver && this.enabled.ik ? ikSolver : null, grantSolver && this.enabled.grant ? grantSolver : null); } else { if (ikSolver && this.enabled.ik) { mesh.updateMatrixWorld(true); ikSolver.update(); } if (grantSolver && this.enabled.grant) grantSolver.update(); } } if (looped === true && this.enabled.physics) { if (physics && this.configuration.resetPhysicsOnLoop) physics.reset(); objects.looped = false; } if (physics && this.enabled.physics && !this.sharedPhysics) { this.onBeforePhysics(mesh); physics.update(delta); } } _sortBoneDataArray(boneDataArray) { return boneDataArray.sort(function(a, b) { if (a.transformationClass !== b.transformationClass) return a.transformationClass - b.transformationClass; else return a.index - b.index; }); } _animatePMXMesh(mesh, sortedBonesData, ikSolver, grantSolver) { _quaternionIndex = 0; _grantResultMap.clear(); for (let i = 0, il = sortedBonesData.length; i < il; i++) updateOne(mesh, sortedBonesData[i].index, ikSolver, grantSolver); mesh.updateMatrixWorld(true); return this; } _animateCamera(camera, delta) { const mixer = this.objects.get(camera).mixer; if (mixer && this.enabled.cameraAnimation) { mixer.update(delta); camera.updateProjectionMatrix(); camera.up.set(0, 1, 0); camera.up.applyQuaternion(camera.quaternion); camera.lookAt(this.cameraTarget.position); } } _optimizeIK(mesh, physicsEnabled) { const iks = mesh.geometry.userData.MMD.iks; const bones = mesh.geometry.userData.MMD.bones; for (let i = 0, il = iks.length; i < il; i++) { const links = iks[i].links; for (let j = 0, jl = links.length; j < jl; j++) { const link = links[j]; if (physicsEnabled === true) link.enabled = bones[link.index].rigidBodyType > 0 ? false : true; else link.enabled = true; } } } _createCCDIKSolver(mesh) { if (CCDIKSolver === void 0) throw new Error("THREE.MMDAnimationHelper: Import CCDIKSolver."); return new CCDIKSolver(mesh, mesh.geometry.userData.MMD.iks); } _createMMDPhysics(mesh, params) { if (MMDPhysics === void 0) throw new Error("THREE.MMDPhysics: Import MMDPhysics."); return new MMDPhysics(mesh, mesh.geometry.userData.MMD.rigidBodies, mesh.geometry.userData.MMD.constraints, params); } _syncDuration() { let max = 0; const objects = this.objects; const meshes = this.meshes; const camera = this.camera; const audioManager = this.audioManager; for (let i = 0, il = meshes.length; i < il; i++) { const mixer = this.objects.get(meshes[i]).mixer; if (mixer === void 0) continue; for (let j = 0; j < mixer._actions.length; j++) { const clip = mixer._actions[j]._clip; if (!objects.has(clip)) objects.set(clip, { duration: clip.duration }); max = Math.max(max, objects.get(clip).duration); } } if (camera !== null) { const mixer = this.objects.get(camera).mixer; if (mixer !== void 0) for (let i = 0, il = mixer._actions.length; i < il; i++) { const clip = mixer._actions[i]._clip; if (!objects.has(clip)) objects.set(clip, { duration: clip.duration }); max = Math.max(max, objects.get(clip).duration); } } if (audioManager !== null) max = Math.max(max, objects.get(audioManager).duration); max += this.configuration.afterglow; for (let i = 0, il = this.meshes.length; i < il; i++) { const mixer = this.objects.get(this.meshes[i]).mixer; if (mixer === void 0) continue; for (let j = 0, jl = mixer._actions.length; j < jl; j++) mixer._actions[j]._clip.duration = max; } if (camera !== null) { const mixer = this.objects.get(camera).mixer; if (mixer !== void 0) for (let i = 0, il = mixer._actions.length; i < il; i++) mixer._actions[i]._clip.duration = max; } if (audioManager !== null) audioManager.duration = max; } _updatePropertyMixersBuffer(mesh) { const mixer = this.objects.get(mesh).mixer; const propertyMixers = mixer._bindings; const accuIndex = mixer._accuIndex; for (let i = 0, il = propertyMixers.length; i < il; i++) { const propertyMixer = propertyMixers[i]; const buffer = propertyMixer.buffer; const stride = propertyMixer.valueSize; const offset = (accuIndex + 1) * stride; propertyMixer.binding.getValue(buffer, offset); } } _saveBones(mesh) { const objects = this.objects.get(mesh); const bones = mesh.skeleton.bones; let backupBones = objects.backupBones; if (backupBones === void 0) { backupBones = new Float32Array(bones.length * 7); objects.backupBones = backupBones; } for (let i = 0, il = bones.length; i < il; i++) { const bone = bones[i]; bone.position.toArray(backupBones, i * 7); bone.quaternion.toArray(backupBones, i * 7 + 3); } } _restoreBones(mesh) { const backupBones = this.objects.get(mesh).backupBones; if (backupBones === void 0) return; const bones = mesh.skeleton.bones; for (let i = 0, il = bones.length; i < il; i++) { const bone = bones[i]; bone.position.fromArray(backupBones, i * 7); bone.quaternion.fromArray(backupBones, i * 7 + 3); } } _getMasterPhysics() { if (this.masterPhysics !== null) return this.masterPhysics; for (let i = 0, il = this.meshes.length; i < il; i++) { const physics = this.meshes[i].physics; if (physics !== void 0 && physics !== null) { this.masterPhysics = physics; return this.masterPhysics; } } return null; } _updateSharedPhysics(delta) { if (this.meshes.length === 0 || !this.enabled.physics || !this.sharedPhysics) return; const physics = this._getMasterPhysics(); if (physics === null) return; for (let i = 0, il = this.meshes.length; i < il; i++) { const p = this.meshes[i].physics; if (p !== null && p !== void 0) p.updateRigidBodies(); } physics.stepSimulation(delta); for (let i = 0, il = this.meshes.length; i < il; i++) { const p = this.meshes[i].physics; if (p !== null && p !== void 0) p.updateBones(); } } }; var _quaternions = []; var _quaternionIndex = 0; function getQuaternion() { if (_quaternionIndex >= _quaternions.length) _quaternions.push(new Quaternion()); return _quaternions[_quaternionIndex++]; } var _grantResultMap = /* @__PURE__ */ new Map(); function updateOne(mesh, boneIndex, ikSolver, grantSolver) { const bones = mesh.skeleton.bones; const boneData = mesh.geometry.userData.MMD.bones[boneIndex]; const bone = bones[boneIndex]; if (_grantResultMap.has(boneIndex)) return; const quaternion = getQuaternion(); _grantResultMap.set(boneIndex, quaternion.copy(bone.quaternion)); if (grantSolver && boneData.grant && !boneData.grant.isLocal && boneData.grant.affectRotation) { const parentIndex = boneData.grant.parentIndex; const ratio = boneData.grant.ratio; if (!_grantResultMap.has(parentIndex)) updateOne(mesh, parentIndex, ikSolver, grantSolver); grantSolver.addGrantRotation(bone, _grantResultMap.get(parentIndex), ratio); } if (ikSolver && boneData.ik) { mesh.updateMatrixWorld(true); ikSolver.updateOne(boneData.ik); const links = boneData.ik.links; for (let i = 0, il = links.length; i < il; i++) { const link = links[i]; if (link.enabled === false) continue; const linkIndex = link.index; if (_grantResultMap.has(linkIndex)) _grantResultMap.set(linkIndex, _grantResultMap.get(linkIndex).copy(bones[linkIndex].quaternion)); } } quaternion.copy(bone.quaternion); } var AudioManager = class { /** * @param {THREE.Audio} audio * @param {Object} params - (optional) * @param {Nuumber} params.delayTime */ constructor(audio, params = {}) { this.audio = audio; this.elapsedTime = 0; this.currentTime = 0; this.delayTime = params.delayTime !== void 0 ? params.delayTime : 0; this.audioDuration = this.audio.buffer.duration; this.duration = this.audioDuration + this.delayTime; } /** * @param {Number} delta * @return {AudioManager} */ control(delta) { this.elapsed += delta; this.currentTime += delta; if (this._shouldStopAudio()) this.audio.stop(); if (this._shouldStartAudio()) this.audio.play(); return this; } _shouldStartAudio() { if (this.audio.isPlaying) return false; while (this.currentTime >= this.duration) this.currentTime -= this.duration; if (this.currentTime < this.delayTime) return false; if (this.currentTime - this.delayTime > this.audioDuration) return false; return true; } _shouldStopAudio() { return this.audio.isPlaying && this.currentTime >= this.duration; } }; var _q$1 = /* @__PURE__ */ new Quaternion(); var GrantSolver = class { constructor(mesh, grants = []) { this.mesh = mesh; this.grants = grants; } /** * Solve all the grant bones * @return {GrantSolver} */ update() { const grants = this.grants; for (let i = 0, il = grants.length; i < il; i++) this.updateOne(grants[i]); return this; } /** * Solve a grant bone * @param {Object} grant - grant parameter * @return {GrantSolver} */ updateOne(grant) { const bones = this.mesh.skeleton.bones; const bone = bones[grant.index]; const parentBone = bones[grant.parentIndex]; if (grant.isLocal) { if (grant.affectPosition); if (grant.affectRotation); } else { if (grant.affectPosition); if (grant.affectRotation) this.addGrantRotation(bone, parentBone.quaternion, grant.ratio); } return this; } addGrantRotation(bone, q, ratio) { _q$1.set(0, 0, 0, 1); _q$1.slerp(q, ratio); bone.quaternion.multiply(_q$1); return this; } }; //#endregion //#region node_modules/three-stdlib/objects/BatchedMesh.js var __defProp$47 = Object.defineProperty; var __defNormalProp$47 = (obj, key, value) => key in obj ? __defProp$47(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$47 = (obj, key, value) => { __defNormalProp$47(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var ID_ATTR_NAME = "_batch_id_"; var _identityMatrix$1 = /* @__PURE__ */ new Matrix4(); var _zeroScaleMatrix = /* @__PURE__ */ (() => new Matrix4().set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1))(); var batchingParsVertex = ` #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 = ` #ifdef BATCHING mat4 batchingMatrix = getBatchingMatrix( ${ID_ATTR_NAME} ); #endif `; var batchingnormalVertex = ` #ifdef BATCHING objectNormal = vec4( batchingMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( batchingMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif `; var batchingVertex = ` #ifdef BATCHING transformed = ( batchingMatrix * vec4( transformed, 1.0 ) ).xyz; #endif `; function copyAttributeData(src, target, targetOffset = 0) { const itemSize = target.itemSize; if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) { const vertexCount = src.count; for (let i = 0; i < vertexCount; i++) for (let c = 0; c < itemSize; c++) target.setComponent(i + targetOffset, c, src.getComponent(i, c)); } else target.array.set(src.array, targetOffset * itemSize); target.needsUpdate = true; } var BatchedMesh = class extends Mesh { constructor(maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) { super(new BufferGeometry(), material); __publicField$47(this, "_vertexStarts"); __publicField$47(this, "_vertexCounts"); __publicField$47(this, "_indexStarts"); __publicField$47(this, "_indexCounts"); __publicField$47(this, "_reservedRanges"); __publicField$47(this, "_visible"); __publicField$47(this, "_active"); __publicField$47(this, "_maxGeometryCount"); __publicField$47(this, "_maxVertexCount"); __publicField$47(this, "_maxIndexCount"); __publicField$47(this, "_geometryInitialized"); __publicField$47(this, "_geometryCount"); __publicField$47(this, "_matrices"); __publicField$47(this, "_matricesTexture"); __publicField$47(this, "_customUniforms"); this._vertexStarts = []; this._vertexCounts = []; this._indexStarts = []; this._indexCounts = []; this._reservedRanges = []; this._visible = []; this._active = []; this._maxGeometryCount = maxGeometryCount; this._maxVertexCount = maxVertexCount; this._maxIndexCount = maxIndexCount; this._geometryInitialized = false; this._geometryCount = 0; this._matrices = []; this._matricesTexture = null; this.frustumCulled = false; this._customUniforms = { batchingTexture: { value: null } }; this._initMatricesTexture(); this._initShader(); this.onBeforeRender = function() { if (this.material.defines) this.material.defines.BATCHING = true; }; this.onAfterRender = function() { if (this.material.defines) this.material.defines.BATCHING = false; }; } _initMatricesTexture() { let size = Math.sqrt(this._maxGeometryCount * 4); size = MathUtils.ceilPowerOfTwo(size); size = Math.max(size, 4); const matricesTexture = new DataTexture(new Float32Array(size * size * 4), size, size, RGBAFormat, FloatType); this._matricesTexture = matricesTexture; this._customUniforms.batchingTexture.value = this._matricesTexture; } _initShader() { const material = this.material; const currentOnBeforeCompile = material.onBeforeCompile; const customUniforms = this._customUniforms; material.onBeforeCompile = function onBeforeCompile(parameters, renderer) { parameters.vertexShader = parameters.vertexShader.replace("#include ", "#include \n" + batchingParsVertex).replace("#include ", "#include \n" + batchingbaseVertex).replace("#include ", "#include \n" + batchingnormalVertex).replace("#include ", "#include \n" + batchingVertex); for (const uniformName in customUniforms) parameters.uniforms[uniformName] = customUniforms[uniformName]; currentOnBeforeCompile.call(this, parameters, renderer); }; material.defines = material.defines || {}; material.defines.BATCHING = false; } _initializeGeometry(reference) { const geometry = this.geometry; const maxVertexCount = this._maxVertexCount; const maxGeometryCount = this._maxGeometryCount; const maxIndexCount = this._maxIndexCount; if (this._geometryInitialized === false) { for (const attributeName in reference.attributes) { const srcAttribute = reference.getAttribute(attributeName); const { array, itemSize, normalized } = srcAttribute; const dstArray = new array.constructor(maxVertexCount * itemSize); const dstAttribute = new srcAttribute.constructor(dstArray, itemSize, normalized); dstAttribute.setUsage(srcAttribute.usage); geometry.setAttribute(attributeName, dstAttribute); } if (reference.getIndex() !== null) { const indexArray = maxVertexCount > 65536 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount); geometry.setIndex(new BufferAttribute(indexArray, 1)); } const idArray = maxGeometryCount > 65536 ? new Uint32Array(maxVertexCount) : new Uint16Array(maxVertexCount); geometry.setAttribute(ID_ATTR_NAME, new BufferAttribute(idArray, 1)); this._geometryInitialized = true; } } _validateGeometry(geometry) { if (geometry.getAttribute(ID_ATTR_NAME)) throw new Error(`BatchedMesh: Geometry cannot use attribute "${ID_ATTR_NAME}"`); const batchGeometry = this.geometry; if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) throw new Error("BatchedMesh: All geometries must consistently have \"index\"."); for (const attributeName in batchGeometry.attributes) { if (attributeName === ID_ATTR_NAME) continue; if (!geometry.hasAttribute(attributeName)) throw new Error(`BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`); const srcAttribute = geometry.getAttribute(attributeName); const dstAttribute = batchGeometry.getAttribute(attributeName); if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value."); } } getGeometryCount() { return this._geometryCount; } getVertexCount() { const reservedRanges = this._reservedRanges; if (reservedRanges.length === 0) return 0; else { const finalRange = reservedRanges[reservedRanges.length - 1]; return finalRange.vertexStart + finalRange.vertexCount; } } getIndexCount() { const reservedRanges = this._reservedRanges; if (this.geometry.getIndex() === null || reservedRanges.length === 0) return 0; else { const finalRange = reservedRanges[reservedRanges.length - 1]; return finalRange.indexStart + finalRange.indexCount; } } addGeometry(geometry, vertexCount = -1, indexCount = -1) { this._initializeGeometry(geometry); this._validateGeometry(geometry); if (this._geometryCount >= this._maxGeometryCount) throw new Error("BatchedMesh: Maximum geometry count reached."); const range = { vertexStart: -1, vertexCount: -1, indexStart: -1, indexCount: -1 }; let lastRange = null; const reservedRanges = this._reservedRanges; if (this._geometryCount !== 0) lastRange = reservedRanges[reservedRanges.length - 1]; if (vertexCount === -1) range.vertexCount = geometry.getAttribute("position").count; else range.vertexCount = vertexCount; if (lastRange === null) range.vertexStart = 0; else range.vertexStart = lastRange.vertexStart + lastRange.vertexCount; if (geometry.getIndex() !== null) { if (indexCount === -1) range.indexCount = geometry.getIndex().count; else range.indexCount = indexCount; if (lastRange === null) range.indexStart = 0; else range.indexStart = lastRange.indexStart + lastRange.indexCount; } if (range.indexStart !== -1 && range.indexStart + range.indexCount > this._maxIndexCount || range.vertexStart + range.vertexCount > this._maxVertexCount) throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size."); const indexCounts = this._indexCounts; const indexStarts = this._indexStarts; const vertexCounts = this._vertexCounts; const vertexStarts = this._vertexStarts; const visible = this._visible; const active = this._active; const matricesTexture = this._matricesTexture; const matrices = this._matrices; const matricesArray = this._matricesTexture.image.data; visible.push(true); active.push(true); const geometryId = this._geometryCount; this._geometryCount++; matrices.push(new Matrix4()); _identityMatrix$1.toArray(matricesArray, geometryId * 16); matricesTexture.needsUpdate = true; reservedRanges.push(range); vertexStarts.push(range.vertexStart); vertexCounts.push(range.vertexCount); if (geometry.getIndex() !== null) { indexStarts.push(range.indexCount); indexCounts.push(range.indexCount); } const idAttribute = this.geometry.getAttribute(ID_ATTR_NAME); for (let i = 0; i < range.vertexCount; i++) idAttribute.setX(range.vertexStart + i, geometryId); idAttribute.needsUpdate = true; this.setGeometryAt(geometryId, geometry); return geometryId; } /** * @deprecated use `addGeometry` instead. */ applyGeometry(geometry) { return this.addGeometry(geometry); } setGeometryAt(id, geometry) { if (id >= this._geometryCount) throw new Error("BatchedMesh: Maximum geometry count reached."); this._validateGeometry(geometry); const range = this._reservedRanges[id]; if (geometry.getIndex() !== null && geometry.getIndex().count > range.indexCount || geometry.attributes.position.count > range.vertexCount) throw new Error("BatchedMesh: Reserved space not large enough for provided geometry."); const batchGeometry = this.geometry; const srcPositionAttribute = geometry.getAttribute("position"); const hasIndex = batchGeometry.getIndex() !== null; const dstIndex = batchGeometry.getIndex(); const srcIndex = geometry.getIndex(); const vertexStart = range.vertexStart; const vertexCount = range.vertexCount; for (const attributeName in batchGeometry.attributes) { if (attributeName === ID_ATTR_NAME) continue; const srcAttribute = geometry.getAttribute(attributeName); const dstAttribute = batchGeometry.getAttribute(attributeName); copyAttributeData(srcAttribute, dstAttribute, vertexStart); const itemSize = srcAttribute.itemSize; for (let i = srcAttribute.count, l = vertexCount; i < l; i++) { const index = vertexStart + i; for (let c = 0; c < itemSize; c++) dstAttribute.setComponent(index, c, 0); } dstAttribute.needsUpdate = true; } this._vertexCounts[id] = srcPositionAttribute.count; if (hasIndex) { const indexStart = range.indexStart; for (let i = 0; i < srcIndex.count; i++) dstIndex.setX(indexStart + i, vertexStart + srcIndex.getX(i)); for (let i = srcIndex.count, l = range.indexCount; i < l; i++) dstIndex.setX(indexStart + i, vertexStart); dstIndex.needsUpdate = true; this._indexCounts[id] = srcIndex.count; } return id; } deleteGeometry(geometryId) { const active = this._active; const matricesTexture = this._matricesTexture; const matricesArray = matricesTexture.image.data; if (geometryId >= active.length || active[geometryId] === false) return this; active[geometryId] = false; _zeroScaleMatrix.toArray(matricesArray, geometryId * 16); matricesTexture.needsUpdate = true; return this; } optimize() { throw new Error("BatchedMesh: Optimize function not implemented."); } setMatrixAt(geometryId, matrix) { const visible = this._visible; const active = this._active; const matricesTexture = this._matricesTexture; const matrices = this._matrices; const matricesArray = matricesTexture.image.data; if (geometryId >= matrices.length || active[geometryId] === false) return this; if (visible[geometryId] === true) { matrix.toArray(matricesArray, geometryId * 16); matricesTexture.needsUpdate = true; } matrices[geometryId].copy(matrix); return this; } getMatrixAt(geometryId, matrix) { const matrices = this._matrices; const active = this._active; if (geometryId >= matrices.length || active[geometryId] === false) return matrix; return matrix.copy(matrices[geometryId]); } setVisibleAt(geometryId, value) { const visible = this._visible; const active = this._active; const matricesTexture = this._matricesTexture; const matrices = this._matrices; const matricesArray = matricesTexture.image.data; if (geometryId >= visible.length || active[geometryId] === false || visible[geometryId] === value) return this; if (value === true) matrices[geometryId].toArray(matricesArray, geometryId * 16); else _zeroScaleMatrix.toArray(matricesArray, geometryId * 16); matricesTexture.needsUpdate = true; visible[geometryId] = value; return this; } getVisibleAt(geometryId) { const visible = this._visible; const active = this._active; if (geometryId >= visible.length || active[geometryId] === false) return false; return visible[geometryId]; } raycast() { console.warn("BatchedMesh: Raycast function not implemented."); } copy() { throw new Error("BatchedMesh: Copy function not implemented."); } toJSON() { throw new Error("BatchedMesh: toJSON function not implemented."); } dispose() { this.geometry.dispose(); this._matricesTexture.dispose(); this._matricesTexture = null; return this; } }; //#endregion //#region node_modules/three-stdlib/objects/Reflector.js var __defProp$46 = Object.defineProperty; var __defNormalProp$46 = (obj, key, value) => key in obj ? __defProp$46(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$46 = (obj, key, value) => { __defNormalProp$46(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Reflector = /* @__PURE__ */ (() => { const _Reflector = class extends Mesh { constructor(geometry, options = {}) { super(geometry); 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 normal = new Vector3(); const reflectorWorldPosition = new Vector3(); const cameraWorldPosition = new Vector3(); const rotationMatrix = new Matrix4(); const lookAtPosition = new Vector3(0, 0, -1); const clipPlane = new Vector4(); const view = new Vector3(); const target = 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); rotationMatrix.extractRotation(scope.matrixWorld); normal.set(0, 0, 1); normal.applyMatrix4(rotationMatrix); view.subVectors(reflectorWorldPosition, cameraWorldPosition); if (view.dot(normal) > 0) return; view.reflect(normal).negate(); view.add(reflectorWorldPosition); rotationMatrix.extractRotation(camera.matrixWorld); lookAtPosition.set(0, 0, -1); lookAtPosition.applyMatrix4(rotationMatrix); lookAtPosition.add(cameraWorldPosition); target.subVectors(reflectorWorldPosition, lookAtPosition); target.reflect(normal).negate(); target.add(reflectorWorldPosition); virtualCamera.position.copy(view); virtualCamera.up.set(0, 1, 0); virtualCamera.up.applyMatrix4(rotationMatrix); virtualCamera.up.reflect(normal); virtualCamera.lookAt(target); virtualCamera.far = camera.far; virtualCamera.updateMatrixWorld(); virtualCamera.projectionMatrix.copy(camera.projectionMatrix); textureMatrix.set(.5, 0, 0, .5, 0, .5, 0, .5, 0, 0, .5, .5, 0, 0, 0, 1); textureMatrix.multiply(virtualCamera.projectionMatrix); textureMatrix.multiply(virtualCamera.matrixWorldInverse); textureMatrix.multiply(scope.matrixWorld); reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition); reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse); clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant); const projectionMatrix = virtualCamera.projectionMatrix; 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 = 0; 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; __publicField$46(Reflector2, "ReflectorShader", { uniforms: { color: { value: null }, tDiffuse: { value: null }, textureMatrix: { value: null } }, vertexShader: ` 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: ` 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; })(); //#endregion //#region node_modules/three-stdlib/objects/Refractor.js var __defProp$45 = Object.defineProperty; var __defNormalProp$45 = (obj, key, value) => key in obj ? __defProp$45(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$45 = (obj, key, value) => { __defNormalProp$45(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Refractor = /* @__PURE__ */ (() => { const _Refractor = class extends Mesh { constructor(geometry, options = {}) { super(geometry); this.isRefractor = true; this.type = "Refractor"; this.camera = new PerspectiveCamera(); const scope = this; const color = options.color !== void 0 ? new Color(options.color) : new Color(8355711); const textureWidth = options.textureWidth || 512; const textureHeight = options.textureHeight || 512; const clipBias = options.clipBias || 0; const shader = options.shader || _Refractor.RefractorShader; const multisample = options.multisample !== void 0 ? options.multisample : 4; const virtualCamera = this.camera; virtualCamera.matrixAutoUpdate = false; virtualCamera.userData.refractor = true; const refractorPlane = new Plane(); const textureMatrix = new Matrix4(); const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType }); this.material = new ShaderMaterial({ uniforms: UniformsUtils.clone(shader.uniforms), vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader, transparent: true }); 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 rotationMatrix = new Matrix4(); const view = new Vector3(); const normal = new Vector3(); return function visible2(camera) { refractorWorldPosition.setFromMatrixPosition(scope.matrixWorld); cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); view.subVectors(refractorWorldPosition, cameraWorldPosition); rotationMatrix.extractRotation(scope.matrixWorld); normal.set(0, 0, 1); normal.applyMatrix4(rotationMatrix); return view.dot(normal) < 0; }; }(); const updateRefractorPlane = function() { const normal = new Vector3(); const position = new Vector3(); const quaternion = new Quaternion(); const scale = new Vector3(); return function updateRefractorPlane2() { scope.matrixWorld.decompose(position, quaternion, scale); normal.set(0, 0, 1).applyQuaternion(quaternion).normalize(); normal.negate(); refractorPlane.setFromNormalAndCoplanarPoint(normal, position); }; }(); 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(.5, 0, 0, .5, 0, .5, 0, .5, 0, 0, .5, .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 = 0; 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; __publicField$45(Refractor2, "RefractorShader", { uniforms: { color: { value: null }, tDiffuse: { value: null }, textureMatrix: { value: null } }, vertexShader: ` uniform mat4 textureMatrix; varying vec4 vUv; void main() { vUv = textureMatrix * vec4( position, 1.0 ); gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: ` 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; })(); //#endregion //#region node_modules/three-stdlib/objects/ShadowMesh.js var _shadowMatrix = /* @__PURE__ */ new Matrix4(); var ShadowMesh = class extends Mesh { constructor(mesh) { const shadowMaterial = new MeshBasicMaterial({ color: 0, transparent: true, opacity: .6, depthWrite: false, stencilWrite: true, stencilFunc: 514, stencilRef: 0, stencilZPass: IncrementStencilOp }); super(mesh.geometry, shadowMaterial); this.isShadowMesh = true; this.meshMatrix = mesh.matrixWorld; this.frustumCulled = false; this.matrixAutoUpdate = false; } update(plane, lightPosition4D) { const dot = plane.normal.x * lightPosition4D.x + plane.normal.y * lightPosition4D.y + plane.normal.z * lightPosition4D.z + -plane.constant * lightPosition4D.w; const sme = _shadowMatrix.elements; sme[0] = dot - lightPosition4D.x * plane.normal.x; sme[4] = -lightPosition4D.x * plane.normal.y; sme[8] = -lightPosition4D.x * plane.normal.z; sme[12] = -lightPosition4D.x * -plane.constant; sme[1] = -lightPosition4D.y * plane.normal.x; sme[5] = dot - lightPosition4D.y * plane.normal.y; sme[9] = -lightPosition4D.y * plane.normal.z; sme[13] = -lightPosition4D.y * -plane.constant; sme[2] = -lightPosition4D.z * plane.normal.x; sme[6] = -lightPosition4D.z * plane.normal.y; sme[10] = dot - lightPosition4D.z * plane.normal.z; sme[14] = -lightPosition4D.z * -plane.constant; sme[3] = -lightPosition4D.w * plane.normal.x; sme[7] = -lightPosition4D.w * plane.normal.y; sme[11] = -lightPosition4D.w * plane.normal.z; sme[15] = dot - lightPosition4D.w * -plane.constant; this.matrix.multiplyMatrices(_shadowMatrix, this.meshMatrix); } }; //#endregion //#region node_modules/three-stdlib/objects/Lensflare.js var Lensflare = /* @__PURE__ */ (() => { 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 geometry = Lensflare2.Geometry; const material1a = new RawShaderMaterial({ uniforms: { scale: { value: null }, screenPosition: { value: null } }, vertexShader: ` 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: ` 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: ` 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: ` precision highp float; uniform sampler2D map; varying vec2 vUV; void main() { gl_FragColor = texture2D( map, vUV ); }`, depthTest: false, depthWrite: false, transparent: false }); const mesh1 = new Mesh(geometry, material1a); const elements = []; const shader = LensflareElement.Shader; const material2 = new RawShaderMaterial({ 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: 2, transparent: true, depthWrite: false }); const mesh2 = new Mesh(geometry, material2); this.addElement = function(element) { elements.push(element); }; const scale = 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 size = 16 / viewport.w; scale.set(size * invAspect, size); 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 = scale; uniforms["screenPosition"].value = positionScreen; renderer.renderBufferDirect(camera, null, geometry, material1a, mesh1, null); renderer.copyFramebufferToTexture(screenPositionPixels, occlusionMap); uniforms = material1b.uniforms; uniforms["scale"].value = scale; uniforms["screenPosition"].value = positionScreen; renderer.renderBufferDirect(camera, null, geometry, material1b, mesh1, null); const vecX = -positionScreen.x * 2; const vecY = -positionScreen.y * 2; for (let i = 0, l = elements.length; i < l; i++) { const element = elements[i]; const uniforms2 = material2.uniforms; uniforms2["color"].value.copy(element.color); uniforms2["map"].value = element.texture; uniforms2["screenPosition"].value.x = positionScreen.x + vecX * element.distance; uniforms2["screenPosition"].value.y = positionScreen.y + vecY * element.distance; size = element.size / viewport.w; const invAspect2 = viewport.w / viewport.z; uniforms2["scale"].value.set(size * invAspect2, size); material2.uniformsNeedUpdate = true; renderer.renderBufferDirect(camera, null, geometry, material2, mesh2, null); } } }; this.dispose = function() { material1a.dispose(); material1b.dispose(); material2.dispose(); tempMap.dispose(); occlusionMap.dispose(); for (let i = 0, l = elements.length; i < l; i++) elements[i].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 = /* @__PURE__ */ (() => { class LensflareElement2 { constructor(texture, size = 1, distance = 0, color = new Color(16777215)) { this.texture = texture; this.size = size; this.distance = distance; this.color = color; } } LensflareElement2.Shader = { uniforms: { map: { value: null }, occlusionMap: { value: null }, color: { value: null }, scale: { value: null }, screenPosition: { value: null } }, vertexShader: ` 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: ` 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; })(); //#endregion //#region node_modules/three-stdlib/objects/Water.js var Water = class extends Mesh { constructor(geometry, options = {}) { super(geometry); this.isWater = true; const scope = this; const textureWidth = options.textureWidth !== void 0 ? options.textureWidth : 512; const textureHeight = options.textureHeight !== void 0 ? options.textureHeight : 512; const clipBias = options.clipBias !== void 0 ? options.clipBias : 0; const alpha = options.alpha !== void 0 ? options.alpha : 1; const time = options.time !== void 0 ? options.time : 0; const normalSampler = options.waterNormals !== void 0 ? options.waterNormals : null; const sunDirection = options.sunDirection !== void 0 ? options.sunDirection : new Vector3(.70707, .70707, 0); const sunColor = new Color(options.sunColor !== void 0 ? options.sunColor : 16777215); const waterColor = new Color(options.waterColor !== void 0 ? options.waterColor : 8355711); const eye = options.eye !== void 0 ? options.eye : new Vector3(0, 0, 0); const distortionScale = options.distortionScale !== void 0 ? options.distortionScale : 20; const side = options.side !== void 0 ? options.side : 0; const fog = options.fog !== void 0 ? options.fog : false; const mirrorPlane = new Plane(); const normal = new Vector3(); const mirrorWorldPosition = new Vector3(); const cameraWorldPosition = new Vector3(); const rotationMatrix = new Matrix4(); const lookAtPosition = new Vector3(0, 0, -1); const clipPlane = new Vector4(); const view = new Vector3(); const target = new Vector3(); const q = new Vector4(); const textureMatrix = new Matrix4(); const mirrorCamera = new PerspectiveCamera(); const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight); const mirrorShader = { uniforms: UniformsUtils.merge([ UniformsLib["fog"], UniformsLib["lights"], { normalSampler: { value: null }, mirrorSampler: { value: null }, alpha: { value: 1 }, time: { value: 0 }, size: { value: 1 }, distortionScale: { value: 20 }, textureMatrix: { value: new Matrix4() }, sunColor: { value: new Color(8355711) }, sunDirection: { value: new Vector3(.70707, .70707, 0) }, eye: { value: new Vector3() }, waterColor: { value: new Color(5592405) } } ]), vertexShader: ` uniform mat4 textureMatrix; uniform float time; varying vec4 mirrorCoord; varying vec4 worldPosition; #include #include #include #include void main() { mirrorCoord = modelMatrix * vec4( position, 1.0 ); worldPosition = mirrorCoord.xyzw; mirrorCoord = textureMatrix * mirrorCoord; vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); gl_Position = projectionMatrix * mvPosition; #include #include #include #include #include }`, fragmentShader: ` uniform sampler2D mirrorSampler; uniform float alpha; uniform float time; uniform float size; uniform float distortionScale; uniform sampler2D normalSampler; uniform vec3 sunColor; uniform vec3 sunDirection; uniform vec3 eye; uniform vec3 waterColor; varying vec4 mirrorCoord; varying vec4 worldPosition; vec4 getNoise( vec2 uv ) { vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0); vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 ); vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 ); vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 ); vec4 noise = texture2D( normalSampler, uv0 ) + texture2D( normalSampler, uv1 ) + texture2D( normalSampler, uv2 ) + texture2D( normalSampler, uv3 ); return noise * 0.5 - 1.0; } void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) { vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) ); float direction = max( 0.0, dot( eyeDirection, reflection ) ); specularColor += pow( direction, shiny ) * sunColor * spec; diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse; } #include #include #include #include #include #include #include #include void main() { #include vec4 noise = getNoise( worldPosition.xz * size ); vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) ); vec3 diffuseLight = vec3(0.0); vec3 specularLight = vec3(0.0); vec3 worldToEye = eye-worldPosition.xyz; vec3 eyeDirection = normalize( worldToEye ); sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight ); float distance = length(worldToEye); vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale; vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) ); float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 ); float rf0 = 0.3; float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 ); vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor; vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance); vec3 outgoingLight = albedo; gl_FragColor = vec4( outgoingLight, alpha ); #include #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}> #include }` }; const material = new ShaderMaterial({ fragmentShader: mirrorShader.fragmentShader, vertexShader: mirrorShader.vertexShader, uniforms: UniformsUtils.clone(mirrorShader.uniforms), lights: true, side, fog }); material.uniforms["mirrorSampler"].value = renderTarget.texture; material.uniforms["textureMatrix"].value = textureMatrix; material.uniforms["alpha"].value = alpha; material.uniforms["time"].value = time; material.uniforms["normalSampler"].value = normalSampler; material.uniforms["sunColor"].value = sunColor; material.uniforms["waterColor"].value = waterColor; material.uniforms["sunDirection"].value = sunDirection; material.uniforms["distortionScale"].value = distortionScale; material.uniforms["eye"].value = eye; scope.material = material; scope.onBeforeRender = function(renderer, scene, camera) { mirrorWorldPosition.setFromMatrixPosition(scope.matrixWorld); cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); rotationMatrix.extractRotation(scope.matrixWorld); normal.set(0, 0, 1); normal.applyMatrix4(rotationMatrix); view.subVectors(mirrorWorldPosition, cameraWorldPosition); if (view.dot(normal) > 0) return; view.reflect(normal).negate(); view.add(mirrorWorldPosition); rotationMatrix.extractRotation(camera.matrixWorld); lookAtPosition.set(0, 0, -1); lookAtPosition.applyMatrix4(rotationMatrix); lookAtPosition.add(cameraWorldPosition); target.subVectors(mirrorWorldPosition, lookAtPosition); target.reflect(normal).negate(); target.add(mirrorWorldPosition); mirrorCamera.position.copy(view); mirrorCamera.up.set(0, 1, 0); mirrorCamera.up.applyMatrix4(rotationMatrix); mirrorCamera.up.reflect(normal); mirrorCamera.lookAt(target); mirrorCamera.far = camera.far; mirrorCamera.updateMatrixWorld(); mirrorCamera.projectionMatrix.copy(camera.projectionMatrix); textureMatrix.set(.5, 0, 0, .5, 0, .5, 0, .5, 0, 0, .5, .5, 0, 0, 0, 1); textureMatrix.multiply(mirrorCamera.projectionMatrix); textureMatrix.multiply(mirrorCamera.matrixWorldInverse); mirrorPlane.setFromNormalAndCoplanarPoint(normal, mirrorWorldPosition); mirrorPlane.applyMatrix4(mirrorCamera.matrixWorldInverse); clipPlane.set(mirrorPlane.normal.x, mirrorPlane.normal.y, mirrorPlane.normal.z, mirrorPlane.constant); const projectionMatrix = mirrorCamera.projectionMatrix; 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; eye.setFromMatrixPosition(camera.matrixWorld); const currentRenderTarget = renderer.getRenderTarget(); const currentXrEnabled = renderer.xr.enabled; const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; scope.visible = false; renderer.xr.enabled = false; renderer.shadowMap.autoUpdate = false; renderer.setRenderTarget(renderTarget); renderer.state.buffers.depth.setMask(true); if (renderer.autoClear === false) renderer.clear(); renderer.render(scene, mirrorCamera); scope.visible = true; renderer.xr.enabled = currentXrEnabled; renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; renderer.setRenderTarget(currentRenderTarget); const viewport = camera.viewport; if (viewport !== void 0) renderer.state.viewport(viewport); }; } }; //#endregion //#region node_modules/three-stdlib/objects/MarchingCubes.js var MarchingCubes = class extends Mesh { constructor(resolution, material, enableUvs = false, enableColors = false, maxPolyCount = 1e4) { const geometry = new BufferGeometry(); super(geometry, material); this.isMarchingCubes = true; const scope = this; const vlist = new Float32Array(36); const nlist = new Float32Array(36); const clist = new Float32Array(36); this.enableUvs = enableUvs; this.enableColors = enableColors; this.init = function(resolution2) { this.resolution = resolution2; this.isolation = 80; this.size = resolution2; this.size2 = this.size * this.size; this.size3 = this.size2 * this.size; this.halfsize = this.size / 2; this.delta = 2 / this.size; this.yd = this.size; this.zd = this.size2; this.field = new Float32Array(this.size3); this.normal_cache = new Float32Array(this.size3 * 3); this.palette = new Float32Array(this.size3 * 3); this.count = 0; const maxVertexCount = maxPolyCount * 3; this.positionArray = new Float32Array(maxVertexCount * 3); const positionAttribute = new BufferAttribute(this.positionArray, 3); positionAttribute.setUsage(DynamicDrawUsage); geometry.setAttribute("position", positionAttribute); this.normalArray = new Float32Array(maxVertexCount * 3); const normalAttribute = new BufferAttribute(this.normalArray, 3); normalAttribute.setUsage(DynamicDrawUsage); geometry.setAttribute("normal", normalAttribute); if (this.enableUvs) { this.uvArray = new Float32Array(maxVertexCount * 2); const uvAttribute = new BufferAttribute(this.uvArray, 2); uvAttribute.setUsage(DynamicDrawUsage); geometry.setAttribute("uv", uvAttribute); } if (this.enableColors) { this.colorArray = new Float32Array(maxVertexCount * 3); const colorAttribute = new BufferAttribute(this.colorArray, 3); colorAttribute.setUsage(DynamicDrawUsage); geometry.setAttribute("color", colorAttribute); } geometry.boundingSphere = new Sphere(new Vector3(), 1); }; function lerp(a, b, t) { return a + (b - a) * t; } 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] = lerp(nc[q + 0], nc[q + 3], mu); nlist[offset + 1] = lerp(nc[q + 1], nc[q + 4], mu); nlist[offset + 2] = lerp(nc[q + 2], nc[q + 5], mu); clist[offset + 0] = lerp(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); clist[offset + 1] = lerp(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); clist[offset + 2] = lerp(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 q2 = q + scope.yd * 3; nlist[offset + 0] = lerp(nc[q + 0], nc[q2 + 0], mu); nlist[offset + 1] = lerp(nc[q + 1], nc[q2 + 1], mu); nlist[offset + 2] = lerp(nc[q + 2], nc[q2 + 2], mu); clist[offset + 0] = lerp(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); clist[offset + 1] = lerp(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); clist[offset + 2] = lerp(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 q2 = q + scope.zd * 3; nlist[offset + 0] = lerp(nc[q + 0], nc[q2 + 0], mu); nlist[offset + 1] = lerp(nc[q + 1], nc[q2 + 1], mu); nlist[offset + 2] = lerp(nc[q + 2], nc[q2 + 2], mu); clist[offset + 0] = lerp(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu); clist[offset + 1] = lerp(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu); clist[offset + 2] = lerp(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 q1 = q + 1, qy = q + scope.yd, qz = q + scope.zd, q1y = q1 + scope.yd, q1z = q1 + scope.zd, qyz = q + scope.yd + scope.zd, q1yz = q1 + scope.yd + scope.zd; let cubeindex = 0; const field0 = scope.field[q], field1 = scope.field[q1], field2 = scope.field[qy], field3 = scope.field[q1y], field4 = scope.field[qz], field5 = scope.field[q1z], field6 = scope.field[qyz], field7 = scope.field[q1yz]; if (field0 < isol) cubeindex |= 1; if (field1 < isol) cubeindex |= 2; if (field2 < isol) cubeindex |= 8; if (field3 < isol) cubeindex |= 4; if (field4 < isol) cubeindex |= 16; if (field5 < isol) cubeindex |= 32; if (field6 < isol) cubeindex |= 128; if (field7 < isol) cubeindex |= 64; const bits = edgeTable[cubeindex]; if (bits === 0) return 0; const d = scope.delta, fx2 = fx + d, fy2 = fy + d, fz2 = fz + d; if (bits & 1) { compNorm(q); compNorm(q1); VIntX(q * 3, 0, isol, fx, fy, fz, field0, field1, q, q1); } if (bits & 2) { compNorm(q1); compNorm(q1y); VIntY(q1 * 3, 3, isol, fx2, fy, fz, field1, field3, q1, q1y); } if (bits & 4) { compNorm(qy); compNorm(q1y); VIntX(qy * 3, 6, isol, fx, fy2, fz, field2, field3, qy, q1y); } if (bits & 8) { compNorm(q); compNorm(qy); VIntY(q * 3, 9, isol, fx, fy, fz, field0, field2, q, qy); } if (bits & 16) { compNorm(qz); compNorm(q1z); VIntX(qz * 3, 12, isol, fx, fy, fz2, field4, field5, qz, q1z); } if (bits & 32) { compNorm(q1z); compNorm(q1yz); VIntY(q1z * 3, 15, isol, fx2, fy, fz2, field5, field7, q1z, q1yz); } if (bits & 64) { compNorm(qyz); compNorm(q1yz); VIntX(qyz * 3, 18, isol, fx, fy2, fz2, field6, field7, qyz, q1yz); } if (bits & 128) { compNorm(qz); compNorm(qyz); VIntY(qz * 3, 21, isol, fx, fy, fz2, field4, field6, qz, qyz); } if (bits & 256) { compNorm(q); compNorm(qz); VIntZ(q * 3, 24, isol, fx, fy, fz, field0, field4, q, qz); } if (bits & 512) { compNorm(q1); compNorm(q1z); VIntZ(q1 * 3, 27, isol, fx2, fy, fz, field1, field5, q1, q1z); } if (bits & 1024) { compNorm(q1y); compNorm(q1yz); VIntZ(q1y * 3, 30, isol, fx2, fy2, fz, field3, field7, q1y, q1yz); } if (bits & 2048) { compNorm(qy); compNorm(qyz); VIntZ(qy * 3, 33, isol, fx, fy2, fz, field2, field6, qy, qyz); } cubeindex <<= 4; let o1, o2, o3, numtris = 0, i = 0; while (triTable[cubeindex + i] != -1) { o1 = cubeindex + i; o2 = o1 + 1; o3 = o1 + 2; posnormtriv(vlist, nlist, clist, 3 * triTable[o1], 3 * triTable[o2], 3 * triTable[o3]); i += 3; numtris++; } return numtris; } function posnormtriv(pos, norm, colors, o1, o2, o3) { const c = scope.count * 3; scope.positionArray[c + 0] = pos[o1]; scope.positionArray[c + 1] = pos[o1 + 1]; scope.positionArray[c + 2] = pos[o1 + 2]; scope.positionArray[c + 3] = pos[o2]; scope.positionArray[c + 4] = pos[o2 + 1]; scope.positionArray[c + 5] = pos[o2 + 2]; scope.positionArray[c + 6] = pos[o3]; scope.positionArray[c + 7] = pos[o3 + 1]; scope.positionArray[c + 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[c + 0] = nx; scope.normalArray[c + 1] = ny; scope.normalArray[c + 2] = nz; scope.normalArray[c + 3] = nx; scope.normalArray[c + 4] = ny; scope.normalArray[c + 5] = nz; scope.normalArray[c + 6] = nx; scope.normalArray[c + 7] = ny; scope.normalArray[c + 8] = nz; } else { scope.normalArray[c + 0] = norm[o1 + 0]; scope.normalArray[c + 1] = norm[o1 + 1]; scope.normalArray[c + 2] = norm[o1 + 2]; scope.normalArray[c + 3] = norm[o2 + 0]; scope.normalArray[c + 4] = norm[o2 + 1]; scope.normalArray[c + 5] = norm[o2 + 2]; scope.normalArray[c + 6] = norm[o3 + 0]; scope.normalArray[c + 7] = norm[o3 + 1]; scope.normalArray[c + 8] = norm[o3 + 2]; } if (scope.enableUvs) { const d = scope.count * 2; scope.uvArray[d + 0] = pos[o1 + 0]; scope.uvArray[d + 1] = pos[o1 + 2]; scope.uvArray[d + 2] = pos[o2 + 0]; scope.uvArray[d + 3] = pos[o2 + 2]; scope.uvArray[d + 4] = pos[o3 + 0]; scope.uvArray[d + 5] = pos[o3 + 2]; } if (scope.enableColors) { scope.colorArray[c + 0] = colors[o1 + 0]; scope.colorArray[c + 1] = colors[o1 + 1]; scope.colorArray[c + 2] = colors[o1 + 2]; scope.colorArray[c + 3] = colors[o2 + 0]; scope.colorArray[c + 4] = colors[o2 + 1]; scope.colorArray[c + 5] = colors[o2 + 2]; scope.colorArray[c + 6] = colors[o3 + 0]; scope.colorArray[c + 7] = colors[o3 + 1]; scope.colorArray[c + 8] = colors[o3 + 2]; } scope.count += 3; } this.addBall = function(ballx, bally, ballz, strength, subtract, colors) { const sign = Math.sign(strength); strength = Math.abs(strength); const userDefineColor = !(colors === void 0 || colors === null); let ballColor = new Color(ballx, bally, ballz); if (userDefineColor) try { ballColor = colors instanceof Color ? colors : Array.isArray(colors) ? new Color(Math.min(Math.abs(colors[0]), 1), Math.min(Math.abs(colors[1]), 1), Math.min(Math.abs(colors[2]), 1)) : new Color(colors); } catch (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 size = this.size, yd = this.yd, zd = this.zd, field = this.field; let x, y, z, xx, val, xdiv, cxy, dist = size * Math.sqrt(strength / subtract); if (dist > size) dist = size; for (x = 0; x < dist; x++) { xdiv = x / size; xx = xdiv * xdiv; val = strength / (1e-4 + xx) - subtract; if (val > 0) for (y = 0; y < size; y++) { cxy = x + y * yd; for (z = 0; z < size; z++) field[zd * z + cxy] += val; } } }; this.addPlaneY = function(strength, subtract) { const size = this.size, yd = this.yd, zd = this.zd, field = this.field; let x, y, z, yy, val, ydiv, cy, cxy, dist = size * Math.sqrt(strength / subtract); if (dist > size) dist = size; for (y = 0; y < dist; y++) { ydiv = y / size; yy = ydiv * ydiv; val = strength / (1e-4 + yy) - subtract; if (val > 0) { cy = y * yd; for (x = 0; x < size; x++) { cxy = cy + x; for (z = 0; z < size; z++) field[zd * z + cxy] += val; } } } }; this.addPlaneZ = function(strength, subtract) { const size = this.size, yd = this.yd, zd = this.zd, field = this.field; let x, y, z, zz, val, zdiv, cz, cyz, dist = size * Math.sqrt(strength / subtract); if (dist > size) dist = size; for (z = 0; z < dist; z++) { zdiv = z / size; zz = zdiv * zdiv; val = strength / (1e-4 + zz) - subtract; if (val > 0) { cz = zd * z; for (y = 0; y < size; y++) { cyz = cz + y * yd; for (x = 0; x < size; x++) field[cyz + x] += val; } } } }; this.setCell = function(x, y, z, value) { const index = this.size2 * z + this.size * y + x; this.field[index] = value; }; this.getCell = function(x, y, z) { const index = this.size2 * z + this.size * y + x; return this.field[index]; }; this.blur = function(intensity = 1) { const field = this.field; const fieldCopy = field.slice(); const size = this.size; const size2 = this.size2; for (let x = 0; x < size; x++) for (let y = 0; y < size; y++) for (let z = 0; z < size; z++) { const index = size2 * z + size * y + x; let val = fieldCopy[index]; let count = 1; for (let x2 = -1; x2 <= 1; x2 += 2) { const x3 = x2 + x; if (x3 < 0 || x3 >= size) continue; for (let y2 = -1; y2 <= 1; y2 += 2) { const y3 = y2 + y; if (y3 < 0 || y3 >= size) continue; for (let z2 = -1; z2 <= 1; z2 += 2) { const z3 = z2 + z; if (z3 < 0 || z3 >= size) continue; const val2 = fieldCopy[size2 * z3 + size * y3 + x3]; count++; val += intensity * (val2 - val) / count; } } } field[index] = val; } }; this.reset = function() { for (let i = 0; i < this.size3; i++) { this.normal_cache[i * 3] = 0; this.field[i] = 0; this.palette[i * 3] = this.palette[i * 3 + 1] = this.palette[i * 3 + 2] = 0; } }; this.update = function() { this.count = 0; const smin2 = this.size - 2; for (let z = 1; z < smin2; z++) { const z_offset = this.size2 * z; const fz = (z - this.halfsize) / this.halfsize; for (let y = 1; y < smin2; y++) { const y_offset = z_offset + this.size * y; const fy = (y - this.halfsize) / this.halfsize; for (let x = 1; x < smin2; x++) polygonize((x - this.halfsize) / this.halfsize, fy, fz, y_offset + x, this.isolation); } } this.geometry.setDrawRange(0, this.count); geometry.getAttribute("position").needsUpdate = true; geometry.getAttribute("normal").needsUpdate = true; if (this.enableUvs) geometry.getAttribute("uv").needsUpdate = true; if (this.enableColors) geometry.getAttribute("color").needsUpdate = true; if (this.count / 3 > maxPolyCount) console.warn("THREE.MarchingCubes: Geometry buffers too small for rendering. Please create an instance with a higher poly count."); }; this.init(resolution); } }; var edgeTable = new Int32Array([ 0, 265, 515, 778, 1030, 1295, 1541, 1804, 2060, 2309, 2575, 2822, 3082, 3331, 3593, 3840, 400, 153, 915, 666, 1430, 1183, 1941, 1692, 2460, 2197, 2975, 2710, 3482, 3219, 3993, 3728, 560, 825, 51, 314, 1590, 1855, 1077, 1340, 2620, 2869, 2111, 2358, 3642, 3891, 3129, 3376, 928, 681, 419, 170, 1958, 1711, 1445, 1196, 2988, 2725, 2479, 2214, 4010, 3747, 3497, 3232, 1120, 1385, 1635, 1898, 102, 367, 613, 876, 3180, 3429, 3695, 3942, 2154, 2403, 2665, 2912, 1520, 1273, 2035, 1786, 502, 255, 1013, 764, 3580, 3317, 4095, 3830, 2554, 2291, 3065, 2800, 1616, 1881, 1107, 1370, 598, 863, 85, 348, 3676, 3925, 3167, 3414, 2650, 2899, 2137, 2384, 1984, 1737, 1475, 1226, 966, 719, 453, 204, 4044, 3781, 3535, 3270, 3018, 2755, 2505, 2240, 2240, 2505, 2755, 3018, 3270, 3535, 3781, 4044, 204, 453, 719, 966, 1226, 1475, 1737, 1984, 2384, 2137, 2899, 2650, 3414, 3167, 3925, 3676, 348, 85, 863, 598, 1370, 1107, 1881, 1616, 2800, 3065, 2291, 2554, 3830, 4095, 3317, 3580, 764, 1013, 255, 502, 1786, 2035, 1273, 1520, 2912, 2665, 2403, 2154, 3942, 3695, 3429, 3180, 876, 613, 367, 102, 1898, 1635, 1385, 1120, 3232, 3497, 3747, 4010, 2214, 2479, 2725, 2988, 1196, 1445, 1711, 1958, 170, 419, 681, 928, 3376, 3129, 3891, 3642, 2358, 2111, 2869, 2620, 1340, 1077, 1855, 1590, 314, 51, 825, 560, 3728, 3993, 3219, 3482, 2710, 2975, 2197, 2460, 1692, 1941, 1183, 1430, 666, 915, 153, 400, 3840, 3593, 3331, 3082, 2822, 2575, 2309, 2060, 1804, 1541, 1295, 1030, 778, 515, 265, 0 ]); var triTable = new Int32Array([ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1, 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1, 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1, 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1, 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1, 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1, 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1, 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1, 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1, 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1, 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1, 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1, 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1, 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1, 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1, 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1, 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1, 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1, 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1, 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1, 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1, 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1, 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1, 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1, 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1, 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1, 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1, 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1, 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1, 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1, 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1, 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1, 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1, 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1, 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1, 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1, 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1, 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1, 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1, 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1, 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1, 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1, 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1, 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1, 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1, 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1, 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1, 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1, 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1, 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1, 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1, 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1, 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1, 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1, 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1, 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1, 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1, 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1, 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1, 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1, 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1, 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1, 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1, 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1, 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1, 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1, 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1, 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1, 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1, 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1, 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1, 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1, 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1, 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1, 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1, 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1, 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1, 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1, 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1, 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1, 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1, 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1, 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1, 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1, 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1, 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1, 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1, 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1, 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1, 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1, 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1, 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1, 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1, 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1, 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1, 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1, 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1, 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1, 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1, 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1, 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1, 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1, 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1, 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1, 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1, 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1, 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1, 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1, 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1, 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1, 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1, 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1, 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1, 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1, 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1, 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1, 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1, 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1, 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1, 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1, 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1, 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1, 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1, 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1, 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1, 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1, 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1, 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1, 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1, 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1, 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1, 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1, 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1, 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1, 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1, 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1, 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1, 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1, 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1, 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1, 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1, 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1, 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1, 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1, 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1, 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1, 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1, 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ]); //#endregion //#region node_modules/three-stdlib/math/SimplexNoise.js var __defProp$44 = Object.defineProperty; var __defNormalProp$44 = (obj, key, value) => key in obj ? __defProp$44(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$44 = (obj, key, value) => { __defNormalProp$44(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(r = Math) { __publicField$44(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 ] ]); __publicField$44(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 ] ]); __publicField$44(this, "p", []); __publicField$44(this, "perm", []); __publicField$44(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 ] ]); __publicField$44(this, "dot", (g, x, y) => { return g[0] * x + g[1] * y; }); __publicField$44(this, "dot3", (g, x, y, z) => { return g[0] * x + g[1] * y + g[2] * z; }); __publicField$44(this, "dot4", (g, x, y, z, w) => { return g[0] * x + g[1] * y + g[2] * z + g[3] * w; }); __publicField$44(this, "noise", (xin, yin) => { let n0; let n1; let n2; const F2 = .5 * (Math.sqrt(3) - 1); const s = (xin + yin) * F2; const i = Math.floor(xin + s); const j = Math.floor(yin + s); const G2 = (3 - Math.sqrt(3)) / 6; const t = (i + j) * G2; const X0 = i - t; const Y0 = j - t; 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 + G2; const y1 = y0 - j1 + G2; const x2 = x0 - 1 + 2 * G2; const y2 = y0 - 1 + 2 * G2; const ii = i & 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 = .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 = .5 - x1 * x1 - y1 * y1; if (t1 < 0) n1 = 0; else { t1 *= t1; n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1); } let t2 = .5 - x2 * x2 - y2 * y2; if (t2 < 0) n2 = 0; else { t2 *= t2; n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2); } return 70 * (n0 + n1 + n2); }); __publicField$44(this, "noise3d", (xin, yin, zin) => { let n0; let n1; let n2; let n3; const s = (xin + yin + zin) * (1 / 3); const i = Math.floor(xin + s); const j = Math.floor(yin + s); const k = Math.floor(zin + s); const G3 = 1 / 6; const t = (i + j + k) * G3; const X0 = i - t; const Y0 = j - t; const Z0 = k - t; const x0 = xin - X0; const y0 = yin - Y0; const z0 = zin - Z0; let i1; let j1; let k1; let i2; let j2; let k2; if (x0 >= y0) if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } else if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; } else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; } else { i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } const x1 = x0 - i1 + G3; const y1 = y0 - j1 + G3; const z1 = z0 - k1 + G3; const x2 = x0 - i2 + 2 * G3; const y2 = y0 - j2 + 2 * G3; const z2 = z0 - k2 + 2 * G3; const x3 = x0 - 1 + 3 * G3; const y3 = y0 - 1 + 3 * G3; const z3 = z0 - 1 + 3 * G3; const ii = i & 255; const jj = 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 + i2 + 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 = .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 = .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 t2 = .6 - x2 * x2 - y2 * y2 - z2 * z2; if (t2 < 0) n2 = 0; else { t2 *= t2; n2 = t2 * t2 * this.dot3(this.grad3[gi2], x2, y2, z2); } let t3 = .6 - x3 * x3 - y3 * y3 - z3 * z3; if (t3 < 0) n3 = 0; else { t3 *= t3; n3 = t3 * t3 * this.dot3(this.grad3[gi3], x3, y3, z3); } return 32 * (n0 + n1 + n2 + n3); }); __publicField$44(this, "noise4d", (x, y, z, w) => { const grad4 = this.grad4; const simplex = this.simplex; const perm = this.perm; const F4 = (Math.sqrt(5) - 1) / 4; const G4 = (5 - Math.sqrt(5)) / 20; let n0; let n1; let n2; let n3; let n4; const s = (x + y + z + w) * F4; const i = Math.floor(x + s); const j = Math.floor(y + s); const k = Math.floor(z + s); const l = Math.floor(w + s); const t = (i + j + k + l) * G4; const X0 = i - t; const Y0 = j - t; const Z0 = k - t; const W0 = l - t; 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 c3 = y0 > z0 ? 8 : 0; const c4 = x0 > w0 ? 4 : 0; const c5 = y0 > w0 ? 2 : 0; const c6 = z0 > w0 ? 1 : 0; const c = c1 + c2 + c3 + c4 + c5 + c6; let i1; let j1; let k1; let l1; let i2; let j2; let k2; let l2; let i3; let j3; let k3; let l3; i1 = simplex[c][0] >= 3 ? 1 : 0; j1 = simplex[c][1] >= 3 ? 1 : 0; k1 = simplex[c][2] >= 3 ? 1 : 0; l1 = simplex[c][3] >= 3 ? 1 : 0; i2 = simplex[c][0] >= 2 ? 1 : 0; j2 = simplex[c][1] >= 2 ? 1 : 0; k2 = simplex[c][2] >= 2 ? 1 : 0; l2 = simplex[c][3] >= 2 ? 1 : 0; i3 = simplex[c][0] >= 1 ? 1 : 0; j3 = simplex[c][1] >= 1 ? 1 : 0; k3 = simplex[c][2] >= 1 ? 1 : 0; l3 = simplex[c][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 - i2 + 2 * G4; const y2 = y0 - j2 + 2 * G4; const z2 = z0 - k2 + 2 * G4; const w2 = w0 - l2 + 2 * G4; const x3 = x0 - i3 + 3 * G4; const y3 = y0 - j3 + 3 * G4; const z3 = z0 - k3 + 3 * G4; const w3 = w0 - l3 + 3 * G4; const x4 = x0 - 1 + 4 * G4; const y4 = y0 - 1 + 4 * G4; const z4 = z0 - 1 + 4 * G4; const w4 = w0 - 1 + 4 * G4; const ii = i & 255; const jj = j & 255; const kk = k & 255; const ll = l & 255; const gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; const gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; const gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; const gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; const gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; let t0 = .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 = .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 t2 = .6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; if (t2 < 0) n2 = 0; else { t2 *= t2; n2 = t2 * t2 * this.dot4(grad4[gi2], x2, y2, z2, w2); } let t3 = .6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; if (t3 < 0) n3 = 0; else { t3 *= t3; n3 = t3 * t3 * this.dot4(grad4[gi3], x3, y3, z3, w3); } let t4 = .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 i = 0; i < 256; i++) this.p[i] = Math.floor(r.random() * 256); for (let i = 0; i < 512; i++) this.perm[i] = this.p[i & 255]; } }; //#endregion //#region node_modules/three-stdlib/geometries/LightningStrike.js var __defProp$43 = Object.defineProperty; var __defNormalProp$43 = (obj, key, value) => key in obj ? __defProp$43(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$43 = (obj, key, value) => { __defNormalProp$43(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var LightningStrike = /* @__PURE__ */ (() => { 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 i = 0; i < numSeeds; i++) 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(seed) { generator.currentSeed = Math.floor(seed * numSeeds) % numSeeds; } }; return generator; } static copyParameters(dest = {}, source = {}) { const vecCopy = function(v) { if (source === dest) return v; else return v.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 : .9, dest.straightness = source.straightness !== void 0 ? source.straightness : .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 : .5, dest.radius1Factor = source.radius1Factor !== void 0 ? source.radius1Factor : .2, dest.minRadius = source.minRadius !== void 0 ? source.minRadius : .2, 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 : .1, dest.vanishingTimeFactor = source.vanishingTimeFactor !== void 0 ? source.vanishingTimeFactor : .9, dest.subrayPeriod = source.subrayPeriod !== void 0 ? source.subrayPeriod : 4, dest.subrayDutyCycle = source.subrayDutyCycle !== void 0 ? source.subrayDutyCycle : .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 : .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 : .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 i = 0; i < this.maxSubrays; i++) this.subrays.push(this.createSubray()); this.raySegments = []; for (let i = 0; i < this.maxRaySegments; i++) 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, .01); lForwards = this.forwards.length(); } const middleRadius = (segment.radius0 + segment.radius1) * .5; const middleFraction = (segment.fraction0 + segment.fraction1) * .5; const timeDimension = this.time * this.currentSubray.timeScale * Math.pow(2, segment.iteration); this.middlePos.lerpVectors(segment.pos0, segment.pos1, .5); this.middleLinPos.lerpVectors(segment.linPos0, segment.linPos1, .5); const p = this.middleLinPos; this.newPos.set(this.simplexX.noise4d(p.x, p.y, p.z, timeDimension), this.simplexY.noise4d(p.x, p.y, p.z, timeDimension), this.simplexZ.noise4d(p.x, p.y, p.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 p = this.vPos; const v = this.vertices; p.copy(pos).sub(this.side).add(this.down); v[this.currentCoordinate++] = p.x; v[this.currentCoordinate++] = p.y; v[this.currentCoordinate++] = p.z; p.copy(pos).add(this.side).add(this.down); v[this.currentCoordinate++] = p.x; v[this.currentCoordinate++] = p.y; v[this.currentCoordinate++] = p.z; p.copy(up).multiplyScalar(radius).add(pos); v[this.currentCoordinate++] = p.x; v[this.currentCoordinate++] = p.y; v[this.currentCoordinate++] = p.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 p = this.vPos; const v = this.vertices; const uv = this.uvs; p.copy(pos).sub(this.side).add(this.down); v[this.currentCoordinate++] = p.x; v[this.currentCoordinate++] = p.y; v[this.currentCoordinate++] = p.z; uv[this.currentUVCoordinate++] = u; uv[this.currentUVCoordinate++] = 0; p.copy(pos).add(this.side).add(this.down); v[this.currentCoordinate++] = p.x; v[this.currentCoordinate++] = p.y; v[this.currentCoordinate++] = p.z; uv[this.currentUVCoordinate++] = u; uv[this.currentUVCoordinate++] = .5; p.copy(up).multiplyScalar(radius).add(pos); v[this.currentCoordinate++] = p.x; v[this.currentCoordinate++] = p.y; v[this.currentCoordinate++] = p.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, .5, .6, .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 length = 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(length * 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 length = 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(length * 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; __publicField$43(LightningStrike2, "RAY_INITIALIZED", 0); __publicField$43(LightningStrike2, "RAY_UNBORN", 1); __publicField$43(LightningStrike2, "RAY_PROPAGATING", 2); __publicField$43(LightningStrike2, "RAY_STEADY", 3); __publicField$43(LightningStrike2, "RAY_VANISHING", 4); __publicField$43(LightningStrike2, "RAY_EXTINGUISHED", 5); __publicField$43(LightningStrike2, "COS30DEG", Math.cos(30 * Math.PI / 180)); __publicField$43(LightningStrike2, "SIN30DEG", Math.sin(30 * Math.PI / 180)); return LightningStrike2; })(); //#endregion //#region node_modules/three-stdlib/objects/LightningStorm.js var LightningStorm = class extends Object3D { constructor(stormParams = {}) { super(); this.isLightningStorm = true; this.stormParams = stormParams; stormParams.size = stormParams.size !== void 0 ? stormParams.size : 1e3; stormParams.minHeight = stormParams.minHeight !== void 0 ? stormParams.minHeight : 80; stormParams.maxHeight = stormParams.maxHeight !== void 0 ? stormParams.maxHeight : 100; stormParams.maxSlope = stormParams.maxSlope !== void 0 ? stormParams.maxSlope : 1.1; stormParams.maxLightnings = stormParams.maxLightnings !== void 0 ? stormParams.maxLightnings : 3; stormParams.lightningMinPeriod = stormParams.lightningMinPeriod !== void 0 ? stormParams.lightningMinPeriod : 3; stormParams.lightningMaxPeriod = stormParams.lightningMaxPeriod !== void 0 ? stormParams.lightningMaxPeriod : 7; stormParams.lightningMinDuration = stormParams.lightningMinDuration !== void 0 ? stormParams.lightningMinDuration : 1; stormParams.lightningMaxDuration = stormParams.lightningMaxDuration !== void 0 ? stormParams.lightningMaxDuration : 2.5; this.lightningParameters = LightningStrike.copyParameters(stormParams.lightningParameters, stormParams.lightningParameters); this.lightningParameters.isEternal = false; this.lightningMaterial = stormParams.lightningMaterial !== void 0 ? stormParams.lightningMaterial : new MeshBasicMaterial({ color: 11599871 }); if (stormParams.onRayPosition !== void 0) this.onRayPosition = stormParams.onRayPosition; else this.onRayPosition = function(source, dest) { dest.set((Math.random() - .5) * stormParams.size, 0, (Math.random() - .5) * stormParams.size); const height = MathUtils.lerp(stormParams.minHeight, stormParams.maxHeight, Math.random()); source.set(stormParams.maxSlope * (2 * Math.random() - 1), 1, stormParams.maxSlope * (2 * Math.random() - 1)).multiplyScalar(height).add(dest); }; this.onLightningDown = stormParams.onLightningDown; this.inited = false; this.nextLightningTime = 0; this.lightningsMeshes = []; this.deadLightningsMeshes = []; for (let i = 0; i < this.stormParams.maxLightnings; i++) { const mesh = new Mesh(new LightningStrike(LightningStrike.copyParameters({}, this.lightningParameters)), this.lightningMaterial); this.deadLightningsMeshes.push(mesh); } } update(time) { if (!this.inited) { this.nextLightningTime = this.getNextLightningTime(time) * Math.random(); this.inited = true; } if (time >= this.nextLightningTime) { const lightningMesh = this.deadLightningsMeshes.pop(); if (lightningMesh) { const lightningParams1 = LightningStrike.copyParameters(lightningMesh.geometry.rayParameters, this.lightningParameters); lightningParams1.birthTime = time; lightningParams1.deathTime = time + MathUtils.lerp(this.stormParams.lightningMinDuration, this.stormParams.lightningMaxDuration, Math.random()); this.onRayPosition(lightningParams1.sourceOffset, lightningParams1.destOffset); lightningParams1.noiseSeed = Math.random(); this.add(lightningMesh); this.lightningsMeshes.push(lightningMesh); } this.nextLightningTime = this.getNextLightningTime(time); } let i = 0, il = this.lightningsMeshes.length; while (i < il) { const mesh = this.lightningsMeshes[i]; const lightning = mesh.geometry; const prevState = lightning.state; lightning.update(time); if (prevState === LightningStrike.RAY_PROPAGATING && lightning.state > prevState) { if (this.onLightningDown) this.onLightningDown(lightning); } if (lightning.state === LightningStrike.RAY_EXTINGUISHED) { this.lightningsMeshes.splice(this.lightningsMeshes.indexOf(mesh), 1); this.deadLightningsMeshes.push(mesh); this.remove(mesh); il--; } else i++; } } getNextLightningTime(currentTime) { return currentTime + MathUtils.lerp(this.stormParams.lightningMinPeriod, this.stormParams.lightningMaxPeriod, Math.random()) / (this.stormParams.maxLightnings + 1); } copy(source, recursive) { super.copy(source, recursive); this.stormParams.size = source.stormParams.size; this.stormParams.minHeight = source.stormParams.minHeight; this.stormParams.maxHeight = source.stormParams.maxHeight; this.stormParams.maxSlope = source.stormParams.maxSlope; this.stormParams.maxLightnings = source.stormParams.maxLightnings; this.stormParams.lightningMinPeriod = source.stormParams.lightningMinPeriod; this.stormParams.lightningMaxPeriod = source.stormParams.lightningMaxPeriod; this.stormParams.lightningMinDuration = source.stormParams.lightningMinDuration; this.stormParams.lightningMaxDuration = source.stormParams.lightningMaxDuration; this.lightningParameters = LightningStrike.copyParameters({}, source.lightningParameters); this.lightningMaterial = source.stormParams.lightningMaterial; this.onLightningDown = source.onLightningDown; return this; } clone() { return new this.constructor(this.stormParams).copy(this); } }; //#endregion //#region node_modules/three-stdlib/objects/ReflectorRTT.js var ReflectorRTT = class extends Reflector { constructor(geometry, options) { super(geometry, options); this.geometry.setDrawRange(0, 0); } }; //#endregion //#region node_modules/three-stdlib/objects/ReflectorForSSRPass.js var __defProp$42 = Object.defineProperty; var __defNormalProp$42 = (obj, key, value) => key in obj ? __defProp$42(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$42 = (obj, key, value) => { __defNormalProp$42(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var ReflectorForSSRPass = /* @__PURE__ */ (() => { const _ReflectorForSSRPass = class extends Mesh { constructor(geometry, options = {}) { super(geometry); this.isReflectorForSSRPass = true; this.type = "ReflectorForSSRPass"; const scope = this; const color = options.color !== void 0 ? new Color(options.color) : new Color(8355711); const textureWidth = options.textureWidth || 512; const textureHeight = options.textureHeight || 512; const clipBias = options.clipBias || 0; const shader = options.shader || _ReflectorForSSRPass.ReflectorShader; const useDepthTexture = options.useDepthTexture === true; const yAxis = 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 normal = new Vector3(); const reflectorWorldPosition = new Vector3(); const cameraWorldPosition = new Vector3(); const rotationMatrix = new Matrix4(); const lookAtPosition = new Vector3(0, 0, -1); const view = new Vector3(); const target = new Vector3(); const textureMatrix = new Matrix4(); const virtualCamera = new PerspectiveCamera(); let depthTexture; if (useDepthTexture) { depthTexture = new DepthTexture(); depthTexture.type = UnsignedShortType; depthTexture.minFilter = NearestFilter; depthTexture.magFilter = NearestFilter; } const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { depthTexture: useDepthTexture ? depthTexture : null, type: HalfFloatType }); 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 globalPlanes = [new Plane(new Vector3(0, 1, 0), clipBias)]; 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(yAxis); material.uniforms["fresnelCoe"].value = (vecTemp0.dot(vecTemp1) + 1) / 2; reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); rotationMatrix.extractRotation(scope.matrixWorld); normal.set(0, 0, 1); normal.applyMatrix4(rotationMatrix); view.subVectors(reflectorWorldPosition, cameraWorldPosition); if (view.dot(normal) > 0) return; view.reflect(normal).negate(); view.add(reflectorWorldPosition); rotationMatrix.extractRotation(camera.matrixWorld); lookAtPosition.set(0, 0, -1); lookAtPosition.applyMatrix4(rotationMatrix); lookAtPosition.add(cameraWorldPosition); target.subVectors(reflectorWorldPosition, lookAtPosition); target.reflect(normal).negate(); target.add(reflectorWorldPosition); virtualCamera.position.copy(view); virtualCamera.up.set(0, 1, 0); virtualCamera.up.applyMatrix4(rotationMatrix); virtualCamera.up.reflect(normal); virtualCamera.lookAt(target); virtualCamera.far = camera.far; virtualCamera.updateMatrixWorld(); virtualCamera.projectionMatrix.copy(camera.projectionMatrix); material.uniforms["virtualCameraNear"].value = camera.near; material.uniforms["virtualCameraFar"].value = camera.far; material.uniforms["virtualCameraMatrixWorld"].value = virtualCamera.matrixWorld; material.uniforms["virtualCameraProjectionMatrix"].value = camera.projectionMatrix; material.uniforms["virtualCameraProjectionMatrixInverse"].value = camera.projectionMatrixInverse; material.uniforms["resolution"].value = scope.resolution; textureMatrix.set(.5, 0, 0, .5, 0, .5, 0, .5, 0, 0, .5, .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; __publicField$42(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: .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: ` uniform mat4 textureMatrix; varying vec4 vUv; void main() { vUv = textureMatrix * vec4( position, 1.0 ); gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: ` 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; })(); //#endregion //#region node_modules/three-stdlib/objects/Sky.js var __defProp$41 = Object.defineProperty; var __defNormalProp$41 = (obj, key, value) => key in obj ? __defProp$41(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$41 = (obj, key, value) => { __defNormalProp$41(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Sky = /* @__PURE__ */ (() => { const SkyShader = { uniforms: { turbidity: { value: 2 }, rayleigh: { value: 1 }, mieCoefficient: { value: .005 }, mieDirectionalG: { value: .8 }, sunPosition: { value: new Vector3() }, up: { value: new Vector3(0, 1, 0) } }, vertexShader: ` 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: ` 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: 1, depthWrite: false }); class Sky2 extends Mesh { constructor() { super(new BoxGeometry(1, 1, 1), material); } } __publicField$41(Sky2, "SkyShader", SkyShader); __publicField$41(Sky2, "material", material); return Sky2; })(); //#endregion //#region node_modules/three-stdlib/objects/Water2.js var __defProp$40 = Object.defineProperty; var __defNormalProp$40 = (obj, key, value) => key in obj ? __defProp$40(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$40 = (obj, key, value) => { __defNormalProp$40(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Water2 = /* @__PURE__ */ (() => { const _Water2 = class extends Mesh { constructor(geometry, options = {}) { super(geometry); this.isWater = true; this.type = "Water"; const scope = this; const color = options.color !== void 0 ? new Color(options.color) : new Color(16777215); const textureWidth = options.textureWidth || 512; const textureHeight = options.textureHeight || 512; const clipBias = options.clipBias || 0; const flowDirection = options.flowDirection || new Vector2(1, 0); const flowSpeed = options.flowSpeed || .03; const reflectivity = options.reflectivity || .02; const scale = 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 = .15; const halfCycle = cycle * .5; const textureMatrix = new Matrix4(); const clock = new Clock(); if (Reflector === void 0) { console.error("THREE.Water: Required component Reflector not found."); return; } if (Refractor === void 0) { console.error("THREE.Water: Required component Refractor not found."); return; } const reflector = new Reflector(geometry, { textureWidth, textureHeight, clipBias, encoding }); const refractor = new Refractor(geometry, { 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 = scale; function updateTextureMatrix(camera) { textureMatrix.set(.5, 0, 0, .5, 0, .5, 0, .5, 0, 0, .5, .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; __publicField$40(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: /* @__PURE__ */ new Vector4() } }, vertexShader: ` #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: ` #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; })(); //#endregion //#region node_modules/three-stdlib/objects/GroundProjectedEnv.js var isCubeTexture = (def) => def && def.isCubeTexture; var GroundProjectedEnv = class extends Mesh { constructor(texture, options) { var _a, _b; const isCubeMap = isCubeTexture(texture); const cubeSize = ((_b = isCubeMap ? (_a = texture.image[0]) == null ? void 0 : _a.width : texture.image.width) != null ? _b : 1024) / 4; const _lodMax = Math.floor(Math.log2(cubeSize)); const _cubeSize = Math.pow(2, _lodMax); const width = 3 * Math.max(_cubeSize, 112); 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 vertexShader = ` varying vec3 vWorldPosition; void main() { vec4 worldPosition = ( modelMatrix * vec4( position, 1.0 ) ); vWorldPosition = worldPosition.xyz; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `; const fragmentShader = defines.join("\n") + ` #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 geometry = new IcosahedronGeometry(1, 16); const material = new ShaderMaterial({ uniforms, fragmentShader, vertexShader, side: 2 }); super(geometry, 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; } }; //#endregion //#region node_modules/three-stdlib/utils/SceneUtils.js var SceneUtils = { createMeshesFromInstancedMesh: function(instancedMesh) { const group = new Group(); const count = instancedMesh.count; const geometry = instancedMesh.geometry; const material = instancedMesh.material; for (let i = 0; i < count; i++) { const mesh = new Mesh(geometry, material); instancedMesh.getMatrixAt(i, mesh.matrix); mesh.matrix.decompose(mesh.position, mesh.quaternion, mesh.scale); group.add(mesh); } group.copy(instancedMesh); group.updateMatrixWorld(); return group; }, createMultiMaterialObject: function(geometry, materials) { const group = new Group(); for (let i = 0, l = materials.length; i < l; i++) group.add(new Mesh(geometry, materials[i])); return group; }, detach: function(child, parent, scene) { console.warn("THREE.SceneUtils: detach() has been deprecated. Use scene.attach( child ) instead."); scene.attach(child); }, attach: function(child, scene, parent) { console.warn("THREE.SceneUtils: attach() has been deprecated. Use parent.attach( child ) instead."); parent.attach(child); } }; //#endregion //#region node_modules/three-stdlib/utils/UVsDebug.js function UVsDebug(geometry, size = 1024) { const abc = "abc"; const a = new Vector2(); const b = new Vector2(); const uvs = [ new Vector2(), new Vector2(), new Vector2() ]; const face = []; const canvas = document.createElement("canvas"); const width = size; const height = size; canvas.width = width; canvas.height = height; const ctx = canvas.getContext("2d"); ctx.lineWidth = 1; ctx.strokeStyle = "rgb( 63, 63, 63 )"; ctx.textAlign = "center"; ctx.fillStyle = "rgb( 255, 255, 255 )"; ctx.fillRect(0, 0, width, height); const index = geometry.index; const uvAttribute = geometry.attributes.uv; if (index) for (let i = 0, il = index.count; i < il; i += 3) { face[0] = index.getX(i); face[1] = index.getX(i + 1); face[2] = index.getX(i + 2); uvs[0].fromBufferAttribute(uvAttribute, face[0]); uvs[1].fromBufferAttribute(uvAttribute, face[1]); uvs[2].fromBufferAttribute(uvAttribute, face[2]); processFace(face, uvs, i / 3); } else for (let i = 0, il = uvAttribute.count; i < il; i += 3) { face[0] = i; face[1] = i + 1; face[2] = i + 2; uvs[0].fromBufferAttribute(uvAttribute, face[0]); uvs[1].fromBufferAttribute(uvAttribute, face[1]); uvs[2].fromBufferAttribute(uvAttribute, face[2]); processFace(face, uvs, i / 3); } return canvas; function processFace(face2, uvs2, index2) { ctx.beginPath(); a.set(0, 0); for (let j = 0, jl = uvs2.length; j < jl; j++) { const uv = uvs2[j]; a.x += uv.x; a.y += uv.y; if (j === 0) ctx.moveTo(uv.x * (width - 2) + .5, (1 - uv.y) * (height - 2) + .5); else ctx.lineTo(uv.x * (width - 2) + .5, (1 - uv.y) * (height - 2) + .5); } ctx.closePath(); ctx.stroke(); a.divideScalar(uvs2.length); ctx.font = "18px Arial"; ctx.fillStyle = "rgb( 63, 63, 63 )"; ctx.fillText(index2, a.x * width, (1 - a.y) * height); if (a.x > .95) ctx.fillText(index2, a.x % 1 * width, (1 - a.y) * height); ctx.font = "12px Arial"; ctx.fillStyle = "rgb( 191, 191, 191 )"; for (let j = 0, jl = uvs2.length; j < jl; j++) { const uv = uvs2[j]; b.addVectors(a, uv).divideScalar(2); const vnum = face2[j]; ctx.fillText(abc[j] + vnum, b.x * width, (1 - b.y) * height); if (b.x > .95) ctx.fillText(abc[j] + vnum, b.x % 1 * width, (1 - b.y) * height); } } } //#endregion //#region node_modules/three-stdlib/utils/GeometryUtils.js var hilbert2D = (center = new Vector3(0, 0, 0), size = 10, iterations = 1, v0 = 0, v1 = 1, v2 = 2, v3 = 3) => { const half = size / 2; const vec_s = [ new Vector3(center.x - half, center.y, center.z - half), new Vector3(center.x - half, center.y, center.z + half), new Vector3(center.x + half, center.y, center.z + half), new Vector3(center.x + half, center.y, center.z - half) ]; const vec = [ vec_s[v0], vec_s[v1], vec_s[v2], vec_s[v3] ]; if (0 <= --iterations) { const tmp = []; Array.prototype.push.apply(tmp, hilbert2D(vec[0], half, iterations, v0, v3, v2, v1)); Array.prototype.push.apply(tmp, hilbert2D(vec[1], half, iterations, v0, v1, v2, v3)); Array.prototype.push.apply(tmp, hilbert2D(vec[2], half, iterations, v0, v1, v2, v3)); Array.prototype.push.apply(tmp, hilbert2D(vec[3], half, iterations, v2, v1, v0, v3)); return tmp; } return vec; }; var hilbert3D = (center = new Vector3(0, 0, 0), size = 10, iterations = 1, v0 = 0, v1 = 1, v2 = 2, v3 = 3, v4 = 4, v5 = 5, v6 = 6, v7 = 7) => { const half = size / 2; const vec_s = [ new Vector3(center.x - half, center.y + half, center.z - half), new Vector3(center.x - half, center.y + half, center.z + half), new Vector3(center.x - half, center.y - half, center.z + half), new Vector3(center.x - half, center.y - half, center.z - half), new Vector3(center.x + half, center.y - half, center.z - half), new Vector3(center.x + half, center.y - half, center.z + half), new Vector3(center.x + half, center.y + half, center.z + half), new Vector3(center.x + half, center.y + half, center.z - half) ]; const vec = [ vec_s[v0], vec_s[v1], vec_s[v2], vec_s[v3], vec_s[v4], vec_s[v5], vec_s[v6], vec_s[v7] ]; if (--iterations >= 0) { const tmp = []; Array.prototype.push.apply(tmp, hilbert3D(vec[0], half, iterations, v0, v3, v4, v7, v6, v5, v2, v1)); Array.prototype.push.apply(tmp, hilbert3D(vec[1], half, iterations, v0, v7, v6, v1, v2, v5, v4, v3)); Array.prototype.push.apply(tmp, hilbert3D(vec[2], half, iterations, v0, v7, v6, v1, v2, v5, v4, v3)); Array.prototype.push.apply(tmp, hilbert3D(vec[3], half, iterations, v2, v3, v0, v1, v6, v7, v4, v5)); Array.prototype.push.apply(tmp, hilbert3D(vec[4], half, iterations, v2, v3, v0, v1, v6, v7, v4, v5)); Array.prototype.push.apply(tmp, hilbert3D(vec[5], half, iterations, v4, v3, v2, v5, v6, v1, v0, v7)); Array.prototype.push.apply(tmp, hilbert3D(vec[6], half, iterations, v4, v3, v2, v5, v6, v1, v0, v7)); Array.prototype.push.apply(tmp, hilbert3D(vec[7], half, iterations, v6, v5, v2, v1, v0, v3, v4, v7)); return tmp; } return vec; }; var gosper = (size = 1) => { function fractalize(config) { let output = ""; let input = config.axiom; for (let i = 0, il = config.steps; 0 <= il ? i < il : i > il; 0 <= il ? i++ : i--) { output = ""; for (let j = 0, jl = input.length; j < jl; j++) { const char = input[j]; if (char in config.rules) output += config.rules[char]; else output += char; } input = output; } return output; } function toPoints(config) { let currX = 0; let currY = 0; let angle = 0; const path = [ 0, 0, 0 ]; const fractal = config.fractal; for (let i = 0, l = fractal.length; i < l; i++) { const char = fractal[i]; if (char === "+") angle += config.angle; else if (char === "-") angle -= config.angle; else if (char === "F") { currX += config.size * Math.cos(angle); currY += -config.size * Math.sin(angle); path.push(currX, currY, 0); } } return path; } return toPoints({ fractal: fractalize({ axiom: "A", steps: 4, rules: { A: "A+BF++BF-FA--FAFA-BF+", B: "-FA+BFBF++BF+FA--FA-B" } }), size, angle: Math.PI / 3 }); }; var GeometryUtils = { hilbert3D, gosper, hilbert2D }; //#endregion //#region node_modules/three-stdlib/utils/RoughnessMipmapper.js var __defProp$39 = Object.defineProperty; var __defNormalProp$39 = (obj, key, value) => key in obj ? __defProp$39(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$39 = (obj, key, value) => { __defNormalProp$39(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var _mipmapMaterial = /* @__PURE__ */ _getMipmapMaterial(); var _mesh = /* @__PURE__ */ new Mesh(/* @__PURE__ */ new PlaneGeometry(2, 2), _mipmapMaterial); var _flatCamera = /* @__PURE__ */ new OrthographicCamera(0, 1, 0, 1, 0, 1); var _tempTarget = null; var RoughnessMipmapper = class { constructor(renderer) { __publicField$39(this, "generateMipmaps", function(material) { if ("roughnessMap" in material === false) return; var { roughnessMap, normalMap } = material; if (roughnessMap === null || normalMap === null || !roughnessMap.generateMipmaps || material.userData.roughnessUpdated) return; material.userData.roughnessUpdated = true; var width = Math.max(roughnessMap.image.width, normalMap.image.width); var height = Math.max(roughnessMap.image.height, normalMap.image.height); if (!MathUtils.isPowerOfTwo(width) || !MathUtils.isPowerOfTwo(height)) return; var oldTarget = this._renderer.getRenderTarget(); var autoClear = this._renderer.autoClear; this._renderer.autoClear = false; if (_tempTarget === null || _tempTarget.width !== width || _tempTarget.height !== height) { if (_tempTarget !== null) _tempTarget.dispose(); _tempTarget = new WebGLRenderTarget(width, height, { depthBuffer: false }); _tempTarget.scissorTest = true; } if (width !== roughnessMap.image.width || height !== roughnessMap.image.height) { var params = { wrapS: roughnessMap.wrapS, wrapT: roughnessMap.wrapT, magFilter: roughnessMap.magFilter, minFilter: roughnessMap.minFilter, depthBuffer: false }; var newRoughnessTarget = new WebGLRenderTarget(width, height, params); newRoughnessTarget.texture.generateMipmaps = true; this._renderer.setRenderTarget(newRoughnessTarget); material.roughnessMap = newRoughnessTarget.texture; if (material.metalnessMap == roughnessMap) material.metalnessMap = material.roughnessMap; if (material.aoMap == roughnessMap) material.aoMap = material.roughnessMap; } _mipmapMaterial.uniforms.roughnessMap.value = roughnessMap; _mipmapMaterial.uniforms.normalMap.value = normalMap; var position = new Vector2(0, 0); var texelSize = _mipmapMaterial.uniforms.texelSize.value; for (let mip = 0; width >= 1 && height >= 1; ++mip, width /= 2, height /= 2) { texelSize.set(1 / width, 1 / height); if (mip == 0) texelSize.set(0, 0); _tempTarget.viewport.set(position.x, position.y, width, height); _tempTarget.scissor.set(position.x, position.y, width, height); this._renderer.setRenderTarget(_tempTarget); this._renderer.render(_mesh, _flatCamera); this._renderer.copyFramebufferToTexture(position, material.roughnessMap, mip); _mipmapMaterial.uniforms.roughnessMap.value = material.roughnessMap; } if (roughnessMap !== material.roughnessMap) roughnessMap.dispose(); this._renderer.setRenderTarget(oldTarget); this._renderer.autoClear = autoClear; }); __publicField$39(this, "dispose", function() { _mipmapMaterial.dispose(); _mesh.geometry.dispose(); if (_tempTarget != null) _tempTarget.dispose(); }); this._renderer = renderer; this._renderer.compile(_mesh, _flatCamera); } }; function _getMipmapMaterial() { var shaderMaterial = new RawShaderMaterial({ uniforms: { roughnessMap: { value: null }, normalMap: { value: null }, texelSize: { value: new Vector2(1, 1) } }, vertexShader: ` 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: ` 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: 0, depthTest: false, depthWrite: false }); shaderMaterial.type = "RoughnessMipmapper"; return shaderMaterial; } //#endregion //#region node_modules/three-stdlib/utils/SkeletonUtils.js function retarget(target, source, options = {}) { const pos = new Vector3(), quat = new Quaternion(), scale = 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 = target.isObject3D ? target.skeleton.bones : getBones(target); let bindBones, bone, name, boneTo, bonesPosition; if (target.isObject3D) target.skeleton.pose(); else { options.useTargetMatrix = true; options.preserveMatrix = false; } if (options.preservePosition) { bonesPosition = []; for (let i = 0; i < bones.length; i++) bonesPosition.push(bones[i].position.clone()); } if (options.preserveMatrix) { target.updateMatrixWorld(); target.matrixWorld.identity(); for (let i = 0; i < target.children.length; ++i) target.children[i].updateMatrixWorld(true); } if (options.offsets) { bindBones = []; for (let i = 0; i < bones.length; ++i) { bone = bones[i]; 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 i = 0; i < bones.length; ++i) { bone = bones[i]; 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(target.matrixWorld).invert(); relativeMatrix.multiply(boneTo.matrixWorld); } scale.setFromMatrixScale(relativeMatrix); relativeMatrix.scale(scale.set(1 / scale.x, 1 / scale.y, 1 / scale.z)); globalMatrix.makeRotationFromQuaternion(quat.setFromRotationMatrix(relativeMatrix)); if (target.isObject3D) { const boneIndex = bones.indexOf(bone), wBindMatrix = bindBones ? bindBones[boneIndex] : bindBoneMatrix.copy(target.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 i = 0; i < bones.length; ++i) { bone = bones[i]; name = options.names[bone.name] || bone.name; if (name !== options.hip) bone.position.copy(bonesPosition[i]); } if (options.preserveMatrix) target.updateMatrixWorld(true); } function retargetClip(target, source, clip, options = {}) { options.useFirstFramePosition = options.useFirstFramePosition !== void 0 ? options.useFirstFramePosition : false; options.fps = options.fps !== void 0 ? options.fps : 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(target.skeleton), boneDatas = []; let positionOffset, bone, boneTo, boneData, name; mixer.clipAction(clip).play(); mixer.update(0); source.updateMatrixWorld(); for (let i = 0; i < numFrames; ++i) { const time = i * delta; retarget(target, 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 (i === 0) positionOffset = bone.position.clone(); bone.position.sub(positionOffset); } boneData.pos.times[i] = time; bone.position.toArray(boneData.pos.values, i * 3); } if (!boneData.quat) boneData.quat = { times: new Float32Array(numFrames), values: new Float32Array(numFrames * 4) }; boneData.quat.times[i] = time; bone.quaternion.toArray(boneData.quat.values, i * 4); } } mixer.update(delta); source.updateMatrixWorld(); } for (let i = 0; i < boneDatas.length; ++i) { boneData = boneDatas[i]; if (boneData) { if (boneData.pos) convertedTracks.push(new VectorKeyframeTrack(".bones[" + boneData.bone.name + "].position", boneData.pos.times, boneData.pos.values)); convertedTracks.push(new QuaternionKeyframeTrack(".bones[" + boneData.bone.name + "].quaternion", boneData.quat.times, boneData.quat.values)); } } mixer.uncacheAction(clip); return new AnimationClip(clip.name, -1, convertedTracks); } function clone(source) { const sourceLookup = /* @__PURE__ */ new Map(); const cloneLookup = /* @__PURE__ */ new Map(); const clone2 = source.clone(); parallelTraverse(source, clone2, function(sourceNode, clonedNode) { sourceLookup.set(clonedNode, sourceNode); cloneLookup.set(sourceNode, clonedNode); }); clone2.traverse(function(node) { if (!node.isSkinnedMesh) return; const clonedMesh = node; const sourceMesh = sourceLookup.get(node); const sourceBones = sourceMesh.skeleton.bones; clonedMesh.skeleton = sourceMesh.skeleton.clone(); clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix); clonedMesh.skeleton.bones = sourceBones.map(function(bone) { return cloneLookup.get(bone); }); clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix); }); return clone2; } function getBoneByName(name, skeleton) { for (let i = 0, bones = getBones(skeleton); i < bones.length; i++) if (name === bones[i].name) return bones[i]; } function getBones(skeleton) { return Array.isArray(skeleton) ? skeleton : skeleton.bones; } function getHelperFromSkeleton(skeleton) { const source = new SkeletonHelper(skeleton.bones[0]); source.skeleton = skeleton; return source; } function parallelTraverse(a, b, callback) { callback(a, b); for (let i = 0; i < a.children.length; i++) parallelTraverse(a.children[i], b.children[i], callback); } var SkeletonUtils = { retarget, retargetClip, clone }; //#endregion //#region node_modules/three-stdlib/shaders/UnpackDepthRGBAShader.js var UnpackDepthRGBAShader = { uniforms: { tDiffuse: { value: null }, opacity: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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 ); } ` }; //#endregion //#region node_modules/three-stdlib/utils/ShadowMapViewer.js var ShadowMapViewer = class { constructor(light) { const scope = this; const doRenderLabel = light.name !== void 0 && light.name !== ""; let userAutoClearSetting; const frame = { x: 10, y: 10, width: 256, height: 256 }; const camera = new OrthographicCamera(window.innerWidth / -2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / -2, 1, 10); camera.position.set(0, 0, 2); const scene = new Scene(); const shader = UnpackDepthRGBAShader; const uniforms = UniformsUtils.clone(shader.uniforms); const material = new ShaderMaterial({ uniforms, vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }); const mesh = new Mesh(new PlaneGeometry(frame.width, frame.height), material); scene.add(mesh); let labelCanvas, labelMesh; if (doRenderLabel) { labelCanvas = document.createElement("canvas"); const context = labelCanvas.getContext("2d"); context.font = "Bold 20px Arial"; const labelWidth = context.measureText(light.name).width; labelCanvas.width = labelWidth; labelCanvas.height = 25; context.font = "Bold 20px Arial"; context.fillStyle = "rgba( 255, 0, 0, 1 )"; context.fillText(light.name, 0, 20); const labelTexture = new Texture(labelCanvas); labelTexture.magFilter = LinearFilter; labelTexture.minFilter = LinearFilter; labelTexture.needsUpdate = true; const labelMaterial = new MeshBasicMaterial({ map: labelTexture, side: 2 }); labelMaterial.transparent = true; labelMesh = new Mesh(new PlaneGeometry(labelCanvas.width, labelCanvas.height), labelMaterial); scene.add(labelMesh); } function resetPosition() { scope.position.set(scope.position.x, scope.position.y); } this.enabled = true; this.size = { width: frame.width, height: frame.height, set: function(width, height) { this.width = width; this.height = height; mesh.scale.set(this.width / frame.width, this.height / frame.height, 1); resetPosition(); } }; this.position = { x: frame.x, y: frame.y, set: function(x, y) { this.x = x; this.y = y; const width = scope.size.width; const height = scope.size.height; mesh.position.set(-window.innerWidth / 2 + width / 2 + this.x, window.innerHeight / 2 - height / 2 - this.y, 0); if (doRenderLabel) labelMesh.position.set(mesh.position.x, mesh.position.y - scope.size.height / 2 + labelCanvas.height / 2, 0); } }; this.render = function(renderer) { if (this.enabled) { uniforms.tDiffuse.value = light.shadow.map.texture; userAutoClearSetting = renderer.autoClear; renderer.autoClear = false; renderer.clearDepth(); renderer.render(scene, camera); renderer.autoClear = userAutoClearSetting; } }; this.updateForWindowResize = function() { if (this.enabled) { camera.left = window.innerWidth / -2; camera.right = window.innerWidth / 2; camera.top = window.innerHeight / 2; camera.bottom = window.innerHeight / -2; camera.updateProjectionMatrix(); this.update(); } }; this.update = function() { this.position.set(this.position.x, this.position.y); this.size.set(this.size.width, this.size.height); }; this.update(); } }; //#endregion //#region node_modules/three-stdlib/utils/GeometryCompressionUtils.js var GeometryCompressionUtils = { /** * Make the input mesh.geometry's normal attribute encoded and compressed by 3 different methods. * Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the normal data. * * @param {THREE.Mesh} mesh * @param {String} encodeMethod "DEFAULT" || "OCT1Byte" || "OCT2Byte" || "ANGLES" * */ compressNormals: function(mesh, encodeMethod) { if (!mesh.geometry) console.error("Mesh must contain geometry. "); const normal = mesh.geometry.attributes.normal; if (!normal) console.error("Geometry must contain normal attribute. "); if (normal.isPacked) return; if (normal.itemSize != 3) console.error("normal.itemSize is not 3, which cannot be encoded. "); const array = normal.array; const count = normal.count; let result; if (encodeMethod == "DEFAULT") { result = new Uint8Array(count * 3); for (let idx = 0; idx < array.length; idx += 3) { const encoded = this.EncodingFuncs.defaultEncode(array[idx], array[idx + 1], array[idx + 2], 1); result[idx + 0] = encoded[0]; result[idx + 1] = encoded[1]; result[idx + 2] = encoded[2]; } mesh.geometry.setAttribute("normal", new BufferAttribute(result, 3, true)); mesh.geometry.attributes.normal.bytes = result.length * 1; } else if (encodeMethod == "OCT1Byte") { result = new Int8Array(count * 2); for (let idx = 0; idx < array.length; idx += 3) { const encoded = this.EncodingFuncs.octEncodeBest(array[idx], array[idx + 1], array[idx + 2], 1); result[idx / 3 * 2 + 0] = encoded[0]; result[idx / 3 * 2 + 1] = encoded[1]; } mesh.geometry.setAttribute("normal", new BufferAttribute(result, 2, true)); mesh.geometry.attributes.normal.bytes = result.length * 1; } else if (encodeMethod == "OCT2Byte") { result = new Int16Array(count * 2); for (let idx = 0; idx < array.length; idx += 3) { const encoded = this.EncodingFuncs.octEncodeBest(array[idx], array[idx + 1], array[idx + 2], 2); result[idx / 3 * 2 + 0] = encoded[0]; result[idx / 3 * 2 + 1] = encoded[1]; } mesh.geometry.setAttribute("normal", new BufferAttribute(result, 2, true)); mesh.geometry.attributes.normal.bytes = result.length * 2; } else if (encodeMethod == "ANGLES") { result = new Uint16Array(count * 2); for (let idx = 0; idx < array.length; idx += 3) { const encoded = this.EncodingFuncs.anglesEncode(array[idx], array[idx + 1], array[idx + 2]); result[idx / 3 * 2 + 0] = encoded[0]; result[idx / 3 * 2 + 1] = encoded[1]; } mesh.geometry.setAttribute("normal", new BufferAttribute(result, 2, true)); mesh.geometry.attributes.normal.bytes = result.length * 2; } else console.error("Unrecognized encoding method, should be `DEFAULT` or `ANGLES` or `OCT`. "); mesh.geometry.attributes.normal.needsUpdate = true; mesh.geometry.attributes.normal.isPacked = true; mesh.geometry.attributes.normal.packingMethod = encodeMethod; if (!(mesh.material instanceof PackedPhongMaterial)) mesh.material = new PackedPhongMaterial().copy(mesh.material); if (encodeMethod == "ANGLES") mesh.material.defines.USE_PACKED_NORMAL = 0; if (encodeMethod == "OCT1Byte") mesh.material.defines.USE_PACKED_NORMAL = 1; if (encodeMethod == "OCT2Byte") mesh.material.defines.USE_PACKED_NORMAL = 1; if (encodeMethod == "DEFAULT") mesh.material.defines.USE_PACKED_NORMAL = 2; }, /** * Make the input mesh.geometry's position attribute encoded and compressed. * Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the position data. * * @param {THREE.Mesh} mesh * */ compressPositions: function(mesh) { if (!mesh.geometry) console.error("Mesh must contain geometry. "); const position = mesh.geometry.attributes.position; if (!position) console.error("Geometry must contain position attribute. "); if (position.isPacked) return; if (position.itemSize != 3) console.error("position.itemSize is not 3, which cannot be packed. "); const array = position.array; const encodingBytes = 2; const result = this.EncodingFuncs.quantizedEncode(array, encodingBytes); const quantized = result.quantized; const decodeMat = result.decodeMat; if (mesh.geometry.boundingBox == null) mesh.geometry.computeBoundingBox(); if (mesh.geometry.boundingSphere == null) mesh.geometry.computeBoundingSphere(); mesh.geometry.setAttribute("position", new BufferAttribute(quantized, 3)); mesh.geometry.attributes.position.isPacked = true; mesh.geometry.attributes.position.needsUpdate = true; mesh.geometry.attributes.position.bytes = quantized.length * encodingBytes; if (!(mesh.material instanceof PackedPhongMaterial)) mesh.material = new PackedPhongMaterial().copy(mesh.material); mesh.material.defines.USE_PACKED_POSITION = 0; mesh.material.uniforms.quantizeMatPos.value = decodeMat; mesh.material.uniforms.quantizeMatPos.needsUpdate = true; }, /** * Make the input mesh.geometry's uv attribute encoded and compressed. * Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the uv data. * * @param {THREE.Mesh} mesh * */ compressUvs: function(mesh) { if (!mesh.geometry) console.error("Mesh must contain geometry property. "); const uvs = mesh.geometry.attributes.uv; if (!uvs) console.error("Geometry must contain uv attribute. "); if (uvs.isPacked) return; const range = { min: Infinity, max: -Infinity }; const array = uvs.array; for (let i = 0; i < array.length; i++) { range.min = Math.min(range.min, array[i]); range.max = Math.max(range.max, array[i]); } let result; if (range.min >= -1 && range.max <= 1) { result = new Uint16Array(array.length); for (let i = 0; i < array.length; i += 2) { const encoded = this.EncodingFuncs.defaultEncode(array[i], array[i + 1], 0, 2); result[i] = encoded[0]; result[i + 1] = encoded[1]; } mesh.geometry.setAttribute("uv", new BufferAttribute(result, 2, true)); mesh.geometry.attributes.uv.isPacked = true; mesh.geometry.attributes.uv.needsUpdate = true; mesh.geometry.attributes.uv.bytes = result.length * 2; if (!(mesh.material instanceof PackedPhongMaterial)) mesh.material = new PackedPhongMaterial().copy(mesh.material); mesh.material.defines.USE_PACKED_UV = 0; } else { result = this.EncodingFuncs.quantizedEncodeUV(array, 2); mesh.geometry.setAttribute("uv", new BufferAttribute(result.quantized, 2)); mesh.geometry.attributes.uv.isPacked = true; mesh.geometry.attributes.uv.needsUpdate = true; mesh.geometry.attributes.uv.bytes = result.quantized.length * 2; if (!(mesh.material instanceof PackedPhongMaterial)) mesh.material = new PackedPhongMaterial().copy(mesh.material); mesh.material.defines.USE_PACKED_UV = 1; mesh.material.uniforms.quantizeMatUV.value = result.decodeMat; mesh.material.uniforms.quantizeMatUV.needsUpdate = true; } }, EncodingFuncs: { defaultEncode: function(x, y, z, bytes) { if (bytes == 1) { const tmpx = Math.round((x + 1) * .5 * 255); const tmpy = Math.round((y + 1) * .5 * 255); const tmpz = Math.round((z + 1) * .5 * 255); return new Uint8Array([ tmpx, tmpy, tmpz ]); } else if (bytes == 2) { const tmpx = Math.round((x + 1) * .5 * 65535); const tmpy = Math.round((y + 1) * .5 * 65535); const tmpz = Math.round((z + 1) * .5 * 65535); return new Uint16Array([ tmpx, tmpy, tmpz ]); } else console.error("number of bytes must be 1 or 2"); }, defaultDecode: function(array, bytes) { if (bytes == 1) return [ array[0] / 255 * 2 - 1, array[1] / 255 * 2 - 1, array[2] / 255 * 2 - 1 ]; else if (bytes == 2) return [ array[0] / 65535 * 2 - 1, array[1] / 65535 * 2 - 1, array[2] / 65535 * 2 - 1 ]; else console.error("number of bytes must be 1 or 2"); }, anglesEncode: function(x, y, z) { const normal0 = parseInt(.5 * (1 + Math.atan2(y, x) / Math.PI) * 65535); const normal1 = parseInt(.5 * (1 + z) * 65535); return new Uint16Array([normal0, normal1]); }, octEncodeBest: function(x, y, z, bytes) { var oct, dec, best = oct = octEncodeVec3(x, y, z, "floor", "floor"), currentCos, bestCos; dec = octDecodeVec2(oct); bestCos = dot(x, y, z, dec); oct = octEncodeVec3(x, y, z, "ceil", "floor"); dec = octDecodeVec2(oct); currentCos = dot(x, y, z, dec); if (currentCos > bestCos) { best = oct; bestCos = currentCos; } oct = octEncodeVec3(x, y, z, "floor", "ceil"); dec = octDecodeVec2(oct); currentCos = dot(x, y, z, dec); if (currentCos > bestCos) { best = oct; bestCos = currentCos; } oct = octEncodeVec3(x, y, z, "ceil", "ceil"); dec = octDecodeVec2(oct); currentCos = dot(x, y, z, dec); if (currentCos > bestCos) best = oct; return best; function octEncodeVec3(x0, y0, z0, xfunc, yfunc) { var x2 = x0 / (Math.abs(x0) + Math.abs(y0) + Math.abs(z0)); var y2 = y0 / (Math.abs(x0) + Math.abs(y0) + Math.abs(z0)); if (z < 0) { var tempx = (1 - Math.abs(y2)) * (x2 >= 0 ? 1 : -1); var tempy = (1 - Math.abs(x2)) * (y2 >= 0 ? 1 : -1); x2 = tempx; y2 = tempy; var diff = 1 - Math.abs(x2) - Math.abs(y2); if (diff > 0) { diff += .001; x2 += x2 > 0 ? diff / 2 : -diff / 2; y2 += y2 > 0 ? diff / 2 : -diff / 2; } } if (bytes == 1) return new Int8Array([Math[xfunc](x2 * 127.5 + (x2 < 0 ? 1 : 0)), Math[yfunc](y2 * 127.5 + (y2 < 0 ? 1 : 0))]); if (bytes == 2) return new Int16Array([Math[xfunc](x2 * 32767.5 + (x2 < 0 ? 1 : 0)), Math[yfunc](y2 * 32767.5 + (y2 < 0 ? 1 : 0))]); } function octDecodeVec2(oct2) { var x2 = oct2[0]; var y2 = oct2[1]; if (bytes == 1) { x2 /= x2 < 0 ? 127 : 128; y2 /= y2 < 0 ? 127 : 128; } else if (bytes == 2) { x2 /= x2 < 0 ? 32767 : 32768; y2 /= y2 < 0 ? 32767 : 32768; } var z2 = 1 - Math.abs(x2) - Math.abs(y2); if (z2 < 0) { var tmpx = x2; x2 = (1 - Math.abs(y2)) * (x2 >= 0 ? 1 : -1); y2 = (1 - Math.abs(tmpx)) * (y2 >= 0 ? 1 : -1); } var length = Math.sqrt(x2 * x2 + y2 * y2 + z2 * z2); return [ x2 / length, y2 / length, z2 / length ]; } function dot(x2, y2, z2, vec3) { return x2 * vec3[0] + y2 * vec3[1] + z2 * vec3[2]; } }, quantizedEncode: function(array, bytes) { let quantized, segments; if (bytes == 1) { quantized = new Uint8Array(array.length); segments = 255; } else if (bytes == 2) { quantized = new Uint16Array(array.length); segments = 65535; } else console.error("number of bytes error! "); const decodeMat = new Matrix4(); const min = new Float32Array(3); const max = new Float32Array(3); min[0] = min[1] = min[2] = Number.MAX_VALUE; max[0] = max[1] = max[2] = -Number.MAX_VALUE; for (let i = 0; i < array.length; i += 3) { min[0] = Math.min(min[0], array[i + 0]); min[1] = Math.min(min[1], array[i + 1]); min[2] = Math.min(min[2], array[i + 2]); max[0] = Math.max(max[0], array[i + 0]); max[1] = Math.max(max[1], array[i + 1]); max[2] = Math.max(max[2], array[i + 2]); } decodeMat.scale(new Vector3((max[0] - min[0]) / segments, (max[1] - min[1]) / segments, (max[2] - min[2]) / segments)); decodeMat.elements[12] = min[0]; decodeMat.elements[13] = min[1]; decodeMat.elements[14] = min[2]; decodeMat.transpose(); const multiplier = new Float32Array([ max[0] !== min[0] ? segments / (max[0] - min[0]) : 0, max[1] !== min[1] ? segments / (max[1] - min[1]) : 0, max[2] !== min[2] ? segments / (max[2] - min[2]) : 0 ]); for (let i = 0; i < array.length; i += 3) { quantized[i + 0] = Math.floor((array[i + 0] - min[0]) * multiplier[0]); quantized[i + 1] = Math.floor((array[i + 1] - min[1]) * multiplier[1]); quantized[i + 2] = Math.floor((array[i + 2] - min[2]) * multiplier[2]); } return { quantized, decodeMat }; }, quantizedEncodeUV: function(array, bytes) { let quantized, segments; if (bytes == 1) { quantized = new Uint8Array(array.length); segments = 255; } else if (bytes == 2) { quantized = new Uint16Array(array.length); segments = 65535; } else console.error("number of bytes error! "); const decodeMat = new Matrix3(); const min = new Float32Array(2); const max = new Float32Array(2); min[0] = min[1] = Number.MAX_VALUE; max[0] = max[1] = -Number.MAX_VALUE; for (let i = 0; i < array.length; i += 2) { min[0] = Math.min(min[0], array[i + 0]); min[1] = Math.min(min[1], array[i + 1]); max[0] = Math.max(max[0], array[i + 0]); max[1] = Math.max(max[1], array[i + 1]); } decodeMat.scale((max[0] - min[0]) / segments, (max[1] - min[1]) / segments); decodeMat.elements[6] = min[0]; decodeMat.elements[7] = min[1]; decodeMat.transpose(); const multiplier = new Float32Array([max[0] !== min[0] ? segments / (max[0] - min[0]) : 0, max[1] !== min[1] ? segments / (max[1] - min[1]) : 0]); for (let i = 0; i < array.length; i += 2) { quantized[i + 0] = Math.floor((array[i + 0] - min[0]) * multiplier[0]); quantized[i + 1] = Math.floor((array[i + 1] - min[1]) * multiplier[1]); } return { quantized, decodeMat }; } } }; var PackedPhongMaterial = class extends MeshPhongMaterial { constructor(parameters) { super(); this.defines = {}; this.type = "PackedPhongMaterial"; this.uniforms = UniformsUtils.merge([ShaderLib.phong.uniforms, { quantizeMatPos: { value: null }, quantizeMatUV: { value: null } }]); this.vertexShader = [ "#define PHONG", "varying vec3 vViewPosition;", "#ifndef FLAT_SHADED", "varying vec3 vNormal;", "#endif", ShaderChunk.common, ShaderChunk.uv_pars_vertex, ShaderChunk.uv2_pars_vertex, ShaderChunk.displacementmap_pars_vertex, ShaderChunk.envmap_pars_vertex, ShaderChunk.color_pars_vertex, ShaderChunk.fog_pars_vertex, ShaderChunk.morphtarget_pars_vertex, ShaderChunk.skinning_pars_vertex, ShaderChunk.shadowmap_pars_vertex, ShaderChunk.logdepthbuf_pars_vertex, ShaderChunk.clipping_planes_pars_vertex, `#ifdef USE_PACKED_NORMAL #if USE_PACKED_NORMAL == 0 vec3 decodeNormal(vec3 packedNormal) { float x = packedNormal.x * 2.0 - 1.0; float y = packedNormal.y * 2.0 - 1.0; vec2 scth = vec2(sin(x * PI), cos(x * PI)); vec2 scphi = vec2(sqrt(1.0 - y * y), y); return normalize( vec3(scth.y * scphi.x, scth.x * scphi.x, scphi.y) ); } #endif #if USE_PACKED_NORMAL == 1 vec3 decodeNormal(vec3 packedNormal) { vec3 v = vec3(packedNormal.xy, 1.0 - abs(packedNormal.x) - abs(packedNormal.y)); if (v.z < 0.0) { v.xy = (1.0 - abs(v.yx)) * vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0); } return normalize(v); } #endif #if USE_PACKED_NORMAL == 2 vec3 decodeNormal(vec3 packedNormal) { vec3 v = (packedNormal * 2.0) - 1.0; return normalize(v); } #endif #endif`, `#ifdef USE_PACKED_POSITION #if USE_PACKED_POSITION == 0 uniform mat4 quantizeMatPos; #endif #endif`, `#ifdef USE_PACKED_UV #if USE_PACKED_UV == 1 uniform mat3 quantizeMatUV; #endif #endif`, `#ifdef USE_PACKED_UV #if USE_PACKED_UV == 0 vec2 decodeUV(vec2 packedUV) { vec2 uv = (packedUV * 2.0) - 1.0; return uv; } #endif #if USE_PACKED_UV == 1 vec2 decodeUV(vec2 packedUV) { vec2 uv = ( vec3(packedUV, 1.0) * quantizeMatUV ).xy; return uv; } #endif #endif`, "void main() {", ShaderChunk.uv_vertex, `#ifdef USE_UV #ifdef USE_PACKED_UV vUv = decodeUV(vUv); #endif #endif`, ShaderChunk.uv2_vertex, ShaderChunk.color_vertex, ShaderChunk.beginnormal_vertex, `#ifdef USE_PACKED_NORMAL objectNormal = decodeNormal(objectNormal); #endif #ifdef USE_TANGENT vec3 objectTangent = vec3( tangent.xyz ); #endif `, ShaderChunk.morphnormal_vertex, ShaderChunk.skinbase_vertex, ShaderChunk.skinnormal_vertex, ShaderChunk.defaultnormal_vertex, "#ifndef FLAT_SHADED", " vNormal = normalize( transformedNormal );", "#endif", ShaderChunk.begin_vertex, `#ifdef USE_PACKED_POSITION #if USE_PACKED_POSITION == 0 transformed = ( vec4(transformed, 1.0) * quantizeMatPos ).xyz; #endif #endif`, ShaderChunk.morphtarget_vertex, ShaderChunk.skinning_vertex, ShaderChunk.displacementmap_vertex, ShaderChunk.project_vertex, ShaderChunk.logdepthbuf_vertex, ShaderChunk.clipping_planes_vertex, "vViewPosition = - mvPosition.xyz;", ShaderChunk.worldpos_vertex, ShaderChunk.envmap_vertex, ShaderChunk.shadowmap_vertex, ShaderChunk.fog_vertex, "}" ].join("\n"); this.fragmentShader = [ "#define PHONG", "uniform vec3 diffuse;", "uniform vec3 emissive;", "uniform vec3 specular;", "uniform float shininess;", "uniform float opacity;", ShaderChunk.common, ShaderChunk.packing, ShaderChunk.dithering_pars_fragment, ShaderChunk.color_pars_fragment, ShaderChunk.uv_pars_fragment, ShaderChunk.uv2_pars_fragment, ShaderChunk.map_pars_fragment, ShaderChunk.alphamap_pars_fragment, ShaderChunk.aomap_pars_fragment, ShaderChunk.lightmap_pars_fragment, ShaderChunk.emissivemap_pars_fragment, ShaderChunk.envmap_common_pars_fragment, ShaderChunk.envmap_pars_fragment, ShaderChunk.cube_uv_reflection_fragment, ShaderChunk.fog_pars_fragment, ShaderChunk.bsdfs, ShaderChunk.lights_pars_begin, ShaderChunk.lights_phong_pars_fragment, ShaderChunk.shadowmap_pars_fragment, ShaderChunk.bumpmap_pars_fragment, ShaderChunk.normalmap_pars_fragment, ShaderChunk.specularmap_pars_fragment, ShaderChunk.logdepthbuf_pars_fragment, ShaderChunk.clipping_planes_pars_fragment, "void main() {", ShaderChunk.clipping_planes_fragment, "vec4 diffuseColor = vec4( diffuse, opacity );", "ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );", "vec3 totalEmissiveRadiance = emissive;", ShaderChunk.logdepthbuf_fragment, ShaderChunk.map_fragment, ShaderChunk.color_fragment, ShaderChunk.alphamap_fragment, ShaderChunk.alphatest_fragment, ShaderChunk.specularmap_fragment, ShaderChunk.normal_fragment_begin, ShaderChunk.normal_fragment_maps, ShaderChunk.emissivemap_fragment, ShaderChunk.lights_phong_fragment, ShaderChunk.lights_fragment_begin, ShaderChunk.lights_fragment_maps, ShaderChunk.lights_fragment_end, ShaderChunk.aomap_fragment, "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;", ShaderChunk.envmap_fragment, "gl_FragColor = vec4( outgoingLight, diffuseColor.a );", ShaderChunk.tonemapping_fragment, version >= 154 ? ShaderChunk.colorspace_fragment : ShaderChunk.encodings_fragment, ShaderChunk.fog_fragment, ShaderChunk.premultiplied_alpha_fragment, ShaderChunk.dithering_fragment, "}" ].join("\n"); this.setValues(parameters); } }; //#endregion //#region node_modules/three-stdlib/shaders/BokehShader2.js var BokehShader2 = { uniforms: { textureWidth: { value: 1 }, textureHeight: { value: 1 }, focalDepth: { value: 1 }, focalLength: { value: 24 }, fstop: { value: .9 }, tColor: { value: null }, tDepth: { value: null }, maxblur: { value: 1 }, showFocus: { value: 0 }, manualdof: { value: 0 }, vignetting: { value: 0 }, depthblur: { value: 0 }, threshold: { value: .5 }, gain: { value: 2 }, bias: { value: .5 }, fringe: { value: .7 }, znear: { value: .1 }, zfar: { value: 100 }, noise: { value: 1 }, dithering: { value: 1e-4 }, pentagon: { value: 0 }, shaderFocus: { value: 1 }, focusCoords: { value: /* @__PURE__ */ new Vector2() } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` #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; } ` }; var BokehDepthShader = { uniforms: { mNear: { value: 1 }, mFar: { value: 1e3 } }, vertexShader: ` varying float vViewZDepth; void main() { #include #include vViewZDepth = - mvPosition.z; } `, fragmentShader: ` uniform float mNear; uniform float mFar; varying float vViewZDepth; void main() { float color = 1.0 - smoothstep( mNear, mFar, vViewZDepth ); gl_FragColor = vec4( vec3( color ), 1.0 ); } ` }; //#endregion //#region node_modules/three-stdlib/cameras/CinematicCamera.js var CinematicCamera = class extends PerspectiveCamera { constructor(fov, aspect, near, far) { super(fov, aspect, near, far); this.type = "CinematicCamera"; this.postprocessing = { enabled: true }; this.shaderSettings = { rings: 3, samples: 4 }; const depthShader = BokehDepthShader; this.materialDepth = new ShaderMaterial({ uniforms: depthShader.uniforms, vertexShader: depthShader.vertexShader, fragmentShader: depthShader.fragmentShader }); this.materialDepth.uniforms["mNear"].value = near; this.materialDepth.uniforms["mFar"].value = far; this.setLens(); this.initPostProcessing(); } setLens(focalLength, filmGauge, fNumber, coc) { if (focalLength === void 0) focalLength = 35; if (filmGauge !== void 0) this.filmGauge = filmGauge; this.setFocalLength(focalLength); if (fNumber === void 0) fNumber = 8; if (coc === void 0) coc = .019; this.fNumber = fNumber; this.coc = coc; this.aperture = focalLength / this.fNumber; this.hyperFocal = focalLength * focalLength / (this.aperture * this.coc); } linearize(depth) { const zfar = this.far; const znear = this.near; return -zfar * znear / (depth * (zfar - znear) - zfar); } smoothstep(near, far, depth) { const x = this.saturate((depth - near) / (far - near)); return x * x * (3 - 2 * x); } saturate(x) { return Math.max(0, Math.min(1, x)); } focusAt(focusDistance) { if (focusDistance === void 0) focusDistance = 20; const focalLength = this.getFocalLength(); this.focus = focusDistance; this.nearPoint = this.hyperFocal * this.focus / (this.hyperFocal + (this.focus - focalLength)); this.farPoint = this.hyperFocal * this.focus / (this.hyperFocal - (this.focus - focalLength)); this.depthOfField = this.farPoint - this.nearPoint; if (this.depthOfField < 0) this.depthOfField = 0; this.sdistance = this.smoothstep(this.near, this.far, this.focus); this.ldistance = this.linearize(1 - this.sdistance); this.postprocessing.bokeh_uniforms["focalDepth"].value = this.ldistance; } initPostProcessing() { if (this.postprocessing.enabled) { this.postprocessing.scene = new Scene(); this.postprocessing.camera = new OrthographicCamera(window.innerWidth / -2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / -2, -1e4, 1e4); this.postprocessing.scene.add(this.postprocessing.camera); this.postprocessing.rtTextureDepth = new WebGLRenderTarget(window.innerWidth, window.innerHeight); this.postprocessing.rtTextureColor = new WebGLRenderTarget(window.innerWidth, window.innerHeight); const bokeh_shader = BokehShader2; this.postprocessing.bokeh_uniforms = UniformsUtils.clone(bokeh_shader.uniforms); this.postprocessing.bokeh_uniforms["tColor"].value = this.postprocessing.rtTextureColor.texture; this.postprocessing.bokeh_uniforms["tDepth"].value = this.postprocessing.rtTextureDepth.texture; this.postprocessing.bokeh_uniforms["manualdof"].value = 0; this.postprocessing.bokeh_uniforms["shaderFocus"].value = 0; this.postprocessing.bokeh_uniforms["fstop"].value = 2.8; this.postprocessing.bokeh_uniforms["showFocus"].value = 1; this.postprocessing.bokeh_uniforms["focalDepth"].value = .1; this.postprocessing.bokeh_uniforms["znear"].value = this.near; this.postprocessing.bokeh_uniforms["zfar"].value = this.near; this.postprocessing.bokeh_uniforms["textureWidth"].value = window.innerWidth; this.postprocessing.bokeh_uniforms["textureHeight"].value = window.innerHeight; this.postprocessing.materialBokeh = new ShaderMaterial({ uniforms: this.postprocessing.bokeh_uniforms, vertexShader: bokeh_shader.vertexShader, fragmentShader: bokeh_shader.fragmentShader, defines: { RINGS: this.shaderSettings.rings, SAMPLES: this.shaderSettings.samples, DEPTH_PACKING: 1 } }); this.postprocessing.quad = new Mesh(new PlaneGeometry(window.innerWidth, window.innerHeight), this.postprocessing.materialBokeh); this.postprocessing.quad.position.z = -500; this.postprocessing.scene.add(this.postprocessing.quad); } } renderCinematic(scene, renderer) { if (this.postprocessing.enabled) { const currentRenderTarget = renderer.getRenderTarget(); renderer.clear(); scene.overrideMaterial = null; renderer.setRenderTarget(this.postprocessing.rtTextureColor); renderer.clear(); renderer.render(scene, this); scene.overrideMaterial = this.materialDepth; renderer.setRenderTarget(this.postprocessing.rtTextureDepth); renderer.clear(); renderer.render(scene, this); renderer.setRenderTarget(null); renderer.render(this.postprocessing.scene, this.postprocessing.camera); renderer.setRenderTarget(currentRenderTarget); } } }; //#endregion //#region node_modules/three-stdlib/math/MeshSurfaceSampler.js var _face = /* @__PURE__ */ new Triangle$1(); var _color = /* @__PURE__ */ new Vector3(); var MeshSurfaceSampler = class { constructor(mesh) { let geometry = mesh.geometry; if (geometry.index) { console.warn("THREE.MeshSurfaceSampler: Converting geometry to non-indexed BufferGeometry."); geometry = geometry.toNonIndexed(); } this.geometry = geometry; 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 i = 0; i < positionAttribute.count; i += 3) { let faceWeight = 1; if (weightAttribute) faceWeight = weightAttribute.getX(i) + weightAttribute.getX(i + 1) + weightAttribute.getX(i + 2); _face.a.fromBufferAttribute(positionAttribute, i); _face.b.fromBufferAttribute(positionAttribute, i + 1); _face.c.fromBufferAttribute(positionAttribute, i + 2); faceWeight *= _face.getArea(); faceWeights[i / 3] = faceWeight; } this.distribution = new Float32Array(positionAttribute.count / 3); let cumulativeTotal = 0; for (let i = 0; i < faceWeights.length; i++) { cumulativeTotal += faceWeights[i]; this.distribution[i] = cumulativeTotal; } return this; } setRandomGenerator(randomFunction) { this.randomFunction = randomFunction; return this; } sample(targetPosition, targetNormal, targetColor) { const faceIndex = this.sampleFaceIndex(); return this.sampleFace(faceIndex, targetPosition, 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 index = -1; while (start <= end) { const mid = Math.ceil((start + end) / 2); if (mid === 0 || dist[mid - 1] <= x && dist[mid] > x) { index = mid; break; } else if (x < dist[mid]) end = mid - 1; else start = mid + 1; } return index; } sampleFace(faceIndex, targetPosition, targetNormal, targetColor) { let u = this.randomFunction(); let v = this.randomFunction(); if (u + v > 1) { u = 1 - u; v = 1 - v; } _face.a.fromBufferAttribute(this.positionAttribute, faceIndex * 3); _face.b.fromBufferAttribute(this.positionAttribute, faceIndex * 3 + 1); _face.c.fromBufferAttribute(this.positionAttribute, faceIndex * 3 + 2); targetPosition.set(0, 0, 0).addScaledVector(_face.a, u).addScaledVector(_face.b, v).addScaledVector(_face.c, 1 - (u + v)); 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, v).addScaledVector(_face.c, 1 - (u + v)); targetColor.r = _color.x; targetColor.g = _color.y; targetColor.b = _color.z; } return this; } }; //#endregion //#region node_modules/three-stdlib/math/OBB.js var a = { c: null, u: [ /* @__PURE__ */ new Vector3(), /* @__PURE__ */ new Vector3(), /* @__PURE__ */ new Vector3() ], e: [] }; var b = { c: null, u: [ /* @__PURE__ */ new Vector3(), /* @__PURE__ */ new Vector3(), /* @__PURE__ */ new Vector3() ], e: [] }; var R = [ [], [], [] ]; var AbsR = [ [], [], [] ]; var t = []; var xAxis = /* @__PURE__ */ new Vector3(); var yAxis = /* @__PURE__ */ new Vector3(); var zAxis = /* @__PURE__ */ new Vector3(); var v1 = /* @__PURE__ */ new Vector3(); var size = /* @__PURE__ */ new Vector3(); var closestPoint = /* @__PURE__ */ new Vector3(); var rotationMatrix = /* @__PURE__ */ new Matrix3(); var aabb = /* @__PURE__ */ new Box3(); var matrix = /* @__PURE__ */ new Matrix4(); var inverse = /* @__PURE__ */ new Matrix4(); var localRay = /* @__PURE__ */ new Ray(); var OBB = class { constructor(center = new Vector3(), halfSize = new Vector3(), rotation = new Matrix3()) { this.center = center; this.halfSize = halfSize; this.rotation = rotation; } set(center, halfSize, rotation) { this.center = center; this.halfSize = halfSize; this.rotation = rotation; return this; } copy(obb2) { this.center.copy(obb2.center); this.halfSize.copy(obb2.halfSize); this.rotation.copy(obb2.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; v1.subVectors(point, this.center); this.rotation.extractBasis(xAxis, yAxis, zAxis); result.copy(this.center); const x = MathUtils.clamp(v1.dot(xAxis), -halfSize.x, halfSize.x); result.add(xAxis.multiplyScalar(x)); const y = MathUtils.clamp(v1.dot(yAxis), -halfSize.y, halfSize.y); result.add(yAxis.multiplyScalar(y)); const z = MathUtils.clamp(v1.dot(zAxis), -halfSize.z, halfSize.z); result.add(zAxis.multiplyScalar(z)); return result; } containsPoint(point) { v1.subVectors(point, this.center); this.rotation.extractBasis(xAxis, yAxis, zAxis); return Math.abs(v1.dot(xAxis)) <= this.halfSize.x && Math.abs(v1.dot(yAxis)) <= this.halfSize.y && Math.abs(v1.dot(zAxis)) <= this.halfSize.z; } 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(obb2, epsilon = Number.EPSILON) { a.c = this.center; a.e[0] = this.halfSize.x; a.e[1] = this.halfSize.y; a.e[2] = this.halfSize.z; this.rotation.extractBasis(a.u[0], a.u[1], a.u[2]); b.c = obb2.center; b.e[0] = obb2.halfSize.x; b.e[1] = obb2.halfSize.y; b.e[2] = obb2.halfSize.z; obb2.rotation.extractBasis(b.u[0], b.u[1], b.u[2]); for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) R[i][j] = a.u[i].dot(b.u[j]); v1.subVectors(b.c, a.c); t[0] = v1.dot(a.u[0]); t[1] = v1.dot(a.u[1]); t[2] = v1.dot(a.u[2]); for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) AbsR[i][j] = Math.abs(R[i][j]) + epsilon; let ra, rb; for (let i = 0; i < 3; i++) { ra = a.e[i]; rb = b.e[0] * AbsR[i][0] + b.e[1] * AbsR[i][1] + b.e[2] * AbsR[i][2]; if (Math.abs(t[i]) > ra + rb) return false; } for (let i = 0; i < 3; i++) { ra = a.e[0] * AbsR[0][i] + a.e[1] * AbsR[1][i] + a.e[2] * AbsR[2][i]; rb = b.e[i]; if (Math.abs(t[0] * R[0][i] + t[1] * R[1][i] + t[2] * R[2][i]) > 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 r = 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 d = plane.normal.dot(this.center) - plane.constant; return Math.abs(d) <= r; } /** * 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(ray, result) { this.getSize(size); aabb.setFromCenterAndSize(v1.set(0, 0, 0), size); matrix.setFromMatrix3(this.rotation); matrix.setPosition(this.center); inverse.copy(matrix).invert(); localRay.copy(ray).applyMatrix4(inverse); if (localRay.intersectBox(aabb, result)) return result.applyMatrix4(matrix); else return null; } /** * Performs a ray/OBB intersection test. Returns either true or false if * there is a intersection or not. */ intersectsRay(ray) { return this.intersectRay(ray, v1) !== null; } fromBox3(box3) { box3.getCenter(this.center); box3.getSize(this.halfSize).multiplyScalar(.5); this.rotation.identity(); return this; } equals(obb2) { return obb2.center.equals(this.center) && obb2.halfSize.equals(this.halfSize) && obb2.rotation.equals(this.rotation); } applyMatrix4(matrix2) { const e = matrix2.elements; let sx = v1.set(e[0], e[1], e[2]).length(); const sy = v1.set(e[4], e[5], e[6]).length(); const sz = v1.set(e[8], e[9], e[10]).length(); if (matrix2.determinant() < 0) sx = -sx; rotationMatrix.setFromMatrix4(matrix2); const invSX = 1 / sx; const invSY = 1 / sy; const invSZ = 1 / sz; rotationMatrix.elements[0] *= invSX; rotationMatrix.elements[1] *= invSX; rotationMatrix.elements[2] *= invSX; rotationMatrix.elements[3] *= invSY; rotationMatrix.elements[4] *= invSY; rotationMatrix.elements[5] *= invSY; rotationMatrix.elements[6] *= invSZ; rotationMatrix.elements[7] *= invSZ; rotationMatrix.elements[8] *= invSZ; this.rotation.multiply(rotationMatrix); this.halfSize.x *= sx; this.halfSize.y *= sy; this.halfSize.z *= sz; v1.setFromMatrixPosition(matrix2); this.center.add(v1); return this; } }; var obb = /* @__PURE__ */ new OBB(); //#endregion //#region node_modules/three-stdlib/math/Capsule.js var _v1$3 = /* @__PURE__ */ new Vector3(); var _v2$3 = /* @__PURE__ */ new Vector3(); var _v3 = /* @__PURE__ */ 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(target) { return target.copy(this.end).add(this.start).multiplyScalar(.5); } translate(v) { this.start.add(v); this.end.add(v); } 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 r = _v1$3.copy(line1.end).sub(line1.start); const s = _v2$3.copy(line2.end).sub(line2.start); const w = _v3.copy(line2.start).sub(line1.start); const a = r.dot(s), b = r.dot(r), c = s.dot(s), d = s.dot(w), e = r.dot(w); let t1, t2; const divisor = b * c - a * a; if (Math.abs(divisor) < EPS) { const d1 = -d / c; const d2 = (a - d) / c; if (Math.abs(d1 - .5) < Math.abs(d2 - .5)) { t1 = 0; t2 = d1; } else { t1 = 1; t2 = d2; } } else { t1 = (d * a + e * c) / divisor; t2 = (t1 * a - d) / c; } t2 = Math.max(0, Math.min(1, t2)); t1 = Math.max(0, Math.min(1, t1)); return [r.multiplyScalar(t1).add(line1.start), s.multiplyScalar(t2).add(line2.start)]; } }; //#endregion //#region node_modules/three-stdlib/math/ColorConverter.js var _hsl = {}; var ColorConverter = { setHSV(color, h, s, v) { h = MathUtils.euclideanModulo(h, 1); s = MathUtils.clamp(s, 0, 1); v = MathUtils.clamp(v, 0, 1); return color.setHSL(h, s * v / ((h = (2 - s) * v) < 1 ? h : 2 - h), h * .5); }, getHSV(color, target) { color.getHSL(_hsl); _hsl.s *= _hsl.l < .5 ? _hsl.l : 1 - _hsl.l; target.h = _hsl.h; target.s = 2 * _hsl.s / (_hsl.l + _hsl.s); target.v = _hsl.l + _hsl.s; return target; }, setCMYK(color, c, m, y, k) { const r = (1 - c) * (1 - k); const g = (1 - m) * (1 - k); const b = (1 - y) * (1 - k); return color.setRGB(r, g, b); }, getCMYK(color, target) { const r = color.r; const g = color.g; const b = color.b; const k = 1 - Math.max(r, g, b); const c = (1 - r - k) / (1 - k); const m = (1 - g - k) / (1 - k); const y = (1 - b - k) / (1 - k); target.c = c; target.m = m; target.y = y; target.k = k; return target; } }; //#endregion //#region node_modules/three-stdlib/math/ImprovedNoise.js function init$2() { 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 i = 0; i < 256; i++) _p2[256 + i] = _p2[i]; return _p2; } var _p = /* @__PURE__ */ init$2(); function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); } function lerp(t, a, b) { return a + t * (b - a); } function grad(hash, x, y, z) { const h = hash & 15; const u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z; return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); } var ImprovedNoise = class { noise(x, y, z) { const floorX = Math.floor(x), floorY = Math.floor(y), floorZ = Math.floor(z); const X = floorX & 255, Y = floorY & 255, Z = floorZ & 255; x -= floorX; y -= floorY; z -= floorZ; const xMinus1 = x - 1, yMinus1 = y - 1, zMinus1 = z - 1; const u = fade(x), v = fade(y), w = fade(z); const A = _p[X] + Y, AA = _p[A] + Z, AB = _p[A + 1] + Z, B = _p[X + 1] + Y, BA = _p[B] + Z, BB = _p[B + 1] + Z; return lerp(w, lerp(v, lerp(u, grad(_p[AA], x, y, z), grad(_p[BA], xMinus1, y, z)), lerp(u, grad(_p[AB], x, yMinus1, z), grad(_p[BB], xMinus1, yMinus1, z))), lerp(v, lerp(u, grad(_p[AA + 1], x, y, zMinus1), grad(_p[BA + 1], xMinus1, y, zMinus1)), lerp(u, grad(_p[AB + 1], x, yMinus1, zMinus1), grad(_p[BB + 1], xMinus1, yMinus1, zMinus1)))); } }; //#endregion //#region node_modules/three-stdlib/math/Octree.js var _v1$2 = /* @__PURE__ */ new Vector3(); var _v2$2 = /* @__PURE__ */ new Vector3(); var _plane$1 = /* @__PURE__ */ new Plane(); var _line1 = /* @__PURE__ */ new Line3(); var _line2 = /* @__PURE__ */ new Line3(); var _sphere$1 = /* @__PURE__ */ new Sphere(); var _capsule = /* @__PURE__ */ new Capsule(); var Octree = class Octree { constructor(box) { this.triangles = []; this.box = box; this.subTrees = []; } addTriangle(triangle) { if (!this.bounds) this.bounds = new Box3(); this.bounds.min.x = Math.min(this.bounds.min.x, triangle.a.x, triangle.b.x, triangle.c.x); this.bounds.min.y = Math.min(this.bounds.min.y, triangle.a.y, triangle.b.y, triangle.c.y); this.bounds.min.z = Math.min(this.bounds.min.z, triangle.a.z, triangle.b.z, triangle.c.z); this.bounds.max.x = Math.max(this.bounds.max.x, triangle.a.x, triangle.b.x, triangle.c.x); this.bounds.max.y = Math.max(this.bounds.max.y, triangle.a.y, triangle.b.y, triangle.c.y); this.bounds.max.z = Math.max(this.bounds.max.z, triangle.a.z, triangle.b.z, triangle.c.z); this.triangles.push(triangle); return this; } calcBox() { this.box = this.bounds.clone(); this.box.min.x -= .01; this.box.min.y -= .01; this.box.min.z -= .01; return this; } split(level) { if (!this.box) return; const subTrees = []; const halfsize = _v2$2.copy(this.box.max).sub(this.box.min).multiplyScalar(.5); for (let x = 0; x < 2; x++) for (let y = 0; y < 2; y++) for (let z = 0; z < 2; z++) { const box = new Box3(); const v = _v1$2.set(x, y, z); box.min.copy(this.box.min).add(v.multiply(halfsize)); box.max.copy(box.min).add(halfsize); subTrees.push(new Octree(box)); } let triangle; while (triangle = this.triangles.pop()) for (let i = 0; i < subTrees.length; i++) if (subTrees[i].box.intersectsTriangle(triangle)) subTrees[i].triangles.push(triangle); for (let i = 0; i < subTrees.length; i++) { const len = subTrees[i].triangles.length; if (len > 8 && level < 16) subTrees[i].split(level + 1); if (len !== 0) this.subTrees.push(subTrees[i]); } return this; } build() { this.calcBox(); this.split(0); return this; } getRayTriangles(ray, triangles) { for (let i = 0; i < this.subTrees.length; i++) { const subTree = this.subTrees[i]; if (!ray.intersectsBox(subTree.box)) continue; if (subTree.triangles.length > 0) { for (let j = 0; j < subTree.triangles.length; j++) if (triangles.indexOf(subTree.triangles[j]) === -1) triangles.push(subTree.triangles[j]); } else subTree.getRayTriangles(ray, triangles); } return triangles; } triangleCapsuleIntersect(capsule, triangle) { triangle.getPlane(_plane$1); const d1 = _plane$1.distanceToPoint(capsule.start) - capsule.radius; const d2 = _plane$1.distanceToPoint(capsule.end) - capsule.radius; if (d1 > 0 && d2 > 0 || d1 < -capsule.radius && d2 < -capsule.radius) return false; const delta = Math.abs(d1 / (Math.abs(d1) + Math.abs(d2))); const intersectPoint = _v1$2.copy(capsule.start).lerp(capsule.end, delta); if (triangle.containsPoint(intersectPoint)) return { normal: _plane$1.normal.clone(), point: intersectPoint.clone(), depth: Math.abs(Math.min(d1, d2)) }; const r2 = capsule.radius * capsule.radius; const line1 = _line1.set(capsule.start, capsule.end); const lines = [ [triangle.a, triangle.b], [triangle.b, triangle.c], [triangle.c, triangle.a] ]; for (let i = 0; i < lines.length; i++) { const line2 = _line2.set(lines[i][0], lines[i][1]); const [point1, point2] = capsule.lineLineMinimumPoints(line1, line2); if (point1.distanceToSquared(point2) < r2) return { normal: point1.clone().sub(point2).normalize(), point: point2.clone(), depth: capsule.radius - point1.distanceTo(point2) }; } return false; } triangleSphereIntersect(sphere, triangle) { triangle.getPlane(_plane$1); if (!sphere.intersectsPlane(_plane$1)) return false; const depth = Math.abs(_plane$1.distanceToSphere(sphere)); const r2 = sphere.radius * sphere.radius - depth * depth; const plainPoint = _plane$1.projectPoint(sphere.center, _v1$2); if (triangle.containsPoint(sphere.center)) return { normal: _plane$1.normal.clone(), point: plainPoint.clone(), depth: Math.abs(_plane$1.distanceToSphere(sphere)) }; const lines = [ [triangle.a, triangle.b], [triangle.b, triangle.c], [triangle.c, triangle.a] ]; for (let i = 0; i < lines.length; i++) { _line1.set(lines[i][0], lines[i][1]); _line1.closestPointToPoint(plainPoint, true, _v2$2); const d = _v2$2.distanceToSquared(sphere.center); if (d < r2) return { normal: sphere.center.clone().sub(_v2$2).normalize(), point: _v2$2.clone(), depth: sphere.radius - Math.sqrt(d) }; } return false; } getSphereTriangles(sphere, triangles) { for (let i = 0; i < this.subTrees.length; i++) { const subTree = this.subTrees[i]; if (!sphere.intersectsBox(subTree.box)) continue; if (subTree.triangles.length > 0) { for (let j = 0; j < subTree.triangles.length; j++) if (triangles.indexOf(subTree.triangles[j]) === -1) triangles.push(subTree.triangles[j]); } else subTree.getSphereTriangles(sphere, triangles); } } getCapsuleTriangles(capsule, triangles) { for (let i = 0; i < this.subTrees.length; i++) { const subTree = this.subTrees[i]; if (!capsule.intersectsBox(subTree.box)) continue; if (subTree.triangles.length > 0) { for (let j = 0; j < subTree.triangles.length; j++) if (triangles.indexOf(subTree.triangles[j]) === -1) triangles.push(subTree.triangles[j]); } else subTree.getCapsuleTriangles(capsule, triangles); } } sphereIntersect(sphere) { _sphere$1.copy(sphere); const triangles = []; let result, hit = false; this.getSphereTriangles(sphere, triangles); for (let i = 0; i < triangles.length; i++) if (result = this.triangleSphereIntersect(_sphere$1, triangles[i])) { hit = true; _sphere$1.center.add(result.normal.multiplyScalar(result.depth)); } if (hit) { const collisionVector = _sphere$1.center.clone().sub(sphere.center); const depth = collisionVector.length(); return { normal: collisionVector.normalize(), depth }; } return false; } capsuleIntersect(capsule) { _capsule.copy(capsule); const triangles = []; let result, hit = false; this.getCapsuleTriangles(_capsule, triangles); for (let i = 0; i < triangles.length; i++) if (result = this.triangleCapsuleIntersect(_capsule, triangles[i])) { hit = true; _capsule.translate(result.normal.multiplyScalar(result.depth)); } if (hit) { const collisionVector = _capsule.getCenter(new Vector3()).sub(capsule.getCenter(_v1$2)); const depth = collisionVector.length(); return { normal: collisionVector.normalize(), depth }; } return false; } rayIntersect(ray) { if (ray.direction.length() === 0) return; const triangles = []; let triangle, position, distance = 1e100; this.getRayTriangles(ray, triangles); for (let i = 0; i < triangles.length; i++) { const result = ray.intersectTriangle(triangles[i].a, triangles[i].b, triangles[i].c, true, _v1$2); if (result) { const newdistance = result.sub(ray.origin).length(); if (distance > newdistance) { position = result.clone().add(ray.origin); distance = newdistance; triangle = triangles[i]; } } } return distance < 1e100 ? { distance, triangle, position } : false; } fromGraphNode(group) { group.updateWorldMatrix(true, true); group.traverse((obj) => { if (obj.isMesh === true) { let geometry, isTemp = false; if (obj.geometry.index !== null) { isTemp = true; geometry = obj.geometry.toNonIndexed(); } else geometry = obj.geometry; const positionAttribute = geometry.getAttribute("position"); for (let i = 0; i < positionAttribute.count; i += 3) { const v1 = new Vector3().fromBufferAttribute(positionAttribute, i); const v2 = new Vector3().fromBufferAttribute(positionAttribute, i + 1); const v3 = new Vector3().fromBufferAttribute(positionAttribute, i + 2); v1.applyMatrix4(obj.matrixWorld); v2.applyMatrix4(obj.matrixWorld); v3.applyMatrix4(obj.matrixWorld); this.addTriangle(new Triangle$1(v1, v2, v3)); } if (isTemp) geometry.dispose(); } }); this.build(); return this; } }; //#endregion //#region node_modules/three-stdlib/math/Lut.js var Lut = class { constructor(colormap, count = 32) { this.isLut = true; this.lut = []; this.map = []; this.n = 0; this.minV = 0; this.maxV = 1; this.setColorMap(colormap, count); } set(value) { if (value.isLut === true) this.copy(value); return this; } setMin(min) { this.minV = min; return this; } setMax(max) { this.maxV = max; return this; } setColorMap(colormap, count = 32) { this.map = ColorMapKeywords[colormap] || ColorMapKeywords.rainbow; this.n = count; const step = 1 / this.n; const minColor = new Color(); const maxColor = new Color(); this.lut.length = 0; this.lut.push(new Color(this.map[0][1])); for (let i = 1; i < count; i++) { const alpha = i * step; for (let j = 0; j < this.map.length - 1; j++) if (alpha > this.map[j][0] && alpha <= this.map[j + 1][0]) { const min = this.map[j][0]; const max = this.map[j + 1][0]; minColor.setHex(this.map[j][1], "srgb-linear"); maxColor.setHex(this.map[j + 1][1], "srgb-linear"); const color = new Color().lerpColors(minColor, maxColor, (alpha - min) / (max - min)); this.lut.push(color); } } this.lut.push(new Color(this.map[this.map.length - 1][1])); return this; } copy(lut) { this.lut = lut.lut; this.map = lut.map; this.n = lut.n; this.minV = lut.minV; this.maxV = lut.maxV; return this; } getColor(alpha) { alpha = MathUtils.clamp(alpha, this.minV, this.maxV); alpha = (alpha - this.minV) / (this.maxV - this.minV); const colorPosition = Math.round(alpha * this.n); return this.lut[colorPosition]; } addColorMap(name, arrayOfColors) { ColorMapKeywords[name] = arrayOfColors; return this; } createCanvas() { const canvas = document.createElement("canvas"); canvas.width = 1; canvas.height = this.n; this.updateCanvas(canvas); return canvas; } updateCanvas(canvas) { const ctx = canvas.getContext("2d", { alpha: false }); const imageData = ctx.getImageData(0, 0, 1, this.n); const data = imageData.data; let k = 0; const step = 1 / this.n; const minColor = new Color(); const maxColor = new Color(); const finalColor = new Color(); for (let i = 1; i >= 0; i -= step) for (let j = this.map.length - 1; j >= 0; j--) if (i < this.map[j][0] && i >= this.map[j - 1][0]) { const min = this.map[j - 1][0]; const max = this.map[j][0]; minColor.setHex(this.map[j - 1][1], "srgb-linear"); maxColor.setHex(this.map[j][1], "srgb-linear"); finalColor.lerpColors(minColor, maxColor, (i - min) / (max - min)); data[k * 4] = Math.round(finalColor.r * 255); data[k * 4 + 1] = Math.round(finalColor.g * 255); data[k * 4 + 2] = Math.round(finalColor.b * 255); data[k * 4 + 3] = 255; k += 1; } ctx.putImageData(imageData, 0, 0); return canvas; } }; var ColorMapKeywords = { rainbow: [ [0, 255], [.2, 65535], [.5, 65280], [.8, 16776960], [1, 16711680] ], cooltowarm: [ [0, 3952322], [.2, 10206463], [.5, 14474460], [.8, 16163717], [1, 11797542] ], blackbody: [ [0, 0], [.2, 7864320], [.5, 15086080], [.8, 16776960], [1, 16777215] ], grayscale: [ [0, 0], [.2, 4210752], [.5, 8355712], [.8, 12566463], [1, 16777215] ] }; //#endregion //#region node_modules/three-stdlib/controls/EventDispatcher.js var __defProp$38 = Object.defineProperty; var __defNormalProp$38 = (obj, key, value) => key in obj ? __defProp$38(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$38 = (obj, key, value) => { __defNormalProp$38(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var EventDispatcher = class { constructor() { __publicField$38(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 listenerArray = this._listeners[type]; if (listenerArray !== void 0) { const index = listenerArray.indexOf(listener); if (index !== -1) listenerArray.splice(index, 1); } } /** * Fire an event type. * @param event The event that gets fired. */ dispatchEvent(event) { if (this._listeners === void 0) return; const listenerArray = this._listeners[event.type]; if (listenerArray !== void 0) { event.target = this; const array = listenerArray.slice(0); for (let i = 0, l = array.length; i < l; i++) array[i].call(this, event); event.target = null; } } }; //#endregion //#region node_modules/three-stdlib/controls/experimental/CameraControls.js var __defProp$37 = Object.defineProperty; var __defNormalProp$37 = (obj, key, value) => key in obj ? __defProp$37(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$37 = (obj, key, value) => { __defNormalProp$37(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var STATE$1 = { NONE: -1, ROTATE: 0, DOLLY: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_PAN: 4, TOUCH_DOLLY_PAN: 5, TOUCH_DOLLY_ROTATE: 6 }; var CameraControls = class extends EventDispatcher { constructor(object, domElement) { super(); __publicField$37(this, "object"); __publicField$37(this, "domElement"); /** Set to false to disable this control */ __publicField$37(this, "enabled", true); /** "target" sets the location of focus, where the object orbits around */ __publicField$37(this, "target", new Vector3()); /** Set to true to enable trackball behavior */ __publicField$37(this, "trackball", false); /** How far you can dolly in ( PerspectiveCamera only ) */ __publicField$37(this, "minDistance", 0); /** How far you can dolly out ( PerspectiveCamera only ) */ __publicField$37(this, "maxDistance", Infinity); __publicField$37(this, "minZoom", 0); __publicField$37(this, "maxZoom", Infinity); __publicField$37(this, "minPolarAngle", 0); __publicField$37(this, "maxPolarAngle", Math.PI); __publicField$37(this, "minAzimuthAngle", -Infinity); __publicField$37(this, "maxAzimuthAngle", Infinity); __publicField$37(this, "enableDamping", false); __publicField$37(this, "dampingFactor", .05); /** * This option enables dollying in and out; property named as "zoom" for backwards compatibility * Set to false to disable zooming */ __publicField$37(this, "enableZoom", true); __publicField$37(this, "zoomSpeed", 1); /** Set to false to disable rotating */ __publicField$37(this, "enableRotate", true); __publicField$37(this, "rotateSpeed", 1); /** Set to false to disable panning */ __publicField$37(this, "enablePan", true); __publicField$37(this, "panSpeed", 1); /** if true, pan in screen-space */ __publicField$37(this, "screenSpacePanning", false); /** pixels moved per arrow key push */ __publicField$37(this, "keyPanSpeed", 7); /** * Set to true to automatically rotate around the target * If auto-rotate is enabled, you must call controls.update() in your animation loop * auto-rotate is not supported for trackball behavior */ __publicField$37(this, "autoRotate", false); __publicField$37(this, "autoRotateSpeed", 2); /** Set to false to disable use of the keys */ __publicField$37(this, "enableKeys", true); /** The four arrow keys */ __publicField$37(this, "keys", { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" }); __publicField$37(this, "mouseButtons"); /** Touch fingers */ __publicField$37(this, "touches", { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }); __publicField$37(this, "target0"); __publicField$37(this, "position0"); __publicField$37(this, "quaternion0"); __publicField$37(this, "zoom0"); __publicField$37(this, "spherical", new Spherical()); __publicField$37(this, "sphericalDelta", new Spherical()); __publicField$37(this, "changeEvent", { type: "change" }); __publicField$37(this, "startEvent", { type: "start" }); __publicField$37(this, "endEvent", { type: "end" }); __publicField$37(this, "state", STATE$1.NONE); __publicField$37(this, "EPS", 1e-6); __publicField$37(this, "scale", 1); __publicField$37(this, "panOffset", new Vector3()); __publicField$37(this, "zoomChanged", false); __publicField$37(this, "rotateStart", new Vector2()); __publicField$37(this, "rotateEnd", new Vector2()); __publicField$37(this, "rotateDelta", new Vector2()); __publicField$37(this, "panStart", new Vector2()); __publicField$37(this, "panEnd", new Vector2()); __publicField$37(this, "panDelta", new Vector2()); __publicField$37(this, "dollyStart", new Vector2()); __publicField$37(this, "dollyEnd", new Vector2()); __publicField$37(this, "dollyDelta", new Vector2()); __publicField$37(this, "offset", new Vector3()); __publicField$37(this, "lastPosition", new Vector3()); __publicField$37(this, "lastQuaternion", new Quaternion()); __publicField$37(this, "q", new Quaternion()); __publicField$37(this, "v", new Vector3()); __publicField$37(this, "vec", new Vector3()); __publicField$37(this, "quat"); __publicField$37(this, "quatInverse"); __publicField$37(this, "getPolarAngle", () => this.spherical.phi); __publicField$37(this, "getAzimuthalAngle", () => this.spherical.theta); __publicField$37(this, "saveState", () => { this.target0.copy(this.target); this.position0.copy(this.object.position); this.quaternion0.copy(this.object.quaternion); this.zoom0 = this.object.zoom; }); __publicField$37(this, "reset", () => { this.target.copy(this.target0); this.object.position.copy(this.position0); this.object.quaternion.copy(this.quaternion0); this.object.zoom = this.zoom0; this.object.updateProjectionMatrix(); this.dispatchEvent(this.changeEvent); this.update(); this.state = STATE$1.NONE; }); __publicField$37(this, "dispose", () => { this.domElement.removeEventListener("contextmenu", this.onContextMenu, false); this.domElement.removeEventListener("mousedown", this.onMouseDown, false); this.domElement.removeEventListener("wheel", this.onMouseWheel, false); this.domElement.removeEventListener("touchstart", this.onTouchStart, false); this.domElement.removeEventListener("touchend", this.onTouchEnd, false); this.domElement.removeEventListener("touchmove", this.onTouchMove, false); document.removeEventListener("mousemove", this.onMouseMove, false); document.removeEventListener("mouseup", this.onMouseUp, false); this.domElement.removeEventListener("keydown", this.onKeyDown, false); }); __publicField$37(this, "update", () => { const position = this.object.position; this.offset.copy(position).sub(this.target); if (this.trackball) { if (this.sphericalDelta.theta) { this.vec.set(0, 1, 0).applyQuaternion(this.object.quaternion); const factor = this.enableDamping ? this.dampingFactor : 1; this.q.setFromAxisAngle(this.vec, this.sphericalDelta.theta * factor); this.object.quaternion.premultiply(this.q); this.offset.applyQuaternion(this.q); } if (this.sphericalDelta.phi) { this.vec.set(1, 0, 0).applyQuaternion(this.object.quaternion); const factor = this.enableDamping ? this.dampingFactor : 1; this.q.setFromAxisAngle(this.vec, this.sphericalDelta.phi * factor); this.object.quaternion.premultiply(this.q); this.offset.applyQuaternion(this.q); } this.offset.multiplyScalar(this.scale); this.offset.clampLength(this.minDistance, this.maxDistance); } else { this.offset.applyQuaternion(this.quat); if (this.autoRotate && this.state === STATE$1.NONE) this.rotateLeft(this.getAutoRotationAngle()); this.spherical.setFromVector3(this.offset); if (this.enableDamping) { this.spherical.theta += this.sphericalDelta.theta * this.dampingFactor; this.spherical.phi += this.sphericalDelta.phi * this.dampingFactor; } else { this.spherical.theta += this.sphericalDelta.theta; this.spherical.phi += this.sphericalDelta.phi; } this.spherical.theta = Math.max(this.minAzimuthAngle, Math.min(this.maxAzimuthAngle, this.spherical.theta)); this.spherical.phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, this.spherical.phi)); this.spherical.makeSafe(); this.spherical.radius *= this.scale; this.spherical.radius = Math.max(this.minDistance, Math.min(this.maxDistance, this.spherical.radius)); this.offset.setFromSpherical(this.spherical); this.offset.applyQuaternion(this.quatInverse); } if (this.enableDamping === true) this.target.addScaledVector(this.panOffset, this.dampingFactor); else this.target.add(this.panOffset); position.copy(this.target).add(this.offset); if (this.trackball === false) this.object.lookAt(this.target); if (this.enableDamping === true) { this.sphericalDelta.theta *= 1 - this.dampingFactor; this.sphericalDelta.phi *= 1 - this.dampingFactor; this.panOffset.multiplyScalar(1 - this.dampingFactor); } else { this.sphericalDelta.set(0, 0, 0); this.panOffset.set(0, 0, 0); } this.scale = 1; if (this.zoomChanged || this.lastPosition.distanceToSquared(this.object.position) > this.EPS || 8 * (1 - this.lastQuaternion.dot(this.object.quaternion)) > this.EPS) { this.dispatchEvent(this.changeEvent); this.lastPosition.copy(this.object.position); this.lastQuaternion.copy(this.object.quaternion); this.zoomChanged = false; return true; } return false; }); __publicField$37(this, "getAutoRotationAngle", () => 2 * Math.PI / 60 / 60 * this.autoRotateSpeed); __publicField$37(this, "getZoomScale", () => Math.pow(.95, this.zoomSpeed)); __publicField$37(this, "rotateLeft", (angle) => { this.sphericalDelta.theta -= angle; }); __publicField$37(this, "rotateUp", (angle) => { this.sphericalDelta.phi -= angle; }); __publicField$37(this, "panLeft", (distance, objectMatrix) => { this.v.setFromMatrixColumn(objectMatrix, 0); this.v.multiplyScalar(-distance); this.panOffset.add(this.v); }); __publicField$37(this, "panUp", (distance, objectMatrix) => { if (this.screenSpacePanning === true) this.v.setFromMatrixColumn(objectMatrix, 1); else { this.v.setFromMatrixColumn(objectMatrix, 0); this.v.crossVectors(this.object.up, this.v); } this.v.multiplyScalar(distance); this.panOffset.add(this.v); }); __publicField$37(this, "pan", (deltaX, deltaY) => { const element = this.domElement; if (this.object instanceof PerspectiveCamera) { const position = this.object.position; this.offset.copy(position).sub(this.target); let targetDistance = this.offset.length(); targetDistance *= Math.tan(this.object.fov / 2 * Math.PI / 180); this.panLeft(2 * deltaX * targetDistance / element.clientHeight, this.object.matrix); this.panUp(2 * deltaY * targetDistance / element.clientHeight, this.object.matrix); } else if (this.object.isOrthographicCamera) { this.panLeft(deltaX * (this.object.right - this.object.left) / this.object.zoom / element.clientWidth, this.object.matrix); this.panUp(deltaY * (this.object.top - this.object.bottom) / this.object.zoom / element.clientHeight, this.object.matrix); } else { console.warn("WARNING: CameraControls.js encountered an unknown camera type - pan disabled."); this.enablePan = false; } }); __publicField$37(this, "dollyIn", (dollyScale) => { if (this.object instanceof PerspectiveCamera) this.scale /= dollyScale; else if (this.object instanceof OrthographicCamera) { this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom * dollyScale)); this.object.updateProjectionMatrix(); this.zoomChanged = true; } else { console.warn("WARNING: CameraControls.js encountered an unknown camera type - dolly/zoom disabled."); this.enableZoom = false; } }); __publicField$37(this, "dollyOut", (dollyScale) => { if (this.object instanceof PerspectiveCamera) this.scale *= dollyScale; else if (this.object instanceof OrthographicCamera) { this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / dollyScale)); this.object.updateProjectionMatrix(); this.zoomChanged = true; } else { console.warn("WARNING: CameraControls.js encountered an unknown camera type - dolly/zoom disabled."); this.enableZoom = false; } }); __publicField$37(this, "handleMouseDownRotate", (event) => { this.rotateStart.set(event.clientX, event.clientY); }); __publicField$37(this, "handleMouseDownDolly", (event) => { this.dollyStart.set(event.clientX, event.clientY); }); __publicField$37(this, "handleMouseDownPan", (event) => { this.panStart.set(event.clientX, event.clientY); }); __publicField$37(this, "handleMouseMoveRotate", (event) => { this.rotateEnd.set(event.clientX, event.clientY); this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart).multiplyScalar(this.rotateSpeed); const element = this.domElement; this.rotateLeft(2 * Math.PI * this.rotateDelta.x / element.clientHeight); this.rotateUp(2 * Math.PI * this.rotateDelta.y / element.clientHeight); this.rotateStart.copy(this.rotateEnd); this.update(); }); __publicField$37(this, "handleMouseMoveDolly", (event) => { this.dollyEnd.set(event.clientX, event.clientY); this.dollyDelta.subVectors(this.dollyEnd, this.dollyStart); if (this.dollyDelta.y > 0) this.dollyIn(this.getZoomScale()); else if (this.dollyDelta.y < 0) this.dollyOut(this.getZoomScale()); this.dollyStart.copy(this.dollyEnd); this.update(); }); __publicField$37(this, "handleMouseMovePan", (event) => { this.panEnd.set(event.clientX, event.clientY); this.panDelta.subVectors(this.panEnd, this.panStart).multiplyScalar(this.panSpeed); this.pan(this.panDelta.x, this.panDelta.y); this.panStart.copy(this.panEnd); this.update(); }); __publicField$37(this, "handleMouseWheel", (event) => { if (event.deltaY < 0) this.dollyOut(this.getZoomScale()); else if (event.deltaY > 0) this.dollyIn(this.getZoomScale()); this.update(); }); __publicField$37(this, "handleKeyDown", (event) => { let needsUpdate = false; switch (event.code) { case this.keys.UP: this.pan(0, this.keyPanSpeed); needsUpdate = true; break; case this.keys.BOTTOM: this.pan(0, -this.keyPanSpeed); needsUpdate = true; break; case this.keys.LEFT: this.pan(this.keyPanSpeed, 0); needsUpdate = true; break; case this.keys.RIGHT: this.pan(-this.keyPanSpeed, 0); needsUpdate = true; break; } if (needsUpdate) { event.preventDefault(); this.update(); } }); __publicField$37(this, "handleTouchStartRotate", (event) => { if (event.touches.length == 1) this.rotateStart.set(event.touches[0].pageX, event.touches[0].pageY); else { const x = .5 * (event.touches[0].pageX + event.touches[1].pageX); const y = .5 * (event.touches[0].pageY + event.touches[1].pageY); this.rotateStart.set(x, y); } }); __publicField$37(this, "handleTouchStartPan", (event) => { if (event.touches.length == 1) this.panStart.set(event.touches[0].pageX, event.touches[0].pageY); else { const x = .5 * (event.touches[0].pageX + event.touches[1].pageX); const y = .5 * (event.touches[0].pageY + event.touches[1].pageY); this.panStart.set(x, y); } }); __publicField$37(this, "handleTouchStartDolly", (event) => { const dx = event.touches[0].pageX - event.touches[1].pageX; const dy = event.touches[0].pageY - event.touches[1].pageY; const distance = Math.sqrt(dx * dx + dy * dy); this.dollyStart.set(0, distance); }); __publicField$37(this, "handleTouchStartDollyPan", (event) => { if (this.enableZoom) this.handleTouchStartDolly(event); if (this.enablePan) this.handleTouchStartPan(event); }); __publicField$37(this, "handleTouchStartDollyRotate", (event) => { if (this.enableZoom) this.handleTouchStartDolly(event); if (this.enableRotate) this.handleTouchStartRotate(event); }); __publicField$37(this, "handleTouchMoveRotate", (event) => { if (event.touches.length == 1) this.rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY); else { const x = .5 * (event.touches[0].pageX + event.touches[1].pageX); const y = .5 * (event.touches[0].pageY + event.touches[1].pageY); this.rotateEnd.set(x, y); } this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart).multiplyScalar(this.rotateSpeed); const element = this.domElement; this.rotateLeft(2 * Math.PI * this.rotateDelta.x / element.clientHeight); this.rotateUp(2 * Math.PI * this.rotateDelta.y / element.clientHeight); this.rotateStart.copy(this.rotateEnd); }); __publicField$37(this, "handleTouchMovePan", (event) => { if (event.touches.length == 1) this.panEnd.set(event.touches[0].pageX, event.touches[0].pageY); else { const x = .5 * (event.touches[0].pageX + event.touches[1].pageX); const y = .5 * (event.touches[0].pageY + event.touches[1].pageY); this.panEnd.set(x, y); } this.panDelta.subVectors(this.panEnd, this.panStart).multiplyScalar(this.panSpeed); this.pan(this.panDelta.x, this.panDelta.y); this.panStart.copy(this.panEnd); }); __publicField$37(this, "handleTouchMoveDolly", (event) => { const dx = event.touches[0].pageX - event.touches[1].pageX; const dy = event.touches[0].pageY - event.touches[1].pageY; const distance = Math.sqrt(dx * dx + dy * dy); this.dollyEnd.set(0, distance); this.dollyDelta.set(0, Math.pow(this.dollyEnd.y / this.dollyStart.y, this.zoomSpeed)); this.dollyIn(this.dollyDelta.y); this.dollyStart.copy(this.dollyEnd); }); __publicField$37(this, "handleTouchMoveDollyPan", (event) => { if (this.enableZoom) this.handleTouchMoveDolly(event); if (this.enablePan) this.handleTouchMovePan(event); }); __publicField$37(this, "handleTouchMoveDollyRotate", (event) => { if (this.enableZoom) this.handleTouchMoveDolly(event); if (this.enableRotate) this.handleTouchMoveRotate(event); }); __publicField$37(this, "onMouseDown", (event) => { if (this.enabled === false) return; event.preventDefault(); this.domElement.focus ? this.domElement.focus() : window.focus(); let mouseAction; switch (event.button) { case 0: mouseAction = this.mouseButtons.LEFT; break; case 1: mouseAction = this.mouseButtons.MIDDLE; break; case 2: mouseAction = this.mouseButtons.RIGHT; break; default: mouseAction = -1; } switch (mouseAction) { case MOUSE.DOLLY: if (this.enableZoom === false) return; this.handleMouseDownDolly(event); this.state = STATE$1.DOLLY; break; case MOUSE.ROTATE: if (event.ctrlKey || event.metaKey || event.shiftKey) { if (this.enablePan === false) return; this.handleMouseDownPan(event); this.state = STATE$1.PAN; } else { if (this.enableRotate === false) return; this.handleMouseDownRotate(event); this.state = STATE$1.ROTATE; } break; case MOUSE.PAN: if (event.ctrlKey || event.metaKey || event.shiftKey) { if (this.enableRotate === false) return; this.handleMouseDownRotate(event); this.state = STATE$1.ROTATE; } else { if (this.enablePan === false) return; this.handleMouseDownPan(event); this.state = STATE$1.PAN; } break; default: this.state = STATE$1.NONE; } if (this.state !== STATE$1.NONE) { document.addEventListener("mousemove", this.onMouseMove, false); document.addEventListener("mouseup", this.onMouseUp, false); this.dispatchEvent(this.startEvent); } }); __publicField$37(this, "onMouseMove", (event) => { if (this.enabled === false) return; event.preventDefault(); switch (this.state) { case STATE$1.ROTATE: if (this.enableRotate === false) return; this.handleMouseMoveRotate(event); break; case STATE$1.DOLLY: if (this.enableZoom === false) return; this.handleMouseMoveDolly(event); break; case STATE$1.PAN: if (this.enablePan === false) return; this.handleMouseMovePan(event); break; } }); __publicField$37(this, "onMouseUp", () => { if (this.enabled === false) return; document.removeEventListener("mousemove", this.onMouseMove, false); document.removeEventListener("mouseup", this.onMouseUp, false); this.dispatchEvent(this.endEvent); this.state = STATE$1.NONE; }); __publicField$37(this, "onMouseWheel", (event) => { if (this.enabled === false || this.enableZoom === false || this.state !== STATE$1.NONE && this.state !== STATE$1.ROTATE) return; event.preventDefault(); this.dispatchEvent(this.startEvent); this.handleMouseWheel(event); this.dispatchEvent(this.endEvent); }); __publicField$37(this, "onKeyDown", (event) => { if (this.enabled === false || this.enableKeys === false || this.enablePan === false) return; this.handleKeyDown(event); }); __publicField$37(this, "onTouchStart", (event) => { if (this.enabled === false) return; event.preventDefault(); switch (event.touches.length) { case 1: switch (this.touches.ONE) { case TOUCH.ROTATE: if (this.enableRotate === false) return; this.handleTouchStartRotate(event); this.state = STATE$1.TOUCH_ROTATE; break; case TOUCH.PAN: if (this.enablePan === false) return; this.handleTouchStartPan(event); this.state = STATE$1.TOUCH_PAN; break; default: this.state = STATE$1.NONE; } break; case 2: switch (this.touches.TWO) { case TOUCH.DOLLY_PAN: if (this.enableZoom === false && this.enablePan === false) return; this.handleTouchStartDollyPan(event); this.state = STATE$1.TOUCH_DOLLY_PAN; break; case TOUCH.DOLLY_ROTATE: if (this.enableZoom === false && this.enableRotate === false) return; this.handleTouchStartDollyRotate(event); this.state = STATE$1.TOUCH_DOLLY_ROTATE; break; default: this.state = STATE$1.NONE; } break; default: this.state = STATE$1.NONE; } if (this.state !== STATE$1.NONE) this.dispatchEvent(this.startEvent); }); __publicField$37(this, "onTouchMove", (event) => { if (this.enabled === false) return; event.preventDefault(); switch (this.state) { case STATE$1.TOUCH_ROTATE: if (this.enableRotate === false) return; this.handleTouchMoveRotate(event); this.update(); break; case STATE$1.TOUCH_PAN: if (this.enablePan === false) return; this.handleTouchMovePan(event); this.update(); break; case STATE$1.TOUCH_DOLLY_PAN: if (this.enableZoom === false && this.enablePan === false) return; this.handleTouchMoveDollyPan(event); this.update(); break; case STATE$1.TOUCH_DOLLY_ROTATE: if (this.enableZoom === false && this.enableRotate === false) return; this.handleTouchMoveDollyRotate(event); this.update(); break; default: this.state = STATE$1.NONE; } }); __publicField$37(this, "onTouchEnd", () => { if (this.enabled === false) return; this.dispatchEvent(this.endEvent); this.state = STATE$1.NONE; }); __publicField$37(this, "onContextMenu", (event) => { if (this.enabled === false) return; event.preventDefault(); }); if (domElement === void 0) console.warn("THREE.CameraControls: The second parameter \"domElement\" is now mandatory."); if (domElement instanceof Document) console.error("THREE.CameraControls: \"document\" should not be used as the target \"domElement\". Please use \"renderer.domElement\" instead."); this.object = object; this.domElement = domElement; this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; this.target0 = this.target.clone(); this.position0 = this.object.position.clone(); this.quaternion0 = this.object.quaternion.clone(); this.zoom0 = this.object.zoom; this.quat = new Quaternion().setFromUnitVectors(this.object.up, new Vector3(0, 1, 0)); this.quatInverse = this.quat.clone().invert(); this.lastPosition = new Vector3(); this.lastQuaternion = new Quaternion(); this.domElement.addEventListener("contextmenu", this.onContextMenu, false); this.domElement.addEventListener("mousedown", this.onMouseDown, false); this.domElement.addEventListener("wheel", this.onMouseWheel, false); this.domElement.addEventListener("touchstart", this.onTouchStart, false); this.domElement.addEventListener("touchend", this.onTouchEnd, false); this.domElement.addEventListener("touchmove", this.onTouchMove, false); this.domElement.addEventListener("keydown", this.onKeyDown, false); if (this.domElement.tabIndex === -1) this.domElement.tabIndex = 0; this.object.lookAt(this.target); this.update(); this.saveState(); } handleMouseUp() {} handleTouchEnd() {} }; var OrbitControlsExp = class extends CameraControls { constructor(object, domElement) { super(object, domElement); __publicField$37(this, "mouseButtons"); __publicField$37(this, "touches"); this.mouseButtons = { LEFT: MOUSE.ROTATE, RIGHT: MOUSE.PAN }; this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; } }; var MapControlsExp = class extends CameraControls { constructor(object, domElement) { super(object, domElement); __publicField$37(this, "mouseButtons"); __publicField$37(this, "touches"); this.mouseButtons = { LEFT: MOUSE.PAN, RIGHT: MOUSE.ROTATE }; this.touches = { ONE: TOUCH.PAN, TWO: TOUCH.DOLLY_ROTATE }; } }; var TrackballControlsExp = class extends CameraControls { constructor(object, domElement) { super(object, domElement); __publicField$37(this, "trackball"); __publicField$37(this, "screenSpacePanning"); __publicField$37(this, "autoRotate"); __publicField$37(this, "mouseButtons"); __publicField$37(this, "touches"); this.trackball = true; this.screenSpacePanning = true; this.autoRotate = false; this.mouseButtons = { LEFT: MOUSE.ROTATE, RIGHT: MOUSE.PAN }; this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; } }; //#endregion //#region node_modules/three-stdlib/controls/FirstPersonControls.js var __defProp$36 = Object.defineProperty; var __defNormalProp$36 = (obj, key, value) => key in obj ? __defProp$36(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$36 = (obj, key, value) => { __defNormalProp$36(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var targetPosition = /* @__PURE__ */ new Vector3(); var FirstPersonControls = class extends EventDispatcher { constructor(object, domElement) { super(); __publicField$36(this, "object"); __publicField$36(this, "domElement"); __publicField$36(this, "enabled", true); __publicField$36(this, "movementSpeed", 1); __publicField$36(this, "lookSpeed", .005); __publicField$36(this, "lookVertical", true); __publicField$36(this, "autoForward", false); __publicField$36(this, "activeLook", true); __publicField$36(this, "heightSpeed", false); __publicField$36(this, "heightCoef", 1); __publicField$36(this, "heightMin", 0); __publicField$36(this, "heightMax", 1); __publicField$36(this, "constrainVertical", false); __publicField$36(this, "verticalMin", 0); __publicField$36(this, "verticalMax", Math.PI); __publicField$36(this, "mouseDragOn", false); __publicField$36(this, "autoSpeedFactor", 0); __publicField$36(this, "mouseX", 0); __publicField$36(this, "mouseY", 0); __publicField$36(this, "moveForward", false); __publicField$36(this, "moveBackward", false); __publicField$36(this, "moveLeft", false); __publicField$36(this, "moveRight", false); __publicField$36(this, "moveUp", false); __publicField$36(this, "moveDown", false); __publicField$36(this, "viewHalfX", 0); __publicField$36(this, "viewHalfY", 0); __publicField$36(this, "lat", 0); __publicField$36(this, "lon", 0); __publicField$36(this, "lookDirection", new Vector3()); __publicField$36(this, "spherical", new Spherical()); __publicField$36(this, "target", new Vector3()); __publicField$36(this, "connect", (domElement) => { domElement.setAttribute("tabindex", "-1"); domElement.style.touchAction = "none"; domElement.addEventListener("contextmenu", this.contextmenu); domElement.addEventListener("mousemove", this.onMouseMove); domElement.addEventListener("mousedown", this.onMouseDown); domElement.addEventListener("mouseup", this.onMouseUp); this.domElement = domElement; window.addEventListener("keydown", this.onKeyDown); window.addEventListener("keyup", this.onKeyUp); this.handleResize(); }); __publicField$36(this, "dispose", () => { var _a, _b, _c, _d; (_a = this.domElement) == null || _a.removeEventListener("contextmenu", this.contextmenu); (_b = this.domElement) == null || _b.removeEventListener("mousedown", this.onMouseDown); (_c = this.domElement) == null || _c.removeEventListener("mousemove", this.onMouseMove); (_d = this.domElement) == null || _d.removeEventListener("mouseup", this.onMouseUp); window.removeEventListener("keydown", this.onKeyDown); window.removeEventListener("keyup", this.onKeyUp); }); __publicField$36(this, "handleResize", () => { if (this.domElement) { this.viewHalfX = this.domElement.offsetWidth / 2; this.viewHalfY = this.domElement.offsetHeight / 2; } }); __publicField$36(this, "onMouseDown", (event) => { var _a; (_a = this.domElement) == null || _a.focus(); if (this.activeLook) switch (event.button) { case 0: this.moveForward = true; break; case 2: this.moveBackward = true; break; } this.mouseDragOn = true; }); __publicField$36(this, "onMouseUp", (event) => { if (this.activeLook) switch (event.button) { case 0: this.moveForward = false; break; case 2: this.moveBackward = false; break; } this.mouseDragOn = false; }); __publicField$36(this, "onMouseMove", (event) => { if (this.domElement) { this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX; this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY; } }); __publicField$36(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; } }); __publicField$36(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; } }); __publicField$36(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; }); __publicField$36(this, "update", (delta) => { if (!this.enabled) return; if (this.heightSpeed) { const heightDelta = MathUtils.clamp(this.object.position.y, this.heightMin, this.heightMax) - 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 position = this.object.position; targetPosition.setFromSphericalCoords(1, phi, theta).add(position); this.object.lookAt(targetPosition); }); __publicField$36(this, "contextmenu", (event) => event.preventDefault()); __publicField$36(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); } }; //#endregion //#region node_modules/three-stdlib/controls/TransformControls.js var __defProp$35 = Object.defineProperty; var __defNormalProp$35 = (obj, key, value) => key in obj ? __defProp$35(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$35 = (obj, key, value) => { __defNormalProp$35(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var TransformControls = class extends Object3D { constructor(camera, domElement) { super(); __publicField$35(this, "isTransformControls", true); __publicField$35(this, "visible", false); __publicField$35(this, "domElement"); __publicField$35(this, "raycaster", new Raycaster()); __publicField$35(this, "gizmo"); __publicField$35(this, "plane"); __publicField$35(this, "tempVector", new Vector3()); __publicField$35(this, "tempVector2", new Vector3()); __publicField$35(this, "tempQuaternion", new Quaternion()); __publicField$35(this, "unit", { X: new Vector3(1, 0, 0), Y: new Vector3(0, 1, 0), Z: new Vector3(0, 0, 1) }); __publicField$35(this, "pointStart", new Vector3()); __publicField$35(this, "pointEnd", new Vector3()); __publicField$35(this, "offset", new Vector3()); __publicField$35(this, "rotationAxis", new Vector3()); __publicField$35(this, "startNorm", new Vector3()); __publicField$35(this, "endNorm", new Vector3()); __publicField$35(this, "rotationAngle", 0); __publicField$35(this, "cameraPosition", new Vector3()); __publicField$35(this, "cameraQuaternion", new Quaternion()); __publicField$35(this, "cameraScale", new Vector3()); __publicField$35(this, "parentPosition", new Vector3()); __publicField$35(this, "parentQuaternion", new Quaternion()); __publicField$35(this, "parentQuaternionInv", new Quaternion()); __publicField$35(this, "parentScale", new Vector3()); __publicField$35(this, "worldPositionStart", new Vector3()); __publicField$35(this, "worldQuaternionStart", new Quaternion()); __publicField$35(this, "worldScaleStart", new Vector3()); __publicField$35(this, "worldPosition", new Vector3()); __publicField$35(this, "worldQuaternion", new Quaternion()); __publicField$35(this, "worldQuaternionInv", new Quaternion()); __publicField$35(this, "worldScale", new Vector3()); __publicField$35(this, "eye", new Vector3()); __publicField$35(this, "positionStart", new Vector3()); __publicField$35(this, "quaternionStart", new Quaternion()); __publicField$35(this, "scaleStart", new Vector3()); __publicField$35(this, "camera"); __publicField$35(this, "object"); __publicField$35(this, "enabled", true); __publicField$35(this, "axis", null); __publicField$35(this, "mode", "translate"); __publicField$35(this, "translationSnap", null); __publicField$35(this, "rotationSnap", null); __publicField$35(this, "scaleSnap", null); __publicField$35(this, "space", "world"); __publicField$35(this, "size", 1); __publicField$35(this, "dragging", false); __publicField$35(this, "showX", true); __publicField$35(this, "showY", true); __publicField$35(this, "showZ", true); __publicField$35(this, "changeEvent", { type: "change" }); __publicField$35(this, "mouseDownEvent", { type: "mouseDown", mode: this.mode }); __publicField$35(this, "mouseUpEvent", { type: "mouseUp", mode: this.mode }); __publicField$35(this, "objectChangeEvent", { type: "objectChange" }); __publicField$35(this, "intersectObjectWithRay", (object, raycaster, includeInvisible) => { const allIntersections = raycaster.intersectObject(object, true); for (let i = 0; i < allIntersections.length; i++) if (allIntersections[i].object.visible || includeInvisible) return allIntersections[i]; return false; }); __publicField$35(this, "attach", (object) => { this.object = object; this.visible = true; return this; }); __publicField$35(this, "detach", () => { this.object = void 0; this.visible = false; this.axis = null; return this; }); __publicField$35(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; }); __publicField$35(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(); }); __publicField$35(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; }); __publicField$35(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); } }); __publicField$35(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 d = this.pointEnd.length() / this.pointStart.length(); if (this.pointEnd.dot(this.pointStart) < 0) d *= -1; this.tempVector2.set(d, d, d); } 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); }); __publicField$35(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; }); __publicField$35(this, "getPointer", (event) => { var _a; if (this.domElement && ((_a = this.domElement.ownerDocument) == null ? void 0 : _a.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 }; } }); __publicField$35(this, "onPointerHover", (event) => { if (!this.enabled) return; switch (event.pointerType) { case "mouse": case "pen": this.pointerHover(this.getPointer(event)); break; } }); __publicField$35(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)); }); __publicField$35(this, "onPointerMove", (event) => { if (!this.enabled) return; this.pointerMove(this.getPointer(event)); }); __publicField$35(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)); }); __publicField$35(this, "getMode", () => this.mode); __publicField$35(this, "setMode", (mode) => { this.mode = mode; }); __publicField$35(this, "setTranslationSnap", (translationSnap) => { this.translationSnap = translationSnap; }); __publicField$35(this, "setRotationSnap", (rotationSnap) => { this.rotationSnap = rotationSnap; }); __publicField$35(this, "setScaleSnap", (scaleSnap) => { this.scaleSnap = scaleSnap; }); __publicField$35(this, "setSize", (size) => { this.size = size; }); __publicField$35(this, "setSpace", (space) => { this.space = space; }); __publicField$35(this, "update", () => { console.warn("THREE.TransformControls: update function has no more functionality and therefore has been deprecated."); }); __publicField$35(this, "connect", (domElement) => { if (domElement === document) console.error("THREE.OrbitControls: \"document\" should not be used as the target \"domElement\". Please use \"renderer.domElement\" instead."); this.domElement = domElement; this.domElement.addEventListener("pointerdown", this.onPointerDown); this.domElement.addEventListener("pointermove", this.onPointerHover); this.domElement.ownerDocument.addEventListener("pointerup", this.onPointerUp); }); __publicField$35(this, "dispose", () => { var _a, _b, _c, _d, _e, _f; (_a = this.domElement) == null || _a.removeEventListener("pointerdown", this.onPointerDown); (_b = this.domElement) == null || _b.removeEventListener("pointermove", this.onPointerHover); (_d = (_c = this.domElement) == null ? void 0 : _c.ownerDocument) == null || _d.removeEventListener("pointermove", this.onPointerMove); (_f = (_e = this.domElement) == null ? void 0 : _e.ownerDocument) == null || _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(); __publicField$35(this, "isTransformControlsGizmo", true); __publicField$35(this, "type", "TransformControlsGizmo"); __publicField$35(this, "tempVector", new Vector3(0, 0, 0)); __publicField$35(this, "tempEuler", new Euler()); __publicField$35(this, "alignVector", new Vector3(0, 1, 0)); __publicField$35(this, "zeroVector", new Vector3(0, 0, 0)); __publicField$35(this, "lookAtMatrix", new Matrix4()); __publicField$35(this, "tempQuaternion", new Quaternion()); __publicField$35(this, "tempQuaternion2", new Quaternion()); __publicField$35(this, "identityQuaternion", new Quaternion()); __publicField$35(this, "unitX", new Vector3(1, 0, 0)); __publicField$35(this, "unitY", new Vector3(0, 1, 0)); __publicField$35(this, "unitZ", new Vector3(0, 0, 1)); __publicField$35(this, "gizmo"); __publicField$35(this, "picker"); __publicField$35(this, "helper"); __publicField$35(this, "rotationAxis", new Vector3()); __publicField$35(this, "cameraPosition", new Vector3()); __publicField$35(this, "worldPositionStart", new Vector3()); __publicField$35(this, "worldQuaternionStart", new Quaternion()); __publicField$35(this, "worldPosition", new Vector3()); __publicField$35(this, "worldQuaternion", new Quaternion()); __publicField$35(this, "eye", new Vector3()); __publicField$35(this, "camera", null); __publicField$35(this, "enabled", true); __publicField$35(this, "axis", null); __publicField$35(this, "mode", "translate"); __publicField$35(this, "space", "world"); __publicField$35(this, "size", 1); __publicField$35(this, "dragging", false); __publicField$35(this, "showX", true); __publicField$35(this, "showY", true); __publicField$35(this, "showZ", true); __publicField$35(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 i = 0; i < handles.length; i++) { const handle = handles[i]; handle.visible = true; handle.rotation.set(0, 0, 0); handle.position.copy(this.worldPosition); let factor; if (this.camera.isOrthographicCamera) factor = (this.camera.top - this.camera.bottom) / this.camera.zoom; else factor = this.worldPosition.distanceTo(this.cameraPosition) * Math.min(1.9 * Math.tan(Math.PI * this.camera.fov / 360) / this.camera.zoom, 7); handle.scale.set(1, 1, 1).multiplyScalar(factor * this.size / 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)) > .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)) > .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)) > .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 = .99; const PLANE_HIDE_TRESHOLD = .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 *= .5; handle.material.color.lerp(new Color(1, 1, 1), .5); } else if (this.axis) if (handle.name === this.axis) { handle.material.opacity = 1; handle.material.color.lerp(new Color(1, 1, 1), .5); } else if (this.axis.split("").some(function(a) { return handle.name === a; })) { handle.material.opacity = 1; handle.material.color.lerp(new Color(1, 1, 1), .5); } else { handle.material.opacity *= .25; handle.material.color.lerp(new Color(1, 1, 1), .5); } } super.updateMatrixWorld(); }); const gizmoMaterial = new MeshBasicMaterial({ depthTest: false, depthWrite: false, transparent: true, side: 2, 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 = .15; const matHelper = gizmoMaterial.clone(); matHelper.opacity = .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 = .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); gizmoMaterial.clone().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 = .25; const arrowGeometry = new CylinderGeometry(0, .05, .2, 12, 1, false); const scaleHandleGeometry = new BoxGeometry(.125, .125, .125); const lineGeometry = new BufferGeometry(); lineGeometry.setAttribute("position", new Float32BufferAttribute([ 0, 0, 0, 1, 0, 0 ], 3)); const CircleGeometry = (radius, arc) => { const geometry = new BufferGeometry(); const vertices = []; for (let i = 0; i <= 64 * arc; ++i) vertices.push(0, Math.cos(i / 32 * Math.PI) * radius, Math.sin(i / 32 * Math.PI) * radius); geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); return geometry; }; const TranslateHelperGeometry = () => { const geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute([ 0, 0, 0, 1, 1, 1 ], 3)); return geometry; }; const gizmoTranslate = { X: [ [ new Mesh(arrowGeometry, matRed), [ 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(.1, 0), matWhiteTransparent.clone()), [ 0, 0, 0 ], [ 0, 0, 0 ] ]], XY: [ [new Mesh(new PlaneGeometry(.295, .295), matYellowTransparent.clone()), [ .15, .15, 0 ]], [ new Line(lineGeometry, matLineYellow), [ .18, .3, 0 ], null, [ .125, 1, 1 ] ], [ new Line(lineGeometry, matLineYellow), [ .3, .18, 0 ], [ 0, 0, Math.PI / 2 ], [ .125, 1, 1 ] ] ], YZ: [ [ new Mesh(new PlaneGeometry(.295, .295), matCyanTransparent.clone()), [ 0, .15, .15 ], [ 0, Math.PI / 2, 0 ] ], [ new Line(lineGeometry, matLineCyan), [ 0, .18, .3 ], [ 0, 0, Math.PI / 2 ], [ .125, 1, 1 ] ], [ new Line(lineGeometry, matLineCyan), [ 0, .3, .18 ], [ 0, -Math.PI / 2, 0 ], [ .125, 1, 1 ] ] ], XZ: [ [ new Mesh(new PlaneGeometry(.295, .295), matMagentaTransparent.clone()), [ .15, 0, .15 ], [ -Math.PI / 2, 0, 0 ] ], [ new Line(lineGeometry, matLineMagenta), [ .18, 0, .3 ], null, [ .125, 1, 1 ] ], [ new Line(lineGeometry, matLineMagenta), [ .3, 0, .18 ], [ 0, -Math.PI / 2, 0 ], [ .125, 1, 1 ] ] ] }; const pickerTranslate = { X: [[ new Mesh(new CylinderGeometry(.2, 0, 1, 4, 1, false), matInvisible), [ .6, 0, 0 ], [ 0, 0, -Math.PI / 2 ] ]], Y: [[new Mesh(new CylinderGeometry(.2, 0, 1, 4, 1, false), matInvisible), [ 0, .6, 0 ]]], Z: [[ new Mesh(new CylinderGeometry(.2, 0, 1, 4, 1, false), matInvisible), [ 0, 0, .6 ], [ Math.PI / 2, 0, 0 ] ]], XYZ: [[new Mesh(new OctahedronGeometry(.2, 0), matInvisible)]], XY: [[new Mesh(new PlaneGeometry(.4, .4), matInvisible), [ .2, .2, 0 ]]], YZ: [[ new Mesh(new PlaneGeometry(.4, .4), matInvisible), [ 0, .2, .2 ], [ 0, Math.PI / 2, 0 ] ]], XZ: [[ new Mesh(new PlaneGeometry(.4, .4), matInvisible), [ .2, 0, .2 ], [ -Math.PI / 2, 0, 0 ] ]] }; const helperTranslate = { START: [[ new Mesh(new OctahedronGeometry(.01, 2), matHelper), null, null, null, "helper" ]], END: [[ new Mesh(new OctahedronGeometry(.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, .5), matLineRed)], [ new Mesh(new OctahedronGeometry(.04, 0), matRed), [ 0, 0, .99 ], null, [ 1, 3, 1 ] ]], Y: [[ new Line(CircleGeometry(1, .5), matLineGreen), null, [ 0, 0, -Math.PI / 2 ] ], [ new Mesh(new OctahedronGeometry(.04, 0), matGreen), [ 0, 0, .99 ], null, [ 3, 1, 1 ] ]], Z: [[ new Line(CircleGeometry(1, .5), matLineBlue), null, [ 0, Math.PI / 2, 0 ] ], [ new Mesh(new OctahedronGeometry(.04, 0), matBlue), [ .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(.03, 0, .15, 4, 1, false), matLineYellowTransparent), [ 1.17, 0, 0 ], [ 0, 0, -Math.PI / 2 ], [ 1, 1, .001 ] ], [ new Mesh(new CylinderGeometry(.03, 0, .15, 4, 1, false), matLineYellowTransparent), [ -1.17, 0, 0 ], [ 0, 0, Math.PI / 2 ], [ 1, 1, .001 ] ], [ new Mesh(new CylinderGeometry(.03, 0, .15, 4, 1, false), matLineYellowTransparent), [ 0, -1.17, 0 ], [ Math.PI, 0, 0 ], [ 1, 1, .001 ] ], [ new Mesh(new CylinderGeometry(.03, 0, .15, 4, 1, false), matLineYellowTransparent), [ 0, 1.17, 0 ], [ 0, 0, 0 ], [ 1, 1, .001 ] ] ], 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, .1, 4, 24), matInvisible), [ 0, 0, 0 ], [ 0, -Math.PI / 2, -Math.PI / 2 ] ]], Y: [[ new Mesh(new TorusGeometry(1, .1, 4, 24), matInvisible), [ 0, 0, 0 ], [ Math.PI / 2, 0, 0 ] ]], Z: [[ new Mesh(new TorusGeometry(1, .1, 4, 24), matInvisible), [ 0, 0, 0 ], [ 0, 0, -Math.PI / 2 ] ]], E: [[new Mesh(new TorusGeometry(1.25, .1, 2, 24), matInvisible)]], XYZE: [[new Mesh(new SphereGeometry(.7, 10, 8), matInvisible)]] }; const gizmoScale = { X: [[ new Mesh(scaleHandleGeometry, matRed), [ .8, 0, 0 ], [ 0, 0, -Math.PI / 2 ] ], [ new Line(lineGeometry, matLineRed), null, null, [ .8, 1, 1 ] ]], Y: [[new Mesh(scaleHandleGeometry, matGreen), [ 0, .8, 0 ]], [ new Line(lineGeometry, matLineGreen), null, [ 0, 0, Math.PI / 2 ], [ .8, 1, 1 ] ]], Z: [[ new Mesh(scaleHandleGeometry, matBlue), [ 0, 0, .8 ], [ Math.PI / 2, 0, 0 ] ], [ new Line(lineGeometry, matLineBlue), null, [ 0, -Math.PI / 2, 0 ], [ .8, 1, 1 ] ]], XY: [ [ new Mesh(scaleHandleGeometry, matYellowTransparent), [ .85, .85, 0 ], null, [ 2, 2, .2 ] ], [ new Line(lineGeometry, matLineYellow), [ .855, .98, 0 ], null, [ .125, 1, 1 ] ], [ new Line(lineGeometry, matLineYellow), [ .98, .855, 0 ], [ 0, 0, Math.PI / 2 ], [ .125, 1, 1 ] ] ], YZ: [ [ new Mesh(scaleHandleGeometry, matCyanTransparent), [ 0, .85, .85 ], null, [ .2, 2, 2 ] ], [ new Line(lineGeometry, matLineCyan), [ 0, .855, .98 ], [ 0, 0, Math.PI / 2 ], [ .125, 1, 1 ] ], [ new Line(lineGeometry, matLineCyan), [ 0, .98, .855 ], [ 0, -Math.PI / 2, 0 ], [ .125, 1, 1 ] ] ], XZ: [ [ new Mesh(scaleHandleGeometry, matMagentaTransparent), [ .85, 0, .85 ], null, [ 2, .2, 2 ] ], [ new Line(lineGeometry, matLineMagenta), [ .855, 0, .98 ], null, [ .125, 1, 1 ] ], [ new Line(lineGeometry, matLineMagenta), [ .98, 0, .855 ], [ 0, -Math.PI / 2, 0 ], [ .125, 1, 1 ] ] ], XYZX: [[new Mesh(new BoxGeometry(.125, .125, .125), matWhiteTransparent.clone()), [ 1.1, 0, 0 ]]], XYZY: [[new Mesh(new BoxGeometry(.125, .125, .125), matWhiteTransparent.clone()), [ 0, 1.1, 0 ]]], XYZZ: [[new Mesh(new BoxGeometry(.125, .125, .125), matWhiteTransparent.clone()), [ 0, 0, 1.1 ]]] }; const pickerScale = { X: [[ new Mesh(new CylinderGeometry(.2, 0, .8, 4, 1, false), matInvisible), [ .5, 0, 0 ], [ 0, 0, -Math.PI / 2 ] ]], Y: [[new Mesh(new CylinderGeometry(.2, 0, .8, 4, 1, false), matInvisible), [ 0, .5, 0 ]]], Z: [[ new Mesh(new CylinderGeometry(.2, 0, .8, 4, 1, false), matInvisible), [ 0, 0, .5 ], [ Math.PI / 2, 0, 0 ] ]], XY: [[ new Mesh(scaleHandleGeometry, matInvisible), [ .85, .85, 0 ], null, [ 3, 3, .2 ] ]], YZ: [[ new Mesh(scaleHandleGeometry, matInvisible), [ 0, .85, .85 ], null, [ .2, 3, 3 ] ]], XZ: [[ new Mesh(scaleHandleGeometry, matInvisible), [ .85, 0, .85 ], null, [ 3, .2, 3 ] ]], XYZX: [[new Mesh(new BoxGeometry(.2, .2, .2), matInvisible), [ 1.1, 0, 0 ]]], XYZY: [[new Mesh(new BoxGeometry(.2, .2, .2), matInvisible), [ 0, 1.1, 0 ]]], XYZZ: [[new Mesh(new BoxGeometry(.2, .2, .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 i = gizmoMap[name].length; i--;) { const object = gizmoMap[name][i][0].clone(); const position = gizmoMap[name][i][1]; const rotation = gizmoMap[name][i][2]; const scale = gizmoMap[name][i][3]; const tag = gizmoMap[name][i][4]; object.name = name; object.tag = tag; if (position) object.position.set(position[0], position[1], position[2]); if (rotation) object.rotation.set(rotation[0], rotation[1], rotation[2]); if (scale) object.scale.set(scale[0], scale[1], scale[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: 2, transparent: true, opacity: .1, toneMapped: false })); __publicField$35(this, "isTransformControlsPlane", true); __publicField$35(this, "type", "TransformControlsPlane"); __publicField$35(this, "unitX", new Vector3(1, 0, 0)); __publicField$35(this, "unitY", new Vector3(0, 1, 0)); __publicField$35(this, "unitZ", new Vector3(0, 0, 1)); __publicField$35(this, "tempVector", new Vector3()); __publicField$35(this, "dirVector", new Vector3()); __publicField$35(this, "alignVector", new Vector3()); __publicField$35(this, "tempMatrix", new Matrix4()); __publicField$35(this, "identityQuaternion", new Quaternion()); __publicField$35(this, "cameraQuaternion", new Quaternion()); __publicField$35(this, "worldPosition", new Vector3()); __publicField$35(this, "worldQuaternion", new Quaternion()); __publicField$35(this, "eye", new Vector3()); __publicField$35(this, "axis", null); __publicField$35(this, "mode", "translate"); __publicField$35(this, "space", "world"); __publicField$35(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; 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(); }); } }; //#endregion //#region node_modules/three-stdlib/controls/DragControls.js var __defProp$34 = Object.defineProperty; var __defNormalProp$34 = (obj, key, value) => key in obj ? __defProp$34(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$34 = (obj, key, value) => { __defNormalProp$34(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var DragControls = class extends EventDispatcher { constructor(_objects, _camera, _domElement) { super(); __publicField$34(this, "enabled", true); __publicField$34(this, "transformGroup", false); __publicField$34(this, "_objects"); __publicField$34(this, "_camera"); __publicField$34(this, "_domElement"); __publicField$34(this, "_plane", new Plane()); __publicField$34(this, "_raycaster", new Raycaster()); __publicField$34(this, "_mouse", new Vector2()); __publicField$34(this, "_offset", new Vector3()); __publicField$34(this, "_intersection", new Vector3()); __publicField$34(this, "_worldPosition", new Vector3()); __publicField$34(this, "_inverseMatrix", new Matrix4()); __publicField$34(this, "_intersections", []); __publicField$34(this, "_selected", null); __publicField$34(this, "_hovered", null); __publicField$34(this, "activate", () => { this._domElement.addEventListener("pointermove", this.onPointerMove); this._domElement.addEventListener("pointerdown", this.onPointerDown); this._domElement.addEventListener("pointerup", this.onPointerCancel); this._domElement.addEventListener("pointerleave", this.onPointerCancel); this._domElement.addEventListener("touchmove", this.onTouchMove); this._domElement.addEventListener("touchstart", this.onTouchStart); this._domElement.addEventListener("touchend", this.onTouchEnd); }); __publicField$34(this, "deactivate", () => { this._domElement.removeEventListener("pointermove", this.onPointerMove); this._domElement.removeEventListener("pointerdown", this.onPointerDown); this._domElement.removeEventListener("pointerup", this.onPointerCancel); this._domElement.removeEventListener("pointerleave", this.onPointerCancel); this._domElement.removeEventListener("touchmove", this.onTouchMove); this._domElement.removeEventListener("touchstart", this.onTouchStart); this._domElement.removeEventListener("touchend", this.onTouchEnd); this._domElement.style.cursor = ""; }); __publicField$34(this, "dispose", () => this.deactivate()); __publicField$34(this, "getObjects", () => this._objects); __publicField$34(this, "getRaycaster", () => this._raycaster); __publicField$34(this, "onMouseMove", (event) => { const rect = this._domElement.getBoundingClientRect(); this._mouse.x = (event.clientX - rect.left) / rect.width * 2 - 1; this._mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; this._raycaster.setFromCamera(this._mouse, this._camera); if (this._selected && this.enabled) { if (this._raycaster.ray.intersectPlane(this._plane, this._intersection)) this._selected.position.copy(this._intersection.sub(this._offset).applyMatrix4(this._inverseMatrix)); this.dispatchEvent({ type: "drag", object: this._selected }); return; } this._intersections.length = 0; this._raycaster.setFromCamera(this._mouse, this._camera); this._raycaster.intersectObjects(this._objects, true, this._intersections); if (this._intersections.length > 0) { const object = this._intersections[0].object; this._plane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._plane.normal), this._worldPosition.setFromMatrixPosition(object.matrixWorld)); if (this._hovered !== object) { this.dispatchEvent({ type: "hoveron", object }); this._domElement.style.cursor = "pointer"; this._hovered = object; } } else if (this._hovered !== null) { this.dispatchEvent({ type: "hoveroff", object: this._hovered }); this._domElement.style.cursor = "auto"; this._hovered = null; } }); __publicField$34(this, "onMouseDown", () => { this._intersections.length = 0; this._raycaster.setFromCamera(this._mouse, this._camera); this._raycaster.intersectObjects(this._objects, true, this._intersections); if (this._intersections.length > 0) { this._selected = this.transformGroup === true ? this._objects[0] : this._intersections[0].object; if (this._raycaster.ray.intersectPlane(this._plane, this._intersection) && this._selected.parent) { this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(); this._offset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)); } this._domElement.style.cursor = "move"; this.dispatchEvent({ type: "dragstart", object: this._selected }); } }); __publicField$34(this, "onMouseCancel", () => { if (this._selected) { this.dispatchEvent({ type: "dragend", object: this._selected }); this._selected = null; } this._domElement.style.cursor = this._hovered ? "pointer" : "auto"; }); __publicField$34(this, "onPointerMove", (event) => { switch (event.pointerType) { case "mouse": case "pen": this.onMouseMove(event); break; } }); __publicField$34(this, "onPointerDown", (event) => { switch (event.pointerType) { case "mouse": case "pen": this.onMouseDown(); break; } }); __publicField$34(this, "onPointerCancel", (event) => { switch (event.pointerType) { case "mouse": case "pen": this.onMouseCancel(); break; } }); __publicField$34(this, "onTouchMove", (event) => { event.preventDefault(); const newEvent = event.changedTouches[0]; const rect = this._domElement.getBoundingClientRect(); this._mouse.x = (newEvent.clientX - rect.left) / rect.width * 2 - 1; this._mouse.y = -((newEvent.clientY - rect.top) / rect.height) * 2 + 1; this._raycaster.setFromCamera(this._mouse, this._camera); if (this._selected && this.enabled) { if (this._raycaster.ray.intersectPlane(this._plane, this._intersection)) this._selected.position.copy(this._intersection.sub(this._offset).applyMatrix4(this._inverseMatrix)); this.dispatchEvent({ type: "drag", object: this._selected }); return; } }); __publicField$34(this, "onTouchStart", (event) => { event.preventDefault(); const newEvent = event.changedTouches[0]; const rect = this._domElement.getBoundingClientRect(); this._mouse.x = (newEvent.clientX - rect.left) / rect.width * 2 - 1; this._mouse.y = -((newEvent.clientY - rect.top) / rect.height) * 2 + 1; this._intersections.length = 0; this._raycaster.setFromCamera(this._mouse, this._camera); this._raycaster.intersectObjects(this._objects, true, this._intersections); if (this._intersections.length > 0) { this._selected = this.transformGroup === true ? this._objects[0] : this._intersections[0].object; this._plane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._plane.normal), this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)); if (this._raycaster.ray.intersectPlane(this._plane, this._intersection) && this._selected.parent) { this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(); this._offset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)); } this._domElement.style.cursor = "move"; this.dispatchEvent({ type: "dragstart", object: this._selected }); } }); __publicField$34(this, "onTouchEnd", (event) => { event.preventDefault(); if (this._selected) { this.dispatchEvent({ type: "dragend", object: this._selected }); this._selected = null; } this._domElement.style.cursor = "auto"; }); this._objects = _objects; this._camera = _camera; this._domElement = _domElement; this.activate(); } }; //#endregion //#region node_modules/three-stdlib/controls/PointerLockControls.js var __defProp$33 = Object.defineProperty; var __defNormalProp$33 = (obj, key, value) => key in obj ? __defProp$33(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$33 = (obj, key, value) => { __defNormalProp$33(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var _euler = /* @__PURE__ */ new Euler(0, 0, 0, "YXZ"); var _vector$2 = /* @__PURE__ */ new Vector3(); var _changeEvent$1 = { type: "change" }; var _lockEvent = { type: "lock" }; var _unlockEvent = { type: "unlock" }; var _MOUSE_SENSITIVITY = .002; var _PI_2 = Math.PI / 2; var PointerLockControls = class extends EventDispatcher { constructor(camera, domElement) { super(); __publicField$33(this, "camera"); __publicField$33(this, "domElement"); __publicField$33(this, "isLocked"); __publicField$33(this, "minPolarAngle"); __publicField$33(this, "maxPolarAngle"); __publicField$33(this, "pointerSpeed"); __publicField$33(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$1); }); __publicField$33(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; } }); __publicField$33(this, "onPointerlockError", () => { console.error("THREE.PointerLockControls: Unable to use Pointer Lock API"); }); __publicField$33(this, "connect", (domElement) => { this.domElement = domElement || 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); }); __publicField$33(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); }); __publicField$33(this, "dispose", () => { this.disconnect(); }); __publicField$33(this, "getObject", () => { return this.camera; }); __publicField$33(this, "direction", new Vector3(0, 0, -1)); __publicField$33(this, "getDirection", (v) => { return v.copy(this.direction).applyQuaternion(this.camera.quaternion); }); __publicField$33(this, "moveForward", (distance) => { _vector$2.setFromMatrixColumn(this.camera.matrix, 0); _vector$2.crossVectors(this.camera.up, _vector$2); this.camera.position.addScaledVector(_vector$2, distance); }); __publicField$33(this, "moveRight", (distance) => { _vector$2.setFromMatrixColumn(this.camera.matrix, 0); this.camera.position.addScaledVector(_vector$2, distance); }); __publicField$33(this, "lock", () => { if (this.domElement) this.domElement.requestPointerLock(); }); __publicField$33(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); } }; //#endregion //#region node_modules/three-stdlib/controls/DeviceOrientationControls.js var __defProp$32 = Object.defineProperty; var __defNormalProp$32 = (obj, key, value) => key in obj ? __defProp$32(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$32 = (obj, key, value) => { __defNormalProp$32(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var DeviceOrientationControls = class extends EventDispatcher { constructor(object) { super(); __publicField$32(this, "object"); __publicField$32(this, "changeEvent", { type: "change" }); __publicField$32(this, "EPS", 1e-6); __publicField$32(this, "enabled", true); __publicField$32(this, "deviceOrientation", { alpha: 0, beta: 0, gamma: 0 }); __publicField$32(this, "screenOrientation", 0); __publicField$32(this, "alphaOffset", 0); __publicField$32(this, "onDeviceOrientationChangeEvent", (event) => { this.deviceOrientation = event; }); __publicField$32(this, "onScreenOrientationChangeEvent", () => { this.screenOrientation = window.orientation || 0; }); __publicField$32(this, "zee", new Vector3(0, 0, 1)); __publicField$32(this, "euler", new Euler()); __publicField$32(this, "q0", new Quaternion()); __publicField$32(this, "q1", new Quaternion(-Math.sqrt(.5), 0, 0, Math.sqrt(.5))); __publicField$32(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)); }); __publicField$32(this, "connect", () => { this.onScreenOrientationChangeEvent(); if (window.DeviceOrientationEvent !== void 0 && 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; }); __publicField$32(this, "disconnect", () => { window.removeEventListener("orientationchange", this.onScreenOrientationChangeEvent); window.removeEventListener("deviceorientation", this.onDeviceOrientationChangeEvent); this.enabled = false; }); __publicField$32(this, "lastQuaternion", new Quaternion()); __publicField$32(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); } } }); __publicField$32(this, "dispose", () => this.disconnect()); this.object = object; this.object.rotation.reorder("YXZ"); this.connect(); } }; //#endregion //#region node_modules/three-stdlib/controls/TrackballControls.js var __defProp$31 = Object.defineProperty; var __defNormalProp$31 = (obj, key, value) => key in obj ? __defProp$31(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$31 = (obj, key, value) => { __defNormalProp$31(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var TrackballControls = class extends EventDispatcher { constructor(object, domElement) { super(); __publicField$31(this, "enabled", true); __publicField$31(this, "screen", { left: 0, top: 0, width: 0, height: 0 }); __publicField$31(this, "rotateSpeed", 1); __publicField$31(this, "zoomSpeed", 1.2); __publicField$31(this, "panSpeed", .3); __publicField$31(this, "noRotate", false); __publicField$31(this, "noZoom", false); __publicField$31(this, "noPan", false); __publicField$31(this, "staticMoving", false); __publicField$31(this, "dynamicDampingFactor", .2); __publicField$31(this, "minDistance", 0); __publicField$31(this, "maxDistance", Infinity); __publicField$31(this, "keys", [ "KeyA", "KeyS", "KeyD" ]); __publicField$31(this, "mouseButtons", { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }); __publicField$31(this, "object"); __publicField$31(this, "domElement"); __publicField$31(this, "cursorZoom", false); __publicField$31(this, "target", new Vector3()); __publicField$31(this, "mousePosition", new Vector2()); __publicField$31(this, "STATE", { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 }); __publicField$31(this, "EPS", 1e-6); __publicField$31(this, "lastZoom", 1); __publicField$31(this, "lastPosition", new Vector3()); __publicField$31(this, "cursorVector", new Vector3()); __publicField$31(this, "targetVector", new Vector3()); __publicField$31(this, "_state", this.STATE.NONE); __publicField$31(this, "_keyState", this.STATE.NONE); __publicField$31(this, "_eye", new Vector3()); __publicField$31(this, "_movePrev", new Vector2()); __publicField$31(this, "_moveCurr", new Vector2()); __publicField$31(this, "_lastAxis", new Vector3()); __publicField$31(this, "_lastAngle", 0); __publicField$31(this, "_zoomStart", new Vector2()); __publicField$31(this, "_zoomEnd", new Vector2()); __publicField$31(this, "_touchZoomDistanceStart", 0); __publicField$31(this, "_touchZoomDistanceEnd", 0); __publicField$31(this, "_panStart", new Vector2()); __publicField$31(this, "_panEnd", new Vector2()); __publicField$31(this, "target0"); __publicField$31(this, "position0"); __publicField$31(this, "up0"); __publicField$31(this, "zoom0"); __publicField$31(this, "changeEvent", { type: "change" }); __publicField$31(this, "startEvent", { type: "start" }); __publicField$31(this, "endEvent", { type: "end" }); __publicField$31(this, "onScreenVector", new Vector2()); __publicField$31(this, "getMouseOnScreen", (pageX, pageY) => { this.onScreenVector.set((pageX - this.screen.left) / this.screen.width, (pageY - this.screen.top) / this.screen.height); return this.onScreenVector; }); __publicField$31(this, "onCircleVector", new Vector2()); __publicField$31(this, "getMouseOnCircle", (pageX, pageY) => { this.onCircleVector.set((pageX - this.screen.width * .5 - this.screen.left) / (this.screen.width * .5), (this.screen.height + 2 * (this.screen.top - pageY)) / this.screen.width); return this.onCircleVector; }); __publicField$31(this, "axis", new Vector3()); __publicField$31(this, "quaternion", new Quaternion()); __publicField$31(this, "eyeDirection", new Vector3()); __publicField$31(this, "objectUpDirection", new Vector3()); __publicField$31(this, "objectSidewaysDirection", new Vector3()); __publicField$31(this, "moveDirection", new Vector3()); __publicField$31(this, "angle", 0); __publicField$31(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); }); __publicField$31(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 worldPos = this.cursorVector.set(this.mousePosition.x, this.mousePosition.y, this.targetVector.z).unproject(this.object); this.target.lerpVectors(worldPos, this.target, factor); } if (this.object.isOrthographicCamera) this.object.updateProjectionMatrix(); } }); __publicField$31(this, "mouseChange", new Vector2()); __publicField$31(this, "objectUp", new Vector3()); __publicField$31(this, "pan", new Vector3()); __publicField$31(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)); } }); __publicField$31(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); } } }); __publicField$31(this, "handleResize", () => { if (!this.domElement) return; const box = this.domElement.getBoundingClientRect(); const d = this.domElement.ownerDocument.documentElement; this.screen.left = box.left + window.pageXOffset - d.clientLeft; this.screen.top = box.top + window.pageYOffset - d.clientTop; this.screen.width = box.width; this.screen.height = box.height; }); __publicField$31(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"); }); __publicField$31(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; }); __publicField$31(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; }); __publicField$31(this, "onPointerDown", (event) => { if (this.enabled === false) return; switch (event.pointerType) { case "mouse": case "pen": this.onMouseDown(event); break; } }); __publicField$31(this, "onPointerMove", (event) => { if (this.enabled === false) return; switch (event.pointerType) { case "mouse": case "pen": this.onMouseMove(event); break; } }); __publicField$31(this, "onPointerUp", (event) => { if (this.enabled === false) return; switch (event.pointerType) { case "mouse": case "pen": this.onMouseUp(); break; } }); __publicField$31(this, "keyup", () => { if (this.enabled === false) return; this._keyState = this.STATE.NONE; window.addEventListener("keydown", this.keydown); }); __publicField$31(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); }); __publicField$31(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)); }); __publicField$31(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); }); __publicField$31(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 * .025; break; case 1: this._zoomStart.y -= event.deltaY * .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); }); __publicField$31(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); }); __publicField$31(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; } }); __publicField$31(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); }); __publicField$31(this, "contextmenu", (event) => { if (this.enabled === false) return; event.preventDefault(); }); __publicField$31(this, "connect", (domElement) => { if (domElement === document) console.error("THREE.OrbitControls: \"document\" should not be used as the target \"domElement\". Please use \"renderer.domElement\" instead."); this.domElement = domElement; 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(); }); __publicField$31(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(); } }; //#endregion //#region node_modules/three-stdlib/controls/OrbitControls.js var __defProp$30 = Object.defineProperty; var __defNormalProp$30 = (obj, key, value) => key in obj ? __defProp$30(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$30 = (obj, key, value) => { __defNormalProp$30(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var _ray$2 = /* @__PURE__ */ new Ray(); var _plane = /* @__PURE__ */ new Plane(); var TILT_LIMIT = Math.cos(70 * (Math.PI / 180)); var moduloWrapAround = (offset, capacity) => (offset % capacity + capacity) % capacity; var OrbitControls = class extends EventDispatcher { constructor(object, domElement) { super(); __publicField$30(this, "object"); __publicField$30(this, "domElement"); __publicField$30(this, "enabled", true); __publicField$30(this, "target", new Vector3()); __publicField$30(this, "minDistance", 0); __publicField$30(this, "maxDistance", Infinity); __publicField$30(this, "minZoom", 0); __publicField$30(this, "maxZoom", Infinity); __publicField$30(this, "minPolarAngle", 0); __publicField$30(this, "maxPolarAngle", Math.PI); __publicField$30(this, "minAzimuthAngle", -Infinity); __publicField$30(this, "maxAzimuthAngle", Infinity); __publicField$30(this, "enableDamping", false); __publicField$30(this, "dampingFactor", .05); __publicField$30(this, "enableZoom", true); __publicField$30(this, "zoomSpeed", 1); __publicField$30(this, "enableRotate", true); __publicField$30(this, "rotateSpeed", 1); __publicField$30(this, "enablePan", true); __publicField$30(this, "panSpeed", 1); __publicField$30(this, "screenSpacePanning", true); __publicField$30(this, "keyPanSpeed", 7); __publicField$30(this, "zoomToCursor", false); __publicField$30(this, "autoRotate", false); __publicField$30(this, "autoRotateSpeed", 2); __publicField$30(this, "reverseOrbit", false); __publicField$30(this, "reverseHorizontalOrbit", false); __publicField$30(this, "reverseVerticalOrbit", false); __publicField$30(this, "keys", { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" }); __publicField$30(this, "mouseButtons", { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }); __publicField$30(this, "touches", { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }); __publicField$30(this, "target0"); __publicField$30(this, "position0"); __publicField$30(this, "zoom0"); __publicField$30(this, "_domElementKeyEvents", null); __publicField$30(this, "getPolarAngle"); __publicField$30(this, "getAzimuthalAngle"); __publicField$30(this, "setPolarAngle"); __publicField$30(this, "setAzimuthalAngle"); __publicField$30(this, "getDistance"); __publicField$30(this, "getZoomScale"); __publicField$30(this, "listenToKeyEvents"); __publicField$30(this, "stopListenToKeyEvents"); __publicField$30(this, "saveState"); __publicField$30(this, "reset"); __publicField$30(this, "update"); __publicField$30(this, "connect"); __publicField$30(this, "dispose"); __publicField$30(this, "dollyIn"); __publicField$30(this, "dollyOut"); __publicField$30(this, "getScale"); __publicField$30(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 = () => spherical.phi; this.getAzimuthalAngle = () => spherical.theta; this.setPolarAngle = (value) => { let phi = moduloWrapAround(value, 2 * Math.PI); let currentPhi = spherical.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 = spherical.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 = STATE.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 update() { const position = scope.object.position; quat.setFromUnitVectors(object.up, up); quatInverse.copy(quat).invert(); offset.copy(position).sub(scope.target); offset.applyQuaternion(quat); spherical.setFromVector3(offset); if (scope.autoRotate && state === STATE.NONE) rotateLeft(getAutoRotationAngle()); if (scope.enableDamping) { spherical.theta += sphericalDelta.theta * scope.dampingFactor; spherical.phi += sphericalDelta.phi * scope.dampingFactor; } else { spherical.theta += sphericalDelta.theta; spherical.phi += sphericalDelta.phi; } let min = scope.minAzimuthAngle; let max = scope.maxAzimuthAngle; if (isFinite(min) && isFinite(max)) { if (min < -Math.PI) min += twoPI; else if (min > Math.PI) min -= twoPI; if (max < -Math.PI) max += twoPI; else if (max > Math.PI) max -= twoPI; if (min <= max) spherical.theta = Math.max(min, Math.min(max, spherical.theta)); else spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta); } spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi)); spherical.makeSafe(); if (scope.enableDamping === true) scope.target.addScaledVector(panOffset, scope.dampingFactor); else scope.target.add(panOffset); if (scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera) spherical.radius = clampDistance(spherical.radius); else spherical.radius = clampDistance(spherical.radius * scale); offset.setFromSpherical(spherical); offset.applyQuaternion(quatInverse); position.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 * scale); 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 / scale)); 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$2.origin.copy(scope.object.position); _ray$2.direction.set(0, 0, -1).transformDirection(scope.object.matrix); if (Math.abs(scope.object.up.dot(_ray$2.direction)) < TILT_LIMIT) object.lookAt(scope.target); else { _plane.setFromNormalAndCoplanarPoint(scope.object.up, scope.target); _ray$2.intersectPlane(_plane, scope.target); } } } else if (scope.object instanceof OrthographicCamera && scope.object.isOrthographicCamera) { zoomChanged = scale !== 1; if (zoomChanged) { scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale)); scope.object.updateProjectionMatrix(); } } scale = 1; performCursorZoom = false; if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) { 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 _a, _b, _c, _d, _e, _f; if (scope.domElement) scope.domElement.style.touchAction = "auto"; (_a = scope.domElement) == null || _a.removeEventListener("contextmenu", onContextMenu); (_b = scope.domElement) == null || _b.removeEventListener("pointerdown", onPointerDown); (_c = scope.domElement) == null || _c.removeEventListener("pointercancel", onPointerUp); (_d = scope.domElement) == null || _d.removeEventListener("wheel", onMouseWheel); (_e = scope.domElement) == null || _e.ownerDocument.removeEventListener("pointermove", onPointerMove); (_f = scope.domElement) == null || _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 STATE = { NONE: -1, ROTATE: 0, DOLLY: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_PAN: 4, TOUCH_DOLLY_PAN: 5, TOUCH_DOLLY_ROTATE: 6 }; let state = STATE.NONE; const EPS = 1e-6; const spherical = new Spherical(); const sphericalDelta = new Spherical(); let scale = 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(.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 v = new Vector3(); return function panLeft2(distance, objectMatrix) { v.setFromMatrixColumn(objectMatrix, 0); v.multiplyScalar(-distance); panOffset.add(v); }; })(); const panUp = (() => { const v = new Vector3(); return function panUp2(distance, objectMatrix) { if (scope.screenSpacePanning === true) v.setFromMatrixColumn(objectMatrix, 1); else { v.setFromMatrixColumn(objectMatrix, 0); v.crossVectors(scope.object.up, v); } v.multiplyScalar(distance); panOffset.add(v); }; })(); 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 position = scope.object.position; offset.copy(position).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) scale = newScale; else { console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."); scope.enableZoom = false; } } function dollyOut(dollyScale) { setScale(scale / dollyScale); } function dollyIn(dollyScale) { setScale(scale * 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 = .5 * (pointers[0].pageX + pointers[1].pageX); const y = .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 = .5 * (pointers[0].pageX + pointers[1].pageX); const y = .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 distance = Math.sqrt(dx * dx + dy * dy); dollyStart.set(0, distance); } 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 position = getSecondPointerPosition(event); const x = .5 * (event.pageX + position.x); const y = .5 * (event.pageY + position.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 position = getSecondPointerPosition(event); const x = .5 * (event.pageX + position.x); const y = .5 * (event.pageY + position.y); panEnd.set(x, y); } panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); pan(panDelta.x, panDelta.y); panStart.copy(panEnd); } function handleTouchMoveDolly(event) { const position = getSecondPointerPosition(event); const dx = event.pageX - position.x; const dy = event.pageY - position.y; const distance = Math.sqrt(dx * dx + dy * dy); dollyEnd.set(0, distance); 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 _a, _b; if (scope.enabled === false) return; if (pointers.length === 0) { (_a = scope.domElement) == null || _a.ownerDocument.addEventListener("pointermove", onPointerMove); (_b = scope.domElement) == null || _b.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 _a, _b, _c; removePointer(event); if (pointers.length === 0) { (_a = scope.domElement) == null || _a.releasePointerCapture(event.pointerId); (_b = scope.domElement) == null || _b.ownerDocument.removeEventListener("pointermove", onPointerMove); (_c = scope.domElement) == null || _c.ownerDocument.removeEventListener("pointerup", onPointerUp); } scope.dispatchEvent(endEvent); state = STATE.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 = STATE.DOLLY; break; case MOUSE.ROTATE: if (event.ctrlKey || event.metaKey || event.shiftKey) { if (scope.enablePan === false) return; handleMouseDownPan(event); state = STATE.PAN; } else { if (scope.enableRotate === false) return; handleMouseDownRotate(event); state = STATE.ROTATE; } break; case MOUSE.PAN: if (event.ctrlKey || event.metaKey || event.shiftKey) { if (scope.enableRotate === false) return; handleMouseDownRotate(event); state = STATE.ROTATE; } else { if (scope.enablePan === false) return; handleMouseDownPan(event); state = STATE.PAN; } break; default: state = STATE.NONE; } if (state !== STATE.NONE) scope.dispatchEvent(startEvent); } function onMouseMove(event) { if (scope.enabled === false) return; switch (state) { case STATE.ROTATE: if (scope.enableRotate === false) return; handleMouseMoveRotate(event); break; case STATE.DOLLY: if (scope.enableZoom === false) return; handleMouseMoveDolly(event); break; case STATE.PAN: if (scope.enablePan === false) return; handleMouseMovePan(event); break; } } function onMouseWheel(event) { if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.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 = STATE.TOUCH_ROTATE; break; case TOUCH.PAN: if (scope.enablePan === false) return; handleTouchStartPan(); state = STATE.TOUCH_PAN; break; default: state = STATE.NONE; } break; case 2: switch (scope.touches.TWO) { case TOUCH.DOLLY_PAN: if (scope.enableZoom === false && scope.enablePan === false) return; handleTouchStartDollyPan(); state = STATE.TOUCH_DOLLY_PAN; break; case TOUCH.DOLLY_ROTATE: if (scope.enableZoom === false && scope.enableRotate === false) return; handleTouchStartDollyRotate(); state = STATE.TOUCH_DOLLY_ROTATE; break; default: state = STATE.NONE; } break; default: state = STATE.NONE; } if (state !== STATE.NONE) scope.dispatchEvent(startEvent); } function onTouchMove(event) { trackPointer(event); switch (state) { case STATE.TOUCH_ROTATE: if (scope.enableRotate === false) return; handleTouchMoveRotate(event); scope.update(); break; case STATE.TOUCH_PAN: if (scope.enablePan === false) return; handleTouchMovePan(event); scope.update(); break; case STATE.TOUCH_DOLLY_PAN: if (scope.enableZoom === false && scope.enablePan === false) return; handleTouchMoveDollyPan(event); scope.update(); break; case STATE.TOUCH_DOLLY_ROTATE: if (scope.enableZoom === false && scope.enableRotate === false) return; handleTouchMoveDollyRotate(event); scope.update(); break; default: state = STATE.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 i = 0; i < pointers.length; i++) if (pointers[i].pointerId == event.pointerId) { pointers.splice(i, 1); return; } } function trackPointer(event) { let position = pointerPositions[event.pointerId]; if (position === void 0) { position = new Vector2(); pointerPositions[event.pointerId] = position; } position.set(event.pageX, event.pageY); } function getSecondPointerPosition(event) { return pointerPositions[(event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0]).pointerId]; } this.dollyIn = (dollyScale = getZoomScale()) => { dollyIn(dollyScale); scope.update(); }; this.dollyOut = (dollyScale = getZoomScale()) => { dollyOut(dollyScale); scope.update(); }; this.getScale = () => { return scale; }; 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; } }; //#endregion //#region node_modules/three-stdlib/controls/ArcballControls.js var __defProp$29 = Object.defineProperty; var __defNormalProp$29 = (obj, key, value) => key in obj ? __defProp$29(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$29 = (obj, key, value) => { __defNormalProp$29(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var STATE = { IDLE: Symbol(), ROTATE: Symbol(), PAN: Symbol(), SCALE: Symbol(), FOV: Symbol(), FOCUS: Symbol(), ZROTATE: Symbol(), TOUCH_MULTI: Symbol(), ANIMATION_FOCUS: Symbol(), ANIMATION_ROTATE: Symbol() }; var INPUT = { NONE: Symbol(), ONE_FINGER: Symbol(), ONE_FINGER_SWITCHED: Symbol(), TWO_FINGER: Symbol(), MULT_FINGER: Symbol(), CURSOR: Symbol() }; var _center$1 = { x: 0, y: 0 }; var _transformation = { camera: /* @__PURE__ */ new Matrix4(), gizmos: /* @__PURE__ */ new Matrix4() }; var _changeEvent = { type: "change" }; var _startEvent = { type: "start" }; var _endEvent = { type: "end" }; var ArcballControls = class extends EventDispatcher { constructor(camera, domElement = null, scene = null) { super(); __publicField$29(this, "camera"); __publicField$29(this, "domElement"); __publicField$29(this, "scene"); __publicField$29(this, "mouseActions"); __publicField$29(this, "_mouseOp"); __publicField$29(this, "_v2_1"); __publicField$29(this, "_v3_1"); __publicField$29(this, "_v3_2"); __publicField$29(this, "_m4_1"); __publicField$29(this, "_m4_2"); __publicField$29(this, "_quat"); __publicField$29(this, "_translationMatrix"); __publicField$29(this, "_rotationMatrix"); __publicField$29(this, "_scaleMatrix"); __publicField$29(this, "_rotationAxis"); __publicField$29(this, "_cameraMatrixState"); __publicField$29(this, "_cameraProjectionState"); __publicField$29(this, "_fovState"); __publicField$29(this, "_upState"); __publicField$29(this, "_zoomState"); __publicField$29(this, "_nearPos"); __publicField$29(this, "_farPos"); __publicField$29(this, "_gizmoMatrixState"); __publicField$29(this, "_up0"); __publicField$29(this, "_zoom0"); __publicField$29(this, "_fov0"); __publicField$29(this, "_initialNear"); __publicField$29(this, "_nearPos0"); __publicField$29(this, "_initialFar"); __publicField$29(this, "_farPos0"); __publicField$29(this, "_cameraMatrixState0"); __publicField$29(this, "_gizmoMatrixState0"); __publicField$29(this, "_button"); __publicField$29(this, "_touchStart"); __publicField$29(this, "_touchCurrent"); __publicField$29(this, "_input"); __publicField$29(this, "_switchSensibility"); __publicField$29(this, "_startFingerDistance"); __publicField$29(this, "_currentFingerDistance"); __publicField$29(this, "_startFingerRotation"); __publicField$29(this, "_currentFingerRotation"); __publicField$29(this, "_devPxRatio"); __publicField$29(this, "_downValid"); __publicField$29(this, "_nclicks"); __publicField$29(this, "_downEvents"); __publicField$29(this, "_clickStart"); __publicField$29(this, "_maxDownTime"); __publicField$29(this, "_maxInterval"); __publicField$29(this, "_posThreshold"); __publicField$29(this, "_movementThreshold"); __publicField$29(this, "_currentCursorPosition"); __publicField$29(this, "_startCursorPosition"); __publicField$29(this, "_grid"); __publicField$29(this, "_gridPosition"); __publicField$29(this, "_gizmos"); __publicField$29(this, "_curvePts"); __publicField$29(this, "_timeStart"); __publicField$29(this, "_animationId"); __publicField$29(this, "focusAnimationTime"); __publicField$29(this, "_timePrev"); __publicField$29(this, "_timeCurrent"); __publicField$29(this, "_anglePrev"); __publicField$29(this, "_angleCurrent"); __publicField$29(this, "_cursorPosPrev"); __publicField$29(this, "_cursorPosCurr"); __publicField$29(this, "_wPrev"); __publicField$29(this, "_wCurr"); __publicField$29(this, "adjustNearFar"); __publicField$29(this, "scaleFactor"); __publicField$29(this, "dampingFactor"); __publicField$29(this, "wMax"); __publicField$29(this, "enableAnimations"); __publicField$29(this, "enableGrid"); __publicField$29(this, "cursorZoom"); __publicField$29(this, "minFov"); __publicField$29(this, "maxFov"); __publicField$29(this, "enabled"); __publicField$29(this, "enablePan"); __publicField$29(this, "enableRotate"); __publicField$29(this, "enableZoom"); __publicField$29(this, "minDistance"); __publicField$29(this, "maxDistance"); __publicField$29(this, "minZoom"); __publicField$29(this, "maxZoom"); __publicField$29(this, "target"); __publicField$29(this, "_currentTarget"); __publicField$29(this, "_tbRadius"); __publicField$29(this, "_state"); __publicField$29(this, "onWindowResize", () => { const scale = (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 / scale; const points = new EllipseCurve(0, 0, newRadius, newRadius).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(_changeEvent); }); __publicField$29(this, "onContextMenu", (event) => { if (!this.enabled) return; for (let i = 0; i < this.mouseActions.length; i++) if (this.mouseActions[i].mouse == 2) { event.preventDefault(); break; } }); __publicField$29(this, "onPointerCancel", () => { this._touchStart.splice(0, this._touchStart.length); this._touchCurrent.splice(0, this._touchCurrent.length); this._input = INPUT.NONE; }); __publicField$29(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); } } }); __publicField$29(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: if (this.calculatePointersDistance(this._touchCurrent[0], event) * this._devPxRatio >= 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) { if (this.calculatePointersDistance(this._downEvents[this._downEvents.length - 1], event) * this._devPxRatio > this._movementThreshold) this._downValid = false; } }); __publicField$29(this, "onPointerUp", (event) => { if (event.pointerType == "touch" && this._input != INPUT.CURSOR) { const nTouch = this._touchCurrent.length; for (let i = 0; i < nTouch; i++) if (this._touchCurrent[i].pointerId == event.pointerId) { this._touchCurrent.splice(i, 1); this._touchStart.splice(i, 1); break; } switch (this._input) { case INPUT.ONE_FINGER: case INPUT.ONE_FINGER_SWITCHED: window.removeEventListener("pointermove", this.onPointerMove); window.removeEventListener("pointerup", this.onPointerUp); this._input = INPUT.NONE; this.onSinglePanEnd(); break; case INPUT.TWO_FINGER: this.onDoublePanEnd(); 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) if (event.timeStamp - this._downEvents[this._downEvents.length - 1].timeStamp <= 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); } }); __publicField$29(this, "onWheel", (event) => { var _a, _b; 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 size = 1; if (sgn > 0) size = 1 / this.scaleFactor; else if (sgn < 0) size = this.scaleFactor; switch (mouseOp) { case "ZOOM": this.updateTbState(STATE.SCALE, true); if (sgn > 0) size = 1 / Math.pow(this.scaleFactor, sgn); else if (sgn < 0) size = Math.pow(this.scaleFactor, -sgn); if (this.cursorZoom && this.enablePan) { let scalePoint; if (this.camera instanceof OrthographicCamera) scalePoint = (_a = this.unprojectOnTbPlane(this.camera, event.clientX, event.clientY, this.domElement)) == null ? void 0 : _a.applyQuaternion(this.camera.quaternion).multiplyScalar(1 / this.camera.zoom).add(this._gizmos.position); if (this.camera instanceof PerspectiveCamera) scalePoint = (_b = this.unprojectOnTbPlane(this.camera, event.clientX, event.clientY, this.domElement)) == null ? void 0 : _b.applyQuaternion(this.camera.quaternion).add(this._gizmos.position); if (scalePoint !== void 0) this.applyTransformMatrix(this.applyScale(size, scalePoint)); } else this.applyTransformMatrix(this.applyScale(size, this._gizmos.position)); if (this._grid) { this.disposeGrid(); this.drawGrid(); } this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_changeEvent); this.dispatchEvent(_endEvent); break; case "FOV": if (this.camera instanceof PerspectiveCamera) { this.updateTbState(STATE.FOV, true); if (event.deltaX != 0) { sgn = event.deltaX / notchDeltaY; size = 1; if (sgn > 0) size = 1 / Math.pow(this.scaleFactor, sgn); else if (sgn < 0) size = Math.pow(this.scaleFactor, -sgn); } this._v3_1.setFromMatrixPosition(this._cameraMatrixState); const x = this._v3_1.distanceTo(this._gizmos.position); let xNew = x / size; xNew = MathUtils.clamp(xNew, this.minDistance, this.maxDistance); const y = x * Math.tan(MathUtils.DEG2RAD * this.camera.fov * .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; size = x / (y / Math.tan(MathUtils.DEG2RAD * (newFov / 2))); this.setFov(newFov); this.applyTransformMatrix(this.applyScale(size, this._gizmos.position, false)); } if (this._grid) { this.disposeGrid(); this.drawGrid(); } this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_changeEvent); this.dispatchEvent(_endEvent); break; } } } }); __publicField$29(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(_changeEvent); } if (this.camera) { this.updateTbState(STATE.PAN, true); const rayDir = this.unprojectOnTbPlane(this.camera, _center$1.x, _center$1.y, this.domElement); if (rayDir !== void 0) this._startCursorPosition.copy(rayDir); if (this.enableGrid) { this.drawGrid(); this.dispatchEvent(_changeEvent); } } break; case "ROTATE": if (!this.enableRotate) return; if (this._animationId != -1) { cancelAnimationFrame(this._animationId); this._animationId = -1; this._timeStart = -1; } if (this.camera) { this.updateTbState(STATE.ROTATE, true); const rayDir = this.unprojectOnTbSurface(this.camera, _center$1.x, _center$1.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(_changeEvent); 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(_changeEvent); } this.updateTbState(STATE.FOV, true); this._startCursorPosition.setY(this.getCursorNDC(_center$1.x, _center$1.y, this.domElement).y * .5); this._currentCursorPosition.copy(this._startCursorPosition); } break; case "ZOOM": if (!this.enableZoom) return; if (this._animationId != -1) { cancelAnimationFrame(this._animationId); this._animationId = -1; this._timeStart = -1; this.activateGizmos(false); this.dispatchEvent(_changeEvent); } this.updateTbState(STATE.SCALE, true); this._startCursorPosition.setY(this.getCursorNDC(_center$1.x, _center$1.y, this.domElement).y * .5); this._currentCursorPosition.copy(this._startCursorPosition); break; } } }); __publicField$29(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$1.x, _center$1.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$1.x, _center$1.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$1.x, _center$1.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$1.x, _center$1.y, this.domElement, this._tbRadius); if (rayDir !== void 0) this._currentCursorPosition.copy(rayDir); const distance = this._startCursorPosition.distanceTo(this._currentCursorPosition); const angle = this._startCursorPosition.angleTo(this._currentCursorPosition); const amount = Math.max(distance / 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$1.x, _center$1.y, this.domElement).y * .5); this._currentCursorPosition.copy(this._startCursorPosition); if (this.enableGrid) this.disposeGrid(); this.activateGizmos(false); } else { const screenNotches = 8; this._currentCursorPosition.setY(this.getCursorNDC(_center$1.x, _center$1.y, this.domElement).y * .5); const movement = this._currentCursorPosition.y - this._startCursorPosition.y; let size = 1; if (movement < 0) size = 1 / Math.pow(this.scaleFactor, -movement * screenNotches); else if (movement > 0) size = Math.pow(this.scaleFactor, movement * screenNotches); this.applyTransformMatrix(this.applyScale(size, 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$1.x, _center$1.y, this.domElement).y * .5); this._currentCursorPosition.copy(this._startCursorPosition); if (this.enableGrid) this.disposeGrid(); this.activateGizmos(false); } else { const screenNotches = 8; this._currentCursorPosition.setY(this.getCursorNDC(_center$1.x, _center$1.y, this.domElement).y * .5); const movement = this._currentCursorPosition.y - this._startCursorPosition.y; let size = 1; if (movement < 0) size = 1 / Math.pow(this.scaleFactor, -movement * screenNotches); else if (movement > 0) size = Math.pow(this.scaleFactor, movement * screenNotches); this._v3_1.setFromMatrixPosition(this._cameraMatrixState); const x = this._v3_1.distanceTo(this._gizmos.position); let xNew = x / size; xNew = MathUtils.clamp(xNew, this.minDistance, this.maxDistance); const y = x * Math.tan(MathUtils.DEG2RAD * this._fovState * .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)); size = x / newDistance; this._v3_2.setFromMatrixPosition(this._gizmoMatrixState); this.setFov(newFov); this.applyTransformMatrix(this.applyScale(size, this._v3_2, false)); const direction = this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(newDistance / x); this._m4_1.makeTranslation(direction.x, direction.y, direction.z); } break; } this.dispatchEvent(_changeEvent); } }); __publicField$29(this, "onSinglePanEnd", () => { if (this._state == STATE.ROTATE) { if (!this.enableRotate) return; if (this.enableAnimations) if (performance.now() - this._timeCurrent < 120) { const w = Math.abs((this._wPrev + this._wCurr) / 2); const self = this; this._animationId = window.requestAnimationFrame(function(t) { self.updateTbState(STATE.ANIMATION_ROTATE, true); const rotationAxis = self.calculateRotationAxis(self._cursorPosPrev, self._cursorPosCurr); self.onRotationAnim(t, rotationAxis, Math.min(w, self.wMax)); }); } else { this.updateTbState(STATE.IDLE, false); this.activateGizmos(false); this.dispatchEvent(_changeEvent); } else { this.updateTbState(STATE.IDLE, false); this.activateGizmos(false); this.dispatchEvent(_changeEvent); } } else if (this._state == STATE.PAN || this._state == STATE.IDLE) { this.updateTbState(STATE.IDLE, false); if (this.enableGrid) this.disposeGrid(); this.activateGizmos(false); this.dispatchEvent(_changeEvent); } this.dispatchEvent(_endEvent); }); __publicField$29(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$1.x, _center$1.y, this.domElement), this.camera); if (hitP && this.enableAnimations) { const self = this; if (this._animationId != -1) window.cancelAnimationFrame(this._animationId); this._timeStart = -1; this._animationId = window.requestAnimationFrame(function(t) { self.updateTbState(STATE.ANIMATION_FOCUS, true); self.onFocusAnim(t, hitP, self._cameraMatrixState, self._gizmoMatrixState); }); } else if (hitP && !this.enableAnimations) { this.updateTbState(STATE.FOCUS, true); this.focus(hitP, this.scaleFactor); this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_changeEvent); } } this.dispatchEvent(_endEvent); }); __publicField$29(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$1.x, _center$1.y, this.domElement, true); if (rayDir !== void 0) this._startCursorPosition.copy(rayDir); this._currentCursorPosition.copy(this._startCursorPosition); this.activateGizmos(false); } }); __publicField$29(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$1.x, _center$1.y, this.domElement, true); if (rayDir !== void 0) this._currentCursorPosition.copy(rayDir); this.applyTransformMatrix(this.pan(this._startCursorPosition, this._currentCursorPosition, true)); this.dispatchEvent(_changeEvent); } }); __publicField$29(this, "onDoublePanEnd", () => { this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_endEvent); }); __publicField$29(this, "onRotateStart", () => { var _a; 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; (_a = this.camera) == null || _a.getWorldDirection(this._rotationAxis); if (!this.enablePan && !this.enableZoom) this.activateGizmos(true); } }); __publicField$29(this, "onRotateMove", () => { var _a; 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 = (_a = this.unprojectOnTbPlane(this.camera, _center$1.x, _center$1.y, this.domElement)) == null ? void 0 : _a.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(_changeEvent); } }); __publicField$29(this, "onRotateEnd", () => { this.updateTbState(STATE.IDLE, false); this.activateGizmos(false); this.dispatchEvent(_endEvent); }); __publicField$29(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); } }); __publicField$29(this, "onPinchMove", () => { var _a, _b; 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 = (_a = this.unprojectOnTbPlane(this.camera, _center$1.x, _center$1.y, this.domElement)) == null ? void 0 : _a.applyQuaternion(this.camera.quaternion).multiplyScalar(1 / this.camera.zoom).add(this._gizmos.position); else if (this.camera instanceof PerspectiveCamera) scalePoint = (_b = this.unprojectOnTbPlane(this.camera, _center$1.x, _center$1.y, this.domElement)) == null ? void 0 : _b.applyQuaternion(this.camera.quaternion).add(this._gizmos.position); if (scalePoint !== void 0) this.applyTransformMatrix(this.applyScale(amount, scalePoint)); this.dispatchEvent(_changeEvent); } }); __publicField$29(this, "onPinchEnd", () => { this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_endEvent); }); __publicField$29(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 i = 0; i < nFingers; i++) { clientX += this._touchCurrent[i].clientX; clientY += this._touchCurrent[i].clientY; } this.setCenter(clientX / nFingers, clientY / nFingers); this._startCursorPosition.setY(this.getCursorNDC(_center$1.x, _center$1.y, this.domElement).y * .5); this._currentCursorPosition.copy(this._startCursorPosition); } }); __publicField$29(this, "onTriplePanMove", () => { if (this.enabled && this.enableZoom && this.camera && this.domElement) { let clientX = 0; let clientY = 0; const nFingers = this._touchCurrent.length; for (let i = 0; i < nFingers; i++) { clientX += this._touchCurrent[i].clientX; clientY += this._touchCurrent[i].clientY; } this.setCenter(clientX / nFingers, clientY / nFingers); const screenNotches = 8; this._currentCursorPosition.setY(this.getCursorNDC(_center$1.x, _center$1.y, this.domElement).y * .5); const movement = this._currentCursorPosition.y - this._startCursorPosition.y; let size = 1; if (movement < 0) size = 1 / Math.pow(this.scaleFactor, -movement * screenNotches); else if (movement > 0) size = Math.pow(this.scaleFactor, movement * screenNotches); this._v3_1.setFromMatrixPosition(this._cameraMatrixState); const x = this._v3_1.distanceTo(this._gizmos.position); let xNew = x / size; xNew = MathUtils.clamp(xNew, this.minDistance, this.maxDistance); const y = x * Math.tan(MathUtils.DEG2RAD * this._fovState * .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)); size = x / newDistance; this._v3_2.setFromMatrixPosition(this._gizmoMatrixState); this.setFov(newFov); this.applyTransformMatrix(this.applyScale(size, this._v3_2, false)); const direction = this._gizmos.position.clone().sub(this.camera.position).normalize().multiplyScalar(newDistance / x); this._m4_1.makeTranslation(direction.x, direction.y, direction.z); this.dispatchEvent(_changeEvent); } }); __publicField$29(this, "onTriplePanEnd", () => { this.updateTbState(STATE.IDLE, false); this.dispatchEvent(_endEvent); }); /** * Set _center's x/y coordinates * @param {Number} clientX * @param {Number} clientY */ __publicField$29(this, "setCenter", (clientX, clientY) => { _center$1.x = clientX; _center$1.y = clientY; }); /** * Set default mouse actions */ __publicField$29(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"); }); /** * Set a new mouse action by specifying the operation to be performed and a mouse/key combination. In case of conflict, replaces the existing one * @param {String} operation The operation to be performed ('PAN', 'ROTATE', 'ZOOM', 'FOV) * @param {*} mouse A mouse button (0, 1, 2) or 'WHEEL' for wheel notches * @param {*} key The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed * @returns {Boolean} True if the mouse action has been successfully added, false otherwise */ __publicField$29(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 i = 0; i < this.mouseActions.length; i++) if (this.mouseActions[i].mouse == action.mouse && this.mouseActions[i].key == action.key) { this.mouseActions.splice(i, 1, action); return true; } this.mouseActions.push(action); return true; }); /** * Return the operation associated to a mouse/keyboard combination * @param {*} mouse A mouse button (0, 1, 2) or 'WHEEL' for wheel notches * @param {*} key The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed * @returns The operation if it has been found, null otherwise */ __publicField$29(this, "getOpFromAction", (mouse, key) => { let action; for (let i = 0; i < this.mouseActions.length; i++) { action = this.mouseActions[i]; if (action.mouse == mouse && action.key == key) return action.operation; } if (key) for (let i = 0; i < this.mouseActions.length; i++) { action = this.mouseActions[i]; if (action.mouse == mouse && action.key == null) return action.operation; } return null; }); /** * Get the operation associated to mouse and key combination and returns the corresponding FSA state * @param {Number} mouse Mouse button * @param {String} key Keyboard modifier * @returns The FSA state obtained from the operation associated to mouse/keyboard combination */ __publicField$29(this, "getOpStateFromAction", (mouse, key) => { let action; for (let i = 0; i < this.mouseActions.length; i++) { action = this.mouseActions[i]; if (action.mouse == mouse && action.key == key) return action.state; } if (key) for (let i = 0; i < this.mouseActions.length; i++) { action = this.mouseActions[i]; if (action.mouse == mouse && action.key == null) return action.state; } return null; }); /** * Calculate the angle between two pointers * @param {PointerEvent} p1 * @param {PointerEvent} p2 * @returns {Number} The angle between two pointers in degrees */ __publicField$29(this, "getAngle", (p1, p2) => { return Math.atan2(p2.clientY - p1.clientY, p2.clientX - p1.clientX) * 180 / Math.PI; }); /** * Update a PointerEvent inside current pointerevents array * @param {PointerEvent} event */ __publicField$29(this, "updateTouchEvent", (event) => { for (let i = 0; i < this._touchCurrent.length; i++) if (this._touchCurrent[i].pointerId == event.pointerId) { this._touchCurrent.splice(i, 1, event); break; } }); /** * Calculate the angular speed * @param {Number} p0 Position at t0 * @param {Number} p1 Position at t1 * @param {Number} t0 Initial time in milliseconds * @param {Number} t1 Ending time in milliseconds */ __publicField$29(this, "calculateAngularSpeed", (p0, p1, t0, t1) => { const s = p1 - p0; const t = (t1 - t0) / 1e3; if (t == 0) return 0; return s / t; }); /** * Calculate the distance between two pointers * @param {PointerEvent} p0 The first pointer * @param {PointerEvent} p1 The second pointer * @returns {number} The distance between the two pointers */ __publicField$29(this, "calculatePointersDistance", (p0, p1) => { return Math.sqrt(Math.pow(p1.clientX - p0.clientX, 2) + Math.pow(p1.clientY - p0.clientY, 2)); }); /** * Calculate the rotation axis as the vector perpendicular between two vectors * @param {Vector3} vec1 The first vector * @param {Vector3} vec2 The second vector * @returns {Vector3} The normalized rotation axis */ __publicField$29(this, "calculateRotationAxis", (vec1, vec2) => { this._rotationMatrix.extractRotation(this._cameraMatrixState); this._quat.setFromRotationMatrix(this._rotationMatrix); this._rotationAxis.crossVectors(vec1, vec2).applyQuaternion(this._quat); return this._rotationAxis.normalize().clone(); }); /** * Calculate the trackball radius so that gizmo's diamater will be 2/3 of the minimum side of the camera frustum * @param {Camera} camera * @returns {Number} The trackball radius */ __publicField$29(this, "calculateTbRadius", (camera) => { const factor = .67; const distance = camera.position.distanceTo(this._gizmos.position); if (camera instanceof PerspectiveCamera) { const halfFovV = MathUtils.DEG2RAD * camera.fov * .5; const halfFovH = Math.atan(camera.aspect * Math.tan(halfFovV)); return Math.tan(Math.min(halfFovV, halfFovH)) * distance * factor; } else if (camera instanceof OrthographicCamera) return Math.min(camera.top, camera.right) * factor; }); /** * Focus operation consist of positioning the point of interest in front of the camera and a slightly zoom in * @param {Vector3} point The point of interest * @param {Number} size Scale factor * @param {Number} amount Amount of operation to be completed (used for focus animations, default is complete full operation) */ __publicField$29(this, "focus", (point, size, 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(size, this._gizmos.position)); this._gizmoMatrixState.copy(gizmoStateTemp); this._cameraMatrixState.copy(cameraStateTemp); } }); /** * Draw a grid and add it to the scene */ __publicField$29(this, "drawGrid", () => { if (this.scene) { const color = 8947848; const multiplier = 3; let size, 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; size = maxLength / this.camera.zoom * multiplier; divisions = size / tick * this.camera.zoom; } else if (this.camera instanceof PerspectiveCamera) { const distance = this.camera.position.distanceTo(this._gizmos.position); const halfFovV = MathUtils.DEG2RAD * this.camera.fov * .5; const halfFovH = Math.atan(this.camera.aspect * Math.tan(halfFovV)); maxLength = Math.tan(Math.max(halfFovV, halfFovH)) * distance * 2; tick = maxLength / 20; size = maxLength * multiplier; divisions = size / tick; } if (this._grid == null && this.camera) { this._grid = new GridHelper(size, 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 * .5); this.scene.add(this._grid); } } }); __publicField$29(this, "connect", (domElement) => { if (domElement === document) console.error("THREE.ArcballControls: \"document\" should not be used as the target \"domElement\". Please use \"renderer.domElement\" instead."); this.domElement = domElement; 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); }); /** * Remove all listeners, stop animations and clean scene */ __publicField$29(this, "dispose", () => { var _a, _b, _c, _d, _e; if (this._animationId != -1) window.cancelAnimationFrame(this._animationId); (_a = this.domElement) == null || _a.removeEventListener("pointerdown", this.onPointerDown); (_b = this.domElement) == null || _b.removeEventListener("pointercancel", this.onPointerCancel); (_c = this.domElement) == null || _c.removeEventListener("wheel", this.onWheel); (_d = this.domElement) == null || _d.removeEventListener("contextmenu", this.onContextMenu); window.removeEventListener("pointermove", this.onPointerMove); window.removeEventListener("pointerup", this.onPointerUp); window.removeEventListener("resize", this.onWindowResize); (_e = this.scene) == null || _e.remove(this._gizmos); this.disposeGrid(); }); /** * remove the grid from the scene */ __publicField$29(this, "disposeGrid", () => { if (this._grid && this.scene) { this.scene.remove(this._grid); this._grid = null; } }); /** * Compute the easing out cubic function for ease out effect in animation * @param {Number} t The absolute progress of the animation in the bound of 0 (beginning of the) and 1 (ending of animation) * @returns {Number} Result of easing out cubic at time t */ __publicField$29(this, "easeOutCubic", (t) => { return 1 - Math.pow(1 - t, 3); }); /** * Make rotation gizmos more or less visible * @param {Boolean} isActive If true, make gizmos more visible */ __publicField$29(this, "activateGizmos", (isActive) => { for (const gizmo of this._gizmos.children) gizmo.material.setValues({ opacity: isActive ? 1 : .6 }); }); /** * Calculate the cursor position in NDC * @param {number} x Cursor horizontal coordinate within the canvas * @param {number} y Cursor vertical coordinate within the canvas * @param {HTMLElement} canvas The canvas where the renderer draws its output * @returns {Vector2} Cursor normalized position inside the canvas */ __publicField$29(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(); }); /** * Calculate the cursor position inside the canvas x/y coordinates with the origin being in the center of the canvas * @param {Number} x Cursor horizontal coordinate within the canvas * @param {Number} y Cursor vertical coordinate within the canvas * @param {HTMLElement} canvas The canvas where the renderer draws its output * @returns {Vector2} Cursor position inside the canvas */ __publicField$29(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) * .5; this._v2_1.y *= (this.camera.top - this.camera.bottom) * .5; } return this._v2_1.clone(); }); /** * Set the camera to be controlled * @param {Camera} camera The virtual camera to be controlled */ __publicField$29(this, "setCamera", (camera) => { if (camera) { camera.lookAt(this.target); camera.updateMatrix(); if (camera instanceof PerspectiveCamera) { this._fov0 = camera.fov; this._fovState = camera.fov; } this._cameraMatrixState0.copy(camera.matrix); this._cameraMatrixState.copy(this._cameraMatrixState0); this._cameraProjectionState.copy(camera.projectionMatrix); this._zoom0 = camera.zoom; this._zoomState = this._zoom0; this._initialNear = camera.near; this._nearPos0 = camera.position.distanceTo(this.target) - camera.near; this._nearPos = this._initialNear; this._initialFar = camera.far; this._farPos0 = camera.position.distanceTo(this.target) - camera.far; this._farPos = this._initialFar; this._up0.copy(camera.up); this._upState.copy(camera.up); this.camera = camera; this.camera.updateProjectionMatrix(); const tbRadius = this.calculateTbRadius(camera); if (tbRadius !== void 0) this._tbRadius = tbRadius; this.makeGizmos(this.target, this._tbRadius); } }); /** * Creates the rotation gizmos matching trackball center and radius * @param {Vector3} tbCenter The trackball center * @param {number} tbRadius The trackball radius */ __publicField$29(this, "makeGizmos", (tbCenter, tbRadius) => { const points = new EllipseCurve(0, 0, tbRadius, tbRadius).getPoints(this._curvePts); const curveGeometry = new BufferGeometry().setFromPoints(points); const curveMaterialX = new LineBasicMaterial({ color: 16744576, fog: false, transparent: true, opacity: .6 }); const curveMaterialY = new LineBasicMaterial({ color: 8454016, fog: false, transparent: true, opacity: .6 }); const curveMaterialZ = new LineBasicMaterial({ color: 8421631, fog: false, transparent: true, opacity: .6 }); const gizmoX = new Line(curveGeometry, curveMaterialX); const gizmoY = new Line(curveGeometry, curveMaterialY); const gizmoZ = new Line(curveGeometry, curveMaterialZ); const rotation = Math.PI * .5; gizmoX.rotation.x = rotation; gizmoY.rotation.y = rotation; this._gizmoMatrixState0.identity().setPosition(tbCenter); this._gizmoMatrixState.copy(this._gizmoMatrixState0); if (this.camera && this.camera.zoom != 1) { const size = 1 / this.camera.zoom; this._scaleMatrix.makeScale(size, size, size); 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); }); /** * Perform animation for focus operation * @param {Number} time Instant in which this function is called as performance.now() * @param {Vector3} point Point of interest for focus operation * @param {Matrix4} cameraMatrix Camera matrix * @param {Matrix4} gizmoMatrix Gizmos matrix */ __publicField$29(this, "onFocusAnim", (time, point, cameraMatrix, gizmoMatrix) => { if (this._timeStart == -1) this._timeStart = time; if (this._state == STATE.ANIMATION_FOCUS) { const animTime = (time - this._timeStart) / this.focusAnimationTime; this._gizmoMatrixState.copy(gizmoMatrix); if (animTime >= 1) { this._gizmoMatrixState.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale); this.focus(point, this.scaleFactor); this._timeStart = -1; this.updateTbState(STATE.IDLE, false); this.activateGizmos(false); this.dispatchEvent(_changeEvent); } else { const amount = this.easeOutCubic(animTime); const size = 1 - amount + this.scaleFactor * amount; this._gizmoMatrixState.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale); this.focus(point, size, amount); this.dispatchEvent(_changeEvent); const self = this; this._animationId = window.requestAnimationFrame(function(t) { self.onFocusAnim(t, point, cameraMatrix, gizmoMatrix.clone()); }); } } else { this._animationId = -1; this._timeStart = -1; } }); /** * Perform animation for rotation operation * @param {Number} time Instant in which this function is called as performance.now() * @param {Vector3} rotationAxis Rotation axis * @param {number} w0 Initial angular velocity */ __publicField$29(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; if (w0 + -this.dampingFactor * deltaTime > 0) { this._angleCurrent = .5 * -this.dampingFactor * Math.pow(deltaTime, 2) + w0 * deltaTime + 0; this.applyTransformMatrix(this.rotate(rotationAxis, this._angleCurrent)); this.dispatchEvent(_changeEvent); const self = this; this._animationId = window.requestAnimationFrame(function(t) { self.onRotationAnim(t, rotationAxis, w0); }); } else { this._animationId = -1; this._timeStart = -1; this.updateTbState(STATE.IDLE, false); this.activateGizmos(false); this.dispatchEvent(_changeEvent); } } else { this._animationId = -1; this._timeStart = -1; if (this._state != STATE.ROTATE) { this.activateGizmos(false); this.dispatchEvent(_changeEvent); } } }); /** * Perform pan operation moving camera between two points * @param {Vector3} p0 Initial point * @param {Vector3} p1 Ending point * @param {Boolean} adjust If movement should be adjusted considering camera distance (Perspective only) */ __publicField$29(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; }); /** * Reset trackball */ __publicField$29(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(_changeEvent); } }); /** * Rotate the camera around an axis passing by trackball's center * @param {Vector3} axis Rotation axis * @param {number} angle Angle in radians * @returns {Object} Object with 'camera' field containing transformation matrix resulting from the operation to be applied to the camera */ __publicField$29(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; }); __publicField$29(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); } }); __publicField$29(this, "pasteState", () => { const self = this; navigator.clipboard.readText().then(function resolved(value) { self.setStateFromJSON(value); }); }); /** * Save the current state of the control. This can later be recovered with .reset */ __publicField$29(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; }); /** * Perform uniform scale operation around a given point * @param {Number} size Scale factor * @param {Vector3} point Point around which scale * @param {Boolean} scaleGizmos If gizmos should be scaled (Perspective only) * @returns {Object} Object with 'camera' and 'gizmo' fields containing transformation matrices resulting from the operation to be applied to the camera and gizmos */ __publicField$29(this, "applyScale", (size, point, scaleGizmos = true) => { if (!this.camera) return; const scalePoint = point.clone(); let sizeInverse = 1 / size; if (this.camera instanceof OrthographicCamera) { this.camera.zoom = this._zoomState; this.camera.zoom *= size; 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 distance = this._v3_1.distanceTo(scalePoint); let amount = distance - distance * sizeInverse; const newDistance = distance - amount; if (newDistance < this.minDistance) { sizeInverse = this.minDistance / distance; amount = distance - distance * sizeInverse; } else if (newDistance > this.maxDistance) { sizeInverse = this.maxDistance / distance; amount = distance - distance * sizeInverse; } let direction = scalePoint.clone().sub(this._v3_1).normalize().multiplyScalar(amount); this._m4_1.makeTranslation(direction.x, direction.y, direction.z); if (scaleGizmos) { const pos = this._v3_2; distance = pos.distanceTo(scalePoint); amount = distance - distance * sizeInverse; direction = 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(direction.x, direction.y, direction.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; } }); /** * Set camera fov * @param {Number} value fov to be setted */ __publicField$29(this, "setFov", (value) => { if (this.camera instanceof PerspectiveCamera) { this.camera.fov = MathUtils.clamp(value, this.minFov, this.maxFov); this.camera.updateProjectionMatrix(); } }); /** * Set the trackball's center point * @param {Number} x X coordinate * @param {Number} y Y coordinate * @param {Number} z Z coordinate */ __publicField$29(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); } }); /** * Rotate camera around its direction axis passing by a given point by a given angle * @param {Vector3} point The point where the rotation axis is passing trough * @param {Number} angle Angle in radians * @returns The computed transormation matix */ __publicField$29(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; }); /** * Unproject the cursor on the 3D object surface * @param {Vector2} cursor Cursor coordinates in NDC * @param {Camera} camera Virtual camera * @returns {Vector3} The point of intersection with the model, if exist, null otherwise */ __publicField$29(this, "unprojectOnObj", (cursor, camera) => { if (!this.scene) return null; const raycaster = new Raycaster(); raycaster.near = camera.near; raycaster.far = camera.far; raycaster.setFromCamera(cursor, camera); const intersect = raycaster.intersectObjects(this.scene.children, true); for (let i = 0; i < intersect.length; i++) if (intersect[i].object.uuid != this._gizmos.uuid && intersect[i].face) return intersect[i].point.clone(); return null; }); /** * Unproject the cursor on the trackball surface * @param {Camera} camera The virtual camera * @param {Number} cursorX Cursor horizontal coordinate on screen * @param {Number} cursorY Cursor vertical coordinate on screen * @param {HTMLElement} canvas The canvas where the renderer draws its output * @param {number} tbRadius The trackball radius * @returns {Vector3} The unprojected point on the trackball surface */ __publicField$29(this, "unprojectOnTbSurface", (camera, cursorX, cursorY, canvas, tbRadius) => { if (camera 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 * .5) this._v3_1.setZ(Math.sqrt(r2 - (x2 + y2))); else this._v3_1.setZ(r2 * .5 / Math.sqrt(x2 + y2)); return this._v3_1; } if (camera 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(camera.projectionMatrixInverse); const rayDir = this._v3_1.clone().normalize(); const cameraGizmoDistance = camera.position.distanceTo(this._gizmos.position); const radius2 = Math.pow(tbRadius, 2); const h = this._v3_1.z; const l = Math.sqrt(Math.pow(this._v3_1.x, 2) + Math.pow(this._v3_1.y, 2)); if (l == 0) { rayDir.set(this._v3_1.x, this._v3_1.y, tbRadius); return rayDir; } const m = h / l; const q = cameraGizmoDistance; let a = Math.pow(m, 2) + 1; let b = 2 * m * q; let c = Math.pow(q, 2) - radius2; let delta = Math.pow(b, 2) - 4 * a * c; if (delta >= 0) { this._v2_1.setX((-b - Math.sqrt(delta)) / (2 * a)); this._v2_1.setY(m * this._v2_1.x + q); if (MathUtils.RAD2DEG * this._v2_1.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; } } a = m; b = q; c = -radius2 * .5; delta = Math.pow(b, 2) - 4 * a * c; this._v2_1.setX((-b - Math.sqrt(delta)) / (2 * a)); 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; } }); /** * Unproject the cursor on the plane passing through the center of the trackball orthogonal to the camera * @param {Camera} camera The virtual camera * @param {Number} cursorX Cursor horizontal coordinate on screen * @param {Number} cursorY Cursor vertical coordinate on screen * @param {HTMLElement} canvas The canvas where the renderer draws its output * @param {Boolean} initialDistance If initial distance between camera and gizmos should be used for calculations instead of current (Perspective only) * @returns {Vector3} The unprojected point on the trackball plane */ __publicField$29(this, "unprojectOnTbPlane", (camera, cursorX, cursorY, canvas, initialDistance = false) => { if (camera 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 (camera 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(camera.projectionMatrixInverse); const rayDir = this._v3_1.clone().normalize(); const h = this._v3_1.z; const l = Math.sqrt(Math.pow(this._v3_1.x, 2) + Math.pow(this._v3_1.y, 2)); let cameraGizmoDistance; if (initialDistance) cameraGizmoDistance = this._v3_1.setFromMatrixPosition(this._cameraMatrixState0).distanceTo(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0)); else cameraGizmoDistance = camera.position.distanceTo(this._gizmos.position); if (l == 0) { rayDir.set(0, 0, 0); return rayDir; } const m = h / l; 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; } }); /** * Update camera and gizmos state */ __publicField$29(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; }); /** * Update the trackball FSA * @param {STATE} newState New state of the FSA * @param {Boolean} updateMatrices If matriices state should be updated */ __publicField$29(this, "updateTbState", (newState, updateMatrices) => { this._state = newState; if (updateMatrices) this.updateMatrixState(); }); __publicField$29(this, "update", () => { const EPS = 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 distance = this.camera.position.distanceTo(this._gizmos.position); if (distance > this.maxDistance + EPS || distance < this.minDistance - EPS) { const newDistance = MathUtils.clamp(distance, this.minDistance, this.maxDistance); this.applyTransformMatrix(this.applyScale(newDistance / distance, 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 - EPS || oldRadius > this._tbRadius + EPS) { const scale = (this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z) / 3; const newRadius = this._tbRadius / scale; const points = new EllipseCurve(0, 0, newRadius, newRadius).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); }); __publicField$29(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(_changeEvent); } }); 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 bb = new Box3(); bb.setFromObject(this._gizmos); const sphere = new Sphere(); bb.getBoundingSphere(sphere); const adjustedNearPosition = Math.max(this._nearPos0, sphere.radius + sphere.center.length()); const regularNearPosition = cameraDistance - this._initialNear; const minNearPos = Math.min(adjustedNearPosition, regularNearPosition); this.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 update = false; if (this.camera.near != this._initialNear) { this.camera.near = this._initialNear; update = true; } if (this.camera.far != this._initialFar) { this.camera.far = this._initialFar; update = true; } if (update) this.camera.updateProjectionMatrix(); } } } /** * Set gizmos visibility * @param {Boolean} value Value of gizmos visibility */ setGizmosVisible(value) { this._gizmos.visible = value; this.dispatchEvent(_changeEvent); } /** * 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; } }; //#endregion //#region node_modules/three-stdlib/controls/FlyControls.js var __defProp$28 = Object.defineProperty; var __defNormalProp$28 = (obj, key, value) => key in obj ? __defProp$28(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$28 = (obj, key, value) => { __defNormalProp$28(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; function contextmenu(event) { event.preventDefault(); } var FlyControls = class extends EventDispatcher { constructor(object, domElement) { super(); __publicField$28(this, "object"); __publicField$28(this, "domElement", null); __publicField$28(this, "movementSpeed", 1); __publicField$28(this, "rollSpeed", .005); __publicField$28(this, "dragToLook", false); __publicField$28(this, "autoForward", false); __publicField$28(this, "changeEvent", { type: "change" }); __publicField$28(this, "EPS", 1e-6); __publicField$28(this, "tmpQuaternion", new Quaternion()); __publicField$28(this, "mouseStatus", 0); __publicField$28(this, "movementSpeedMultiplier", 1); __publicField$28(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 }); __publicField$28(this, "moveVector", new Vector3(0, 0, 0)); __publicField$28(this, "rotationVector", new Vector3(0, 0, 0)); __publicField$28(this, "keydown", (event) => { if (event.altKey) return; switch (event.code) { case "ShiftLeft": case "ShiftRight": this.movementSpeedMultiplier = .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(); }); __publicField$28(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(); }); __publicField$28(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(); } }); __publicField$28(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(); } }); __publicField$28(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(); }); __publicField$28(this, "lastQuaternion", new Quaternion()); __publicField$28(this, "lastPosition", new Vector3()); __publicField$28(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); } }); __publicField$28(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; }); __publicField$28(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; }); __publicField$28(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] }; }); __publicField$28(this, "connect", (domElement) => { this.domElement = domElement; if (!(domElement instanceof Document)) domElement.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); }); __publicField$28(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(); } }; //#endregion //#region node_modules/three-stdlib/postprocessing/Pass.js var __defProp$27 = Object.defineProperty; var __defNormalProp$27 = (obj, key, value) => key in obj ? __defProp$27(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$27 = (obj, key, value) => { __defNormalProp$27(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var Pass = class { constructor() { __publicField$27(this, "enabled", true); __publicField$27(this, "needsSwap", true); __publicField$27(this, "clear", false); __publicField$27(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) { __publicField$27(this, "camera", new OrthographicCamera(-1, 1, 1, -1, 0, 1)); __publicField$27(this, "geometry", new PlaneGeometry(2, 2)); __publicField$27(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); } }; //#endregion //#region node_modules/three-stdlib/postprocessing/ShaderPass.js var __defProp$26 = Object.defineProperty; var __defNormalProp$26 = (obj, key, value) => key in obj ? __defProp$26(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$26 = (obj, key, value) => { __defNormalProp$26(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var ShaderPass = class extends Pass { constructor(shader, textureID = "tDiffuse") { super(); __publicField$26(this, "textureID"); __publicField$26(this, "uniforms"); __publicField$26(this, "material"); __publicField$26(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(); } }; //#endregion //#region node_modules/three-stdlib/postprocessing/LUTPass.js var LUTShader = { defines: { USE_3DTEXTURE: 1 }, uniforms: { lut3d: { value: null }, lut: { value: null }, lutSize: { value: 0 }, tDiffuse: { value: null }, intensity: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform float lutSize; #if USE_3DTEXTURE precision highp sampler3D; uniform sampler3D lut3d; #else uniform sampler2D lut; vec3 lutLookup( sampler2D tex, float size, vec3 rgb ) { float sliceHeight = 1.0 / size; float yPixelHeight = 1.0 / ( size * size ); // Get the slices on either side of the sample float slice = rgb.b * size; float interp = fract( slice ); float slice0 = slice - interp; float centeredInterp = interp - 0.5; float slice1 = slice0 + sign( centeredInterp ); // Pull y sample in by half a pixel in each direction to avoid color // bleeding from adjacent slices. float greenOffset = clamp( rgb.g * sliceHeight, yPixelHeight * 0.5, sliceHeight - yPixelHeight * 0.5 ); vec2 uv0 = vec2( rgb.r, slice0 * sliceHeight + greenOffset ); vec2 uv1 = vec2( rgb.r, slice1 * sliceHeight + greenOffset ); vec3 sample0 = texture2D( tex, uv0 ).rgb; vec3 sample1 = texture2D( tex, uv1 ).rgb; return mix( sample0, sample1, abs( centeredInterp ) ); } #endif varying vec2 vUv; uniform float intensity; uniform sampler2D tDiffuse; void main() { vec4 val = texture2D( tDiffuse, vUv ); vec4 lutVal; // pull the sample in by half a pixel so the sample begins // at the center of the edge pixels. float pixelWidth = 1.0 / lutSize; float halfPixelWidth = 0.5 / lutSize; vec3 uvw = vec3( halfPixelWidth ) + val.rgb * ( 1.0 - pixelWidth ); #if USE_3DTEXTURE lutVal = vec4( texture( lut3d, uvw ).rgb, val.a ); #else lutVal = vec4( lutLookup( lut, lutSize, uvw ), val.a ); #endif gl_FragColor = vec4( mix( val, lutVal, intensity ) ); } ` }; var LUTPass = class extends ShaderPass { set lut(v) { const material = this.material; if (v !== this.lut) { material.uniforms.lut3d.value = null; material.uniforms.lut.value = null; if (v) { const is3dTextureDefine = v.isData3DTexture ? 1 : 0; if (is3dTextureDefine !== material.defines.USE_3DTEXTURE) { material.defines.USE_3DTEXTURE = is3dTextureDefine; material.needsUpdate = true; } material.uniforms.lutSize.value = v.image.width; if (v.isData3DTexture) material.uniforms.lut3d.value = v; else material.uniforms.lut.value = v; } } } get lut() { return this.material.uniforms.lut.value || this.material.uniforms.lut3d.value; } set intensity(v) { this.material.uniforms.intensity.value = v; } get intensity() { return this.material.uniforms.intensity.value; } constructor(options = {}) { super(LUTShader); this.lut = options.lut || null; this.intensity = "intensity" in options ? options.intensity : 1; } }; //#endregion //#region node_modules/three-stdlib/postprocessing/ClearPass.js var __defProp$25 = Object.defineProperty; var __defNormalProp$25 = (obj, key, value) => key in obj ? __defProp$25(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$25 = (obj, key, value) => { __defNormalProp$25(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var ClearPass = class extends Pass { constructor(clearColor, clearAlpha) { super(); __publicField$25(this, "clearColor"); __publicField$25(this, "clearAlpha"); __publicField$25(this, "_oldClearColor"); this.needsSwap = false; this.clearColor = clearColor !== void 0 ? clearColor : 0; this.clearAlpha = clearAlpha !== void 0 ? clearAlpha : 0; this._oldClearColor = new Color(); } render(renderer, writeBuffer, readBuffer) { let oldClearAlpha; if (this.clearColor) { renderer.getClearColor(this._oldClearColor); oldClearAlpha = renderer.getClearAlpha(); renderer.setClearColor(this.clearColor, this.clearAlpha); } renderer.setRenderTarget(this.renderToScreen ? null : readBuffer); renderer.clear(); if (this.clearColor) renderer.setClearColor(this._oldClearColor, oldClearAlpha); } }; //#endregion //#region node_modules/three-stdlib/shaders/DigitalGlitch.js var DigitalGlitch = { uniforms: { tDiffuse: { value: null }, tDisp: { value: null }, byp: { value: 0 }, amount: { value: .08 }, angle: { value: .02 }, seed: { value: .02 }, seed_x: { value: .02 }, seed_y: { value: .02 }, distortion_x: { value: .5 }, distortion_y: { value: .6 }, col_s: { value: .05 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform int byp; //should we apply the glitch ? uniform sampler2D tDiffuse; uniform sampler2D tDisp; uniform float amount; uniform float angle; uniform float seed; uniform float seed_x; uniform float seed_y; uniform float distortion_x; uniform float distortion_y; uniform float col_s; varying vec2 vUv; float rand(vec2 co){ return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453); } void main() { if(byp<1) { vec2 p = vUv; float xs = floor(gl_FragCoord.x / 0.5); float ys = floor(gl_FragCoord.y / 0.5); //based on staffantans glitch shader for unity https://github.com/staffantan/unityglitch vec4 normal = texture2D (tDisp, p*seed*seed); if(p.ydistortion_x-col_s*seed) { if(seed_x>0.){ p.y = 1. - (p.y + distortion_y); } else { p.y = distortion_y; } } if(p.xdistortion_y-col_s*seed) { if(seed_y>0.){ p.x=distortion_x; } else { p.x = 1. - (p.x + distortion_x); } } p.x+=normal.x*seed_x*(seed/5.); p.y+=normal.y*seed_y*(seed/5.); //base from RGB shift shader vec2 offset = amount * vec2( cos(angle), sin(angle)); vec4 cr = texture2D(tDiffuse, p + offset); vec4 cga = texture2D(tDiffuse, p); vec4 cb = texture2D(tDiffuse, p - offset); gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a); //add noise vec4 snow = 200.*amount*vec4(rand(vec2(xs * seed,ys * seed*50.))*0.2); gl_FragColor = gl_FragColor+ snow; } else { gl_FragColor=texture2D (tDiffuse, vUv); } } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/GlitchPass.js var __defProp$24 = Object.defineProperty; var __defNormalProp$24 = (obj, key, value) => key in obj ? __defProp$24(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$24 = (obj, key, value) => { __defNormalProp$24(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var GlitchPass = class extends Pass { constructor(dt_size = 64) { super(); __publicField$24(this, "material"); __publicField$24(this, "fsQuad"); __publicField$24(this, "goWild"); __publicField$24(this, "curF"); __publicField$24(this, "randX"); __publicField$24(this, "uniforms"); this.uniforms = UniformsUtils.clone(DigitalGlitch.uniforms); this.uniforms["tDisp"].value = this.generateHeightmap(dt_size); this.material = new ShaderMaterial({ uniforms: this.uniforms, vertexShader: DigitalGlitch.vertexShader, fragmentShader: DigitalGlitch.fragmentShader }); this.fsQuad = new FullScreenQuad(this.material); this.goWild = false; this.curF = 0; this.generateTrigger(); } render(renderer, writeBuffer, readBuffer) { this.uniforms["tDiffuse"].value = readBuffer.texture; this.uniforms["seed"].value = Math.random(); this.uniforms["byp"].value = 0; if (this.curF % this.randX == 0 || this.goWild == true) { this.uniforms["amount"].value = Math.random() / 30; this.uniforms["angle"].value = MathUtils.randFloat(-Math.PI, Math.PI); this.uniforms["seed_x"].value = MathUtils.randFloat(-1, 1); this.uniforms["seed_y"].value = MathUtils.randFloat(-1, 1); this.uniforms["distortion_x"].value = MathUtils.randFloat(0, 1); this.uniforms["distortion_y"].value = MathUtils.randFloat(0, 1); this.curF = 0; this.generateTrigger(); } else if (this.curF % this.randX < this.randX / 5) { this.uniforms["amount"].value = Math.random() / 90; this.uniforms["angle"].value = MathUtils.randFloat(-Math.PI, Math.PI); this.uniforms["distortion_x"].value = MathUtils.randFloat(0, 1); this.uniforms["distortion_y"].value = MathUtils.randFloat(0, 1); this.uniforms["seed_x"].value = MathUtils.randFloat(-.3, .3); this.uniforms["seed_y"].value = MathUtils.randFloat(-.3, .3); } else if (this.goWild == false) this.uniforms["byp"].value = 1; this.curF++; if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); } } generateTrigger() { this.randX = MathUtils.randInt(120, 240); } generateHeightmap(dt_size) { const data_arr = new Float32Array(dt_size * dt_size); const length = dt_size * dt_size; for (let i = 0; i < length; i++) data_arr[i] = MathUtils.randFloat(0, 1); const texture = new DataTexture(data_arr, dt_size, dt_size, RedFormat, FloatType); texture.needsUpdate = true; return texture; } }; //#endregion //#region 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: ` varying vec2 vUV; void main() { vUV = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `, fragmentShader: ` #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 ); } } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/HalftonePass.js var __defProp$23 = Object.defineProperty; var __defNormalProp$23 = (obj, key, value) => key in obj ? __defProp$23(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$23 = (obj, key, value) => { __defNormalProp$23(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var HalftonePass = class extends Pass { constructor(width, height, params) { super(); __publicField$23(this, "material"); __publicField$23(this, "fsQuad"); __publicField$23(this, "uniforms"); if (HalftoneShader === void 0) console.error("THREE.HalftonePass requires HalftoneShader"); this.uniforms = UniformsUtils.clone(HalftoneShader.uniforms); this.material = new ShaderMaterial({ uniforms: this.uniforms, fragmentShader: HalftoneShader.fragmentShader, vertexShader: HalftoneShader.vertexShader }); this.uniforms.width.value = width; this.uniforms.height.value = height; for (const key in params) if (params.hasOwnProperty(key) && this.uniforms.hasOwnProperty(key)) this.uniforms[key].value = params[key]; this.fsQuad = new FullScreenQuad(this.material); } render(renderer, writeBuffer, readBuffer) { this.material.uniforms["tDiffuse"].value = readBuffer.texture; if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); } } setSize(width, height) { this.uniforms.width.value = width; this.uniforms.height.value = height; } }; //#endregion //#region node_modules/three-stdlib/shaders/SMAAShader.js var SMAAEdgesShader = { defines: { SMAA_THRESHOLD: "0.1" }, uniforms: { tDiffuse: { value: null }, resolution: { value: /* @__PURE__ */ new Vector2(1 / 1024, 1 / 512) } }, vertexShader: ` 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: ` 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: /* @__PURE__ */ new Vector2(1 / 1024, 1 / 512) } }, vertexShader: ` 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: ` #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: /* @__PURE__ */ new Vector2(1 / 1024, 1 / 512) } }, vertexShader: ` 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: ` 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 ); } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/SMAAPass.js var SMAAPass = class extends Pass { constructor(width, height) { super(); this.edgesRT = new WebGLRenderTarget(width, height, { depthBuffer: false }); this.edgesRT.texture.name = "SMAAPass.edges"; this.weightsRT = new WebGLRenderTarget(width, height, { depthBuffer: false }); this.weightsRT.texture.name = "SMAAPass.weights"; const scope = this; const areaTextureImage = new Image(); areaTextureImage.src = this.getAreaTexture(); areaTextureImage.onload = function() { scope.areaTexture.needsUpdate = true; }; this.areaTexture = new Texture(); this.areaTexture.name = "SMAAPass.area"; this.areaTexture.image = areaTextureImage; this.areaTexture.minFilter = LinearFilter; this.areaTexture.generateMipmaps = false; this.areaTexture.flipY = false; const searchTextureImage = new Image(); searchTextureImage.src = this.getSearchTexture(); searchTextureImage.onload = function() { scope.searchTexture.needsUpdate = true; }; this.searchTexture = new Texture(); this.searchTexture.name = "SMAAPass.search"; this.searchTexture.image = searchTextureImage; this.searchTexture.magFilter = NearestFilter; this.searchTexture.minFilter = NearestFilter; this.searchTexture.generateMipmaps = false; this.searchTexture.flipY = false; if (SMAAEdgesShader === void 0) console.error("THREE.SMAAPass relies on SMAAShader"); this.uniformsEdges = UniformsUtils.clone(SMAAEdgesShader.uniforms); this.uniformsEdges["resolution"].value.set(1 / width, 1 / height); this.materialEdges = new ShaderMaterial({ defines: Object.assign({}, SMAAEdgesShader.defines), uniforms: this.uniformsEdges, vertexShader: SMAAEdgesShader.vertexShader, fragmentShader: SMAAEdgesShader.fragmentShader }); this.uniformsWeights = UniformsUtils.clone(SMAAWeightsShader.uniforms); this.uniformsWeights["resolution"].value.set(1 / width, 1 / height); this.uniformsWeights["tDiffuse"].value = this.edgesRT.texture; this.uniformsWeights["tArea"].value = this.areaTexture; this.uniformsWeights["tSearch"].value = this.searchTexture; this.materialWeights = new ShaderMaterial({ defines: Object.assign({}, SMAAWeightsShader.defines), uniforms: this.uniformsWeights, vertexShader: SMAAWeightsShader.vertexShader, fragmentShader: SMAAWeightsShader.fragmentShader }); this.uniformsBlend = UniformsUtils.clone(SMAABlendShader.uniforms); this.uniformsBlend["resolution"].value.set(1 / width, 1 / height); this.uniformsBlend["tDiffuse"].value = this.weightsRT.texture; this.materialBlend = new ShaderMaterial({ uniforms: this.uniformsBlend, vertexShader: SMAABlendShader.vertexShader, fragmentShader: SMAABlendShader.fragmentShader }); this.needsSwap = false; this.fsQuad = new FullScreenQuad(null); } render(renderer, writeBuffer, readBuffer) { this.uniformsEdges["tDiffuse"].value = readBuffer.texture; this.fsQuad.material = this.materialEdges; renderer.setRenderTarget(this.edgesRT); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); this.fsQuad.material = this.materialWeights; renderer.setRenderTarget(this.weightsRT); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); this.uniformsBlend["tColor"].value = readBuffer.texture; this.fsQuad.material = this.materialBlend; if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); } } setSize(width, height) { this.edgesRT.setSize(width, height); this.weightsRT.setSize(width, height); this.materialEdges.uniforms["resolution"].value.set(1 / width, 1 / height); this.materialWeights.uniforms["resolution"].value.set(1 / width, 1 / height); this.materialBlend.uniforms["resolution"].value.set(1 / width, 1 / height); } getAreaTexture() { return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAIwCAIAAACOVPcQAACBeklEQVR42u39W4xlWXrnh/3WWvuciIzMrKxrV8/0rWbY0+SQFKcb4owIkSIFCjY9AC1BT/LYBozRi+EX+cV+8IMsYAaCwRcBwjzMiw2jAWtgwC8WR5Q8mDFHZLNHTarZGrLJJllt1W2qKrsumZWZcTvn7L3W54e1vrXX3vuciLPPORFR1XE2EomorB0nVuz//r71re/y/1eMvb4Cb3N11xV/PP/2v4UBAwJG/7H8urx6/25/Gf8O5hypMQ0EEEQwAqLfoN/Z+97f/SW+/NvcgQk4sGBJK6H7N4PFVL+K+e0N11yNfkKvwUdwdlUAXPHHL38oa15f/i/46Ih6SuMSPmLAYAwyRKn7dfMGH97jaMFBYCJUgotIC2YAdu+LyW9vvubxAP8kAL8H/koAuOKP3+q6+xGnd5kdYCeECnGIJViwGJMAkQKfDvB3WZxjLKGh8VSCCzhwEWBpMc5/kBbjawT4HnwJfhr+pPBIu7uu+OOTo9vsmtQcniMBGkKFd4jDWMSCRUpLjJYNJkM+IRzQ+PQvIeAMTrBS2LEiaiR9b/5PuT6Ap/AcfAFO4Y3dA3DFH7/VS+M8k4baEAQfMI4QfbVDDGIRg7GKaIY52qAjTAgTvGBAPGIIghOCYAUrGFNgzA7Q3QhgCwfwAnwe5vDejgG44o/fbm1C5ZlYQvQDARPAIQGxCWBM+wWl37ZQESb4gImexGMDouhGLx1Cst0Saa4b4AqO4Hk4gxo+3DHAV/nx27p3JziPM2pVgoiia5MdEzCGULprIN7gEEeQ5IQxEBBBQnxhsDb5auGmAAYcHMA9eAAz8PBol8/xij9+C4Djlim4gJjWcwZBhCBgMIIYxGAVIkH3ZtcBuLdtRFMWsPGoY9rN+HoBji9VBYdwD2ZQg4cnO7OSq/z4rU5KKdwVbFAjNojCQzTlCLPFSxtamwh2jMUcEgg2Wm/6XgErIBhBckQtGN3CzbVacERgCnfgLswhnvqf7QyAq/z4rRZm1YglYE3affGITaZsdIe2FmMIpnOCap25I6jt2kCwCW0D1uAD9sZctNGXcQIHCkINDQgc78aCr+zjtw3BU/ijdpw3zhCwcaONwBvdeS2YZKkJNJsMPf2JKEvC28RXxxI0ASJyzQCjCEQrO4Q7sFArEzjZhaFc4cdv+/JFdKULM4px0DfUBI2hIsy06BqLhGTQEVdbfAIZXYMPesq6VoCHICzUyjwInO4Y411//LYLs6TDa9wvg2CC2rElgAnpTBziThxaL22MYhzfkghz6GAs2VHbbdM91VZu1MEEpupMMwKyVTb5ij9+u4VJG/5EgEMMmFF01cFai3isRbKbzb+YaU/MQbAm2XSMoUPAmvZzbuKYRIFApbtlrfFuUGd6vq2hXNnH78ZLh/iFhsQG3T4D1ib7k5CC6vY0DCbtrohgLEIClXiGtl10zc0CnEGIhhatLBva7NP58Tvw0qE8yWhARLQ8h4+AhQSP+I4F5xoU+VilGRJs6wnS7ruti/4KvAY/CfdgqjsMy4pf8fodQO8/gnuX3f/3xi3om1/h7THr+co3x93PP9+FBUfbNUjcjEmhcrkT+8K7ml7V10Jo05mpIEFy1NmCJWx9SIKKt+EjAL4Ez8EBVOB6havuT/rByPvHXK+9zUcfcbb254+9fydJknYnRr1oGfdaiAgpxu1Rx/Rek8KISftx3L+DfsLWAANn8Hvw0/AFeAGO9DFV3c6D+CcWbL8Dj9e7f+T1k8AZv/d7+PXWM/Z+VvdCrIvuAKO09RpEEQJM0Ci6+B4xhTWr4cZNOvhktabw0ta0rSJmqz3Yw5/AKXwenod7cAhTmBSPKf6JBdvH8IP17h95pXqw50/+BFnj88fev4NchyaK47OPhhtI8RFSvAfDSNh0Ck0p2gLxGkib5NJj/JWCr90EWQJvwBzO4AHcgztwAFN1evHPUVGwfXON+0debT1YeGON9Yy9/63X+OguiwmhIhQhD7l4sMqlG3D86Suc3qWZ4rWjI1X7u0Ytw6x3rIMeIOPDprfe2XzNgyj6PahhBjO4C3e6puDgXrdg+/5l948vF3bqwZetZ+z9Rx9zdIY5pInPK4Nk0t+l52xdK2B45Qd87nM8fsD5EfUhIcJcERw4RdqqH7Yde5V7m1vhNmtedkz6EDzUMF/2jJYWbC+4fzzA/Y+/8PPH3j9dcBAPIRP8JLXd5BpAu03aziOL3VVHZzz3CXWDPWd+SH2AnxIqQoTZpo9Ckc6HIrFbAbzNmlcg8Ag8NFDDAhbJvTBZXbC94P7t68EXfv6o+21gUtPETU7bbkLxvNKRFG2+KXzvtObonPP4rBvsgmaKj404DlshFole1Glfh02fE7bYR7dZ82oTewIBGn1Md6CG6YUF26X376oevOLzx95vhUmgblI6LBZwTCDY7vMq0op5WVXgsObOXJ+1x3qaBl9j1FeLxbhU9w1F+Wiba6s1X/TBz1LnUfuYDi4r2C69f1f14BWfP+p+W2GFKuC9phcELMYRRLur9DEZTUdEH+iEqWdaM7X4WOoPGI+ZYD2+wcQ+y+ioHUZ9dTDbArzxmi/bJI9BND0Ynd6lBdve/butBw8+f/T9D3ABa3AG8W3VPX4hBin+bj8dMMmSpp5pg7fJ6xrBFE2WQQEWnV8Qg3FbAWzYfM1rREEnmvkN2o1+acG2d/9u68GDzx91v3mAjb1zkpqT21OipPKO0b9TO5W0nTdOmAQm0TObts3aBKgwARtoPDiCT0gHgwnbArzxmtcLc08HgF1asN0C4Ms/fvD5I+7PhfqyXE/b7RbbrGyRQRT9ARZcwAUmgdoz0ehJ9Fn7QAhUjhDAQSw0bV3T3WbNa59jzmiP6GsWbGXDX2ytjy8+f9T97fiBPq9YeLdBmyuizZHaqXITnXiMUEEVcJ7K4j3BFPurtB4bixW8wTpweL8DC95szWMOqucFYGsWbGU7p3TxxxefP+r+oTVktxY0v5hbq3KiOKYnY8ddJVSBxuMMVffNbxwIOERShst73HZ78DZrHpmJmH3K6sGz0fe3UUj0eyRrSCGTTc+rjVNoGzNSv05srAxUBh8IhqChiQgVNIIBH3AVPnrsnXQZbLTm8ammv8eVXn/vWpaTem5IXRlt+U/LA21zhSb9cye6jcOfCnOwhIAYXAMVTUNV0QhVha9xjgA27ODJbLbmitt3tRN80lqG6N/khgot4ZVlOyO4WNg3OIMzhIZQpUEHieg2im6F91hB3I2tubql6BYNN9Hj5S7G0G2tahslBWKDnOiIvuAEDzakDQKDNFQT6gbn8E2y4BBubM230YIpBnDbMa+y3dx0n1S0BtuG62lCCXwcY0F72T1VRR3t2ONcsmDjbmzNt9RFs2LO2hQNyb022JisaI8rAWuw4HI3FuAIhZdOGIcdjLJvvObqlpqvWTJnnQbyi/1M9O8UxWhBs//H42I0q1Yb/XPGONzcmm+ri172mHKvZBpHkJaNJz6v9jxqiklDj3U4CA2ugpAaYMWqNXsdXbmJNd9egCnJEsphXNM+MnK3m0FCJ5S1kmJpa3DgPVbnQnPGWIDspW9ozbcO4K/9LkfaQO2KHuqlfFXSbdNzcEcwoqNEFE9zcIXu9/6n/ym/BC/C3aJLzEKPuYVlbFnfhZ8kcWxV3dbv4bKl28566wD+8C53aw49lTABp9PWbsB+knfc/Li3eVizf5vv/xmvnPKg5ihwKEwlrcHqucuVcVOxEv8aH37E3ZqpZypUulrHEtIWKUr+txHg+ojZDGlwnqmkGlzcVi1dLiNSJiHjfbRNOPwKpx9TVdTn3K05DBx4psIk4Ei8aCkJahRgffk4YnEXe07T4H2RR1u27E6wfQsBDofUgjFUFnwC2AiVtA+05J2zpiDK2Oa0c5fmAecN1iJzmpqFZxqYBCYhFTCsUNEmUnIcZ6aEA5rQVhEywG6w7HSW02XfOoBlQmjwulOFQAg66SvJblrTEX1YtJ3uG15T/BH1OfOQeuR8g/c0gdpT5fx2SKbs9EfHTKdM8A1GaJRHLVIwhcGyydZsbifAFVKl5EMKNU2Hryo+06BeTgqnxzYjThVySDikbtJPieco75lYfKAJOMEZBTjoITuWHXXZVhcUDIS2hpiXHV9Ku4u44bN5OYLDOkJo8w+xJSMbhBRHEdEs9JZUCkQrPMAvaHyLkxgkEHxiNkx/x2YB0mGsQ8EUWj/stW5YLhtS5SMu+/YBbNPDCkGTUybN8krRLBGPlZkVOA0j+a1+rkyQKWGaPHPLZOkJhioQYnVZ2hS3zVxMtgC46KuRwbJNd9nV2PHgb36F194ecf/Yeu2vAFe5nm/bRBFrnY4BauE8ERmZRFUn0k8hbftiVYSKMEme2dJCJSCGYAlNqh87bXOPdUkGy24P6d1ll21MBqqx48Fvv8ZHH8HZFY7j/uAq1xMJUFqCSUlJPmNbIiNsmwuMs/q9CMtsZsFO6SprzCS1Z7QL8xCQClEelpjTduDMsmWD8S1PT152BtvmIGvUeDA/yRn83u/x0/4qxoPHjx+PXY9pqX9bgMvh/Nz9kpP4pOe1/fYf3axUiMdHLlPpZCNjgtNFAhcHEDxTumNONhHrBduW+vOyY++70WWnPXj98eA4kOt/mj/5E05l9+O4o8ePx67HFqyC+qSSnyselqjZGaVK2TadbFLPWAQ4NBhHqDCCV7OTpo34AlSSylPtIdd2AJZlyzYQrDJ5lcWGNceD80CunPLGGzsfD+7wRb95NevJI5docQ3tgCyr5bGnyaPRlmwNsFELViOOx9loebGNq2moDOKpHLVP5al2cymWHbkfzGXL7kfRl44H9wZy33tvt+PB/Xnf93e+nh5ZlU18wCiRUa9m7kib9LYuOk+hudQNbxwm0AQqbfloimaB2lM5fChex+ylMwuTbfmXQtmWlenZljbdXTLuOxjI/fDDHY4Hjx8/Hrse0zXfPFxbUN1kKqSCCSk50m0Ajtx3ub9XHBKHXESb8iO6E+qGytF4nO0OG3SXzbJlhxBnKtKyl0NwybjvYCD30aMdjgePHz8eu56SVTBbgxJMliQ3Oauwg0QHxXE2Ez/EIReLdQj42Gzb4CLS0YJD9xUx7bsi0vJi5mUbW1QzL0h0PFk17rtiIPfJk52MB48fPx67npJJwyrBa2RCCQRTbGZSPCxTPOiND4G2pYyOQ4h4jINIJh5wFU1NFZt+IsZ59LSnDqBjZ2awbOku+yInunLcd8VA7rNnOxkPHj9+PGY9B0MWJJNozOJmlglvDMXDEozdhQWbgs/U6oBanGzLrdSNNnZFjOkmbi5bNt1lX7JLLhn3vXAg9/h4y/Hg8ePHI9dzQMEkWCgdRfYykYKnkP7D4rIujsujaKPBsB54vE2TS00ccvFY/Tth7JXeq1hz+qgVy04sAJawTsvOknHfCwdyT062HA8eP348Zj0vdoXF4pilKa2BROed+9fyw9rWRXeTFXESMOanvDZfJuJaSXouQdMdDJZtekZcLLvEeK04d8m474UDuaenW44Hjx8/Xns9YYqZpszGWB3AN/4VHw+k7WSFtJ3Qicuqb/NlVmgXWsxh570xg2UwxUw3WfO6B5nOuO8aA7lnZxuPB48fPx6znm1i4bsfcbaptF3zNT78eFPtwi1OaCNOqp1x3zUGcs/PN++AGD1+fMXrSVm2baTtPhPahbPhA71wIHd2bXzRa69nG+3CraTtPivahV/55tXWg8fyRY/9AdsY8VbSdp8V7cKrrgdfM//z6ILQFtJ2nxHtwmuoB4/kf74+gLeRtvvMaBdeSz34+vifx0YG20jbfTa0C6+tHrwe//NmOG0L8EbSdp8R7cLrrQe/996O+ai3ujQOskpTNULa7jOjXXj99eCd8lHvoFiwsbTdZ0a78PrrwTvlo966pLuRtB2fFe3Cm6oHP9kNH/W2FryxtN1nTLvwRurBO+Kj3pWXHidtx2dFu/Bm68Fb81HvykuPlrb7LGkX3mw9eGs+6h1Y8MbSdjegXcguQLjmevDpTQLMxtJ2N6NdyBZu9AbrwVvwUW+LbteULUpCdqm0HTelXbhNPe8G68Gb8lFvVfYfSNuxvrTdTWoXbozAzdaDZzfkorOj1oxVxlIMlpSIlpLrt8D4hrQL17z+c3h6hU/wv4Q/utps4+bm+6P/hIcf0JwQ5oQGPBL0eKPTYEXTW+eL/2DKn73J9BTXYANG57hz1cEMviVf/4tf5b/6C5pTQkMIWoAq7hTpOJjtAM4pxKu5vg5vXeUrtI09/Mo/5H+4z+Mp5xULh7cEm2QbRP2tFIKR7WM3fPf/jZ3SWCqLM2l4NxID5zB72HQXv3jj/8mLR5xXNA5v8EbFQEz7PpRfl1+MB/hlAN65qgDn3wTgH13hK7T59bmP+NIx1SHHU84nLOITt3iVz8mNO+lPrjGAnBFqmioNn1mTyk1ta47R6d4MrX7tjrnjYUpdUbv2rVr6YpVfsGG58AG8Ah9eyUN8CX4WfgV+G8LVWPDGb+Zd4cU584CtqSbMKxauxTg+dyn/LkVgA+IR8KHtejeFKRtTmLLpxN6mYVLjYxwXf5x2VofiZcp/lwKk4wGOpYDnoIZPdg/AAbwMfx0+ge9dgZvYjuqKe4HnGnykYo5TvJbG0Vj12JagRhwKa44H95ShkZa5RyLGGdfYvG7aw1TsF6iapPAS29mNS3NmsTQZCmgTzFwgL3upCTgtBTRwvGMAKrgLn4evwin8+afJRcff+8izUGUM63GOOuAs3tJkw7J4kyoNreqrpO6cYLQeFUd7TTpr5YOTLc9RUUogUOVJQ1GYJaFLAW0oTmKyYS46ZooP4S4EON3xQ5zC8/CX4CnM4c1PE8ApexpoYuzqlP3d4S3OJP8ZDK7cKWNaTlqmgDiiHwl1YsE41w1zT4iRTm3DBqxvOUsbMKKDa/EHxagtnta072ejc3DOIh5ojvh8l3tk1JF/AV6FU6jh3U8HwEazLgdCLYSQ+MYiAI2ltomkzttUb0gGHdSUUgsIYjTzLG3mObX4FBRaYtpDVNZrih9TgTeYOBxsEnN1gOCTM8Bsw/ieMc75w9kuAT6A+/AiHGvN/+Gn4KRkiuzpNNDYhDGFndWRpE6SVfm8U5bxnSgVV2jrg6JCKmneqey8VMFgq2+AM/i4L4RUbfSi27lNXZ7R7W9RTcq/q9fk4Xw3AMQd4I5ifAZz8FcVtm9SAom/dyN4lczJQW/kC42ZrHgcCoIf1oVMKkVItmMBi9cOeNHGLqOZk+QqQmrbc5YmYgxELUUN35z2iohstgfLIFmcMV7s4CFmI74L9+EFmGsi+tGnAOD4Yk9gIpo01Y4cA43BWGygMdr4YZekG3OBIUXXNukvJS8tqa06e+lSDCtnqqMFu6hWHXCF+WaYt64m9QBmNxi7Ioy7D+fa1yHw+FMAcPt7SysFLtoG4PXAk7JOA3aAxBRqUiAdU9Yp5lK3HLSRFtOim0sa8euEt08xvKjYjzeJ2GU7YawexrnKI9tmobInjFXCewpwriY9+RR4aaezFhMhGCppKwom0ChrgFlKzyPKkGlTW1YQrE9HJqu8hKGgMc6hVi5QRq0PZxNfrYNgE64utmRv6KKHRpxf6VDUaOvNP5jCEx5q185My/7RKz69UQu2im5k4/eownpxZxNLwiZ1AZTO2ZjWjkU9uaB2HFn6Q3u0JcsSx/qV9hTEApRzeBLDJQXxYmTnq7bdLa3+uqFrxLJ5w1TehnNHx5ECvCh2g2c3hHH5YsfdaSKddztfjQ6imKFGSyFwlLzxEGPp6r5IevVjk1AMx3wMqi1NxDVjLBiPs9tbsCkIY5we5/ML22zrCScFxnNtzsr9Wcc3CnD+pYO+4VXXiDE0oc/vQQ/fDK3oPESJMYXNmJa/DuloJZkcTpcYE8lIH8Dz8DJMiynNC86Mb2lNaaqP/+L7f2fcE/yP7/Lde8xfgSOdMxvOixZf/9p3+M4hT1+F+zApxg9XfUvYjc8qX2lfOOpK2gNRtB4flpFu9FTKCp2XJRgXnX6olp1zyYjTKJSkGmLE2NjUr1bxFM4AeAAHBUFIeSLqXR+NvH/M9fOnfHzOD2vCSyQJKzfgsCh+yi/Mmc35F2fUrw7miW33W9hBD1vpuUojFphIyvg7aTeoymDkIkeW3XLHmguMzbIAJejN6B5MDrhipE2y6SoFRO/AK/AcHHZHNIfiWrEe/C6cr3f/yOvrQKB+zMM55/GQdLDsR+ifr5Fiuu+/y+M78LzOE5dsNuXC3PYvYWd8NXvphLSkJIasrlD2/HOqQ+RjcRdjKTGWYhhVUm4yxlyiGPuMsZR7sMCHUBeTuNWA7if+ifXgc/hovftHXs/DV+Fvwe+f8shzMiMcweFgBly3//vwJfg5AN4450fn1Hd1Rm1aBLu22Dy3y3H2+OqMemkbGZ4jozcDjJf6596xOLpC0eMTHbKnxLxH27uZ/bMTGs2jOaMOY4m87CfQwF0dw53oa1k80JRuz/XgS+8fX3N9Af4qPIMfzKgCp4H5TDGe9GGeFPzSsZz80SlPTxXjgwJmC45njzgt2vbQ4b4OAdUK4/vWhO8d8v6EE8fMUsfakXbPpFJeLs2ubM/qdm/la3WP91uWhxXHjoWhyRUq2iJ/+5mA73zwIIo+LoZ/SgvIRjAd1IMvvn98PfgOvAJfhhm8scAKVWDuaRaK8aQ9f7vuPDH6Bj47ZXau7rqYJ66mTDwEDU6lLbCjCK0qTXyl5mnDoeNRxanj3FJbaksTk0faXxHxLrssgPkWB9LnA/MFleXcJozzjwsUvUG0X/QCve51qkMDXp9mtcyOy3rwBfdvVJK7D6/ACSzg3RoruIq5UDeESfEmVclDxnniU82vxMLtceD0hGZWzBNPMM/jSPne2OVatiTKUpY5vY7gc0LdUAWeWM5tH+O2I66AOWw9xT2BuyRVLGdoDHUsVRXOo/c+ZdRXvFfnxWyIV4upFLCl9eAL7h8Zv0QH8Ry8pA2cHzQpGesctVA37ZtklBTgHjyvdSeKY/RZw/kJMk0Y25cSNRWSigQtlULPTw+kzuJPeYEkXjQRpoGZobYsLF79pyd1dMRHInbgFTZqNLhDqiIsTNpoex2WLcy0/X6rHcdMMQvFSd5dWA++4P7xv89deACnmr36uGlL69bRCL6BSZsS6c0TU2TKK5gtWCzgAOOwQcurqk9j8whvziZSMLcq5hbuwBEsYjopUBkqw1yYBGpLA97SRElEmx5MCInBY5vgLk94iKqSWmhIGmkJ4Bi9m4L645J68LyY4wsFYBfUg5feP/6gWWm58IEmKQM89hq7KsZNaKtP5TxxrUZZVkNmMJtjbKrGxLNEbHPJxhqy7lAmbC32ZqeF6lTaknRWcYaFpfLUBh/rwaQycCCJmW15Kstv6jRHyJFry2C1ahkkIW0LO75s61+owxK1y3XqweX9m5YLM2DPFeOjn/iiqCKJ+yKXF8t5Yl/kNsqaSCryxPq5xWTFIaP8KSW0RYxqupaUf0RcTNSSdJZGcKYdYA6kdtrtmyBckfKXwqk0pHpUHlwWaffjNRBYFPUDWa8e3Lt/o0R0CdisKDM89cX0pvRHEfM8ca4t0s2Xx4kgo91MPQJ/0c9MQYq0co8MBh7bz1fio0UUHLR4aAIOvOmoYO6kwlEVODSSTliWtOtH6sPkrtctF9ZtJ9GIerBskvhdVS5cFNv9s1BU0AbdUgdK4FG+dRnjFmDTzniRMdZO1QhzMK355vigbdkpz9P6qjUGE5J2qAcXmwJ20cZUiAD0z+pGMx6xkzJkmEf40Hr4qZfVg2XzF9YOyoV5BjzVkUJngKf8lgNYwKECEHrCNDrWZzMlflS3yBhr/InyoUgBc/lKT4pxVrrC6g1YwcceK3BmNxZcAtz3j5EIpqguh9H6wc011YN75cKDLpFDxuwkrPQmUwW4KTbj9mZTwBwLq4aQMUZbHm1rylJ46dzR0dua2n3RYCWZsiHROeywyJGR7mXKlpryyCiouY56sFkBWEnkEB/raeh/Sw4162KeuAxMQpEkzy5alMY5wamMsWKKrtW2WpEWNnReZWONKWjrdsKZarpFjqCslq773PLmEhM448Pc3+FKr1+94vv/rfw4tEcu+lKTBe4kZSdijBrykwv9vbCMPcLQTygBjzVckSLPRVGslqdunwJ4oegtFOYb4SwxNgWLCmD7T9kVjTv5YDgpo0XBmN34Z/rEHp0sgyz7lngsrm4lvMm2Mr1zNOJYJ5cuxuQxwMGJq/TP5emlb8fsQBZviK4t8hFL+zbhtlpwaRSxQRWfeETjuauPsdGxsBVdO7nmP4xvzSoT29pRl7kGqz+k26B3Oy0YNV+SXbbQas1ctC/GarskRdFpKczVAF1ZXnLcpaMuzVe6lZ2g/1ndcvOVgRG3sdUAY1bKD6achijMPdMxV4muKVorSpiDHituH7rSTs7n/4y5DhRXo4FVBN4vO/zbAcxhENzGbHCzU/98Mcx5e7a31kWjw9FCe/zNeYyQjZsWb1uc7U33pN4Mji6hCLhivqfa9Ss6xLg031AgfesA/l99m9fgvnaF9JoE6bYKmkGNK3aPbHB96w3+DnxFm4hs0drLsk7U8kf/N/CvwQNtllna0rjq61sH8L80HAuvwH1tvBy2ChqWSCaYTaGN19sTvlfzFD6n+iKTbvtayfrfe9ueWh6GJFoxLdr7V72a5ZpvHcCPDzma0wTO4EgbLyedxstO81n57LYBOBzyfsOhUKsW1J1BB5vr/tz8RyqOFylQP9Tvst2JALsC5lsH8PyQ40DV4ANzYa4dedNiKNR1s+x2wwbR7q4/4cTxqEk4LWDebfisuo36JXLiWFjOtLrlNWh3K1rRS4xvHcDNlFnNmWBBAl5SWaL3oPOfnvbr5pdjVnEaeBJSYjuLEkyLLsWhKccadmOphZkOPgVdalj2QpSmfOsADhMWE2ZBu4+EEJI4wKTAuCoC4xwQbWXBltpxbjkXJtKxxabo9e7tyhlgb6gNlSbUpMh+l/FaqzVwewGu8BW1Zx7pTpQDJUjb8tsUTW6+GDXbMn3mLbXlXJiGdggxFAoUrtPS3wE4Nk02UZG2OOzlk7fRs7i95QCLo3E0jtrjnM7SR3uS1p4qtS2nJ5OwtQVHgOvArLBFijZUV9QtSl8dAY5d0E0hM0w3HS2DpIeB6m/A1+HfhJcGUq4sOxH+x3f5+VO+Ds9rYNI7zPXOYWPrtf8bYMx6fuOAX5jzNR0PdsuON+X1f7EERxMJJoU6GkTEWBvVolVlb5lh3tKCg6Wx1IbaMDdJ+9sUCc5KC46hKGCk3IVOS4TCqdBNfUs7Kd4iXf2RjnT/LLysJy3XDcHLh/vde3x8DoGvwgsa67vBk91G5Pe/HbOe7xwym0NXbtiuuDkGO2IJDh9oQvJ4cY4vdoqLDuoH9Zl2F/ofsekn8lkuhIlhQcffUtSjytFyp++p6NiE7Rqx/lodgKVoceEp/CP4FfjrquZaTtj2AvH5K/ywpn7M34K/SsoYDAdIN448I1/0/wveW289T1/lX5xBzc8N5IaHr0XMOQdHsIkDuJFifj20pBm5jzwUv9e2FhwRsvhAbalCIuIw3bhJihY3p6nTFFIZgiSYjfTf3aXuOjmeGn4bPoGvwl+CFzTRczBIuHBEeImHc37/lGfwZR0cXzVDOvaKfNHvwe+suZ771K/y/XcBlsoN996JpBhoE2toYxOznNEOS5TJc6Id5GEXLjrWo+LEWGNpPDU4WAwsIRROu+1vM+0oW37z/MBN9kqHnSArwPfgFJ7Cq/Ai3Ie7g7ncmI09v8sjzw9mzOAEXoIHxURueaAce5V80f/DOuuZwHM8vsMb5wBzOFWM7wymTXPAEvm4vcFpZ2ut0VZRjkiP2MlmLd6DIpbGSiHOjdnUHN90hRYmhTnmvhzp1iKDNj+b7t5hi79lWGwQ+HN9RsfFMy0FXbEwhfuczKgCbyxYwBmcFhhvo/7a44v+i3XWcwDP86PzpGQYdWh7csP5dBvZ1jNzdxC8pBGuxqSW5vw40nBpj5JhMwvOzN0RWqERHMr4Lv1kWX84xLR830G3j6yqZ1a8UstTlW+qJPOZ+sZ7xZPKTJLhiNOAFd6tk+jrTH31ncLOxid8+nzRb128HhUcru/y0Wn6iT254YPC6FtVSIMoW2sk727AhvTtrWKZTvgsmckfXYZWeNRXx/3YQ2OUxLDrbHtN11IwrgXT6c8dATDwLniYwxzO4RzuQqTKSC5gAofMZ1QBK3zQ4JWobFbcvJm87FK+6JXrKahLn54m3p+McXzzYtP8VF/QpJuh1OwieElEoI1pRxPS09FBrkq2tWCU59+HdhNtTIqKm8EBrw2RTOEDpG3IKo2Y7mFdLm3ZeVjYwVw11o/oznceMve4CgMfNym/utA/d/ILMR7gpXzRy9eDsgLcgbs8O2Va1L0zzIdwGGemTBuwROHeoMShkUc7P+ISY3KH5ZZeWqO8mFTxQYeXTNuzvvK5FGPdQfuu00DwYFY9dyhctEt+OJDdnucfpmyhzUJzfsJjr29l8S0bXBfwRS9ZT26tmMIdZucch5ZboMz3Nio3nIOsYHCGoDT4kUA9MiXEp9Xsui1S8th/kbWIrMBxDGLodWUQIWcvnXy+9M23xPiSMOiRPqM+YMXkUN3gXFrZJwXGzUaMpJfyRS9ZT0lPe8TpScuRlbMHeUmlaKDoNuy62iWNTWNFYjoxFzuJs8oR+RhRx7O4SVNSXpa0ZJQ0K1LAHDQ+D9IepkMXpcsq5EVCvClBUIzDhDoyKwDw1Lc59GbTeORivugw1IcuaEOaGWdNm+Ps5fQ7/tm0DjMegq3yM3vb5j12qUId5UZD2oxDSEWOZMSqFl/W+5oynWDa/aI04tJRQ2eTXusg86SQVu/nwSYwpW6wLjlqIzwLuxGIvoAvul0PS+ZNz0/akp/pniO/8JDnGyaCkzbhl6YcqmK/69prxPqtpx2+Km9al9sjL+rwMgHw4jE/C8/HQ3m1vBuL1fldbzd8mOueVJ92syqdEY4KJjSCde3mcRw2TA6szxedn+zwhZMps0XrqEsiUjnC1hw0TELC2Ek7uAAdzcheXv1BYLagspxpzSAoZZUsIzIq35MnFQ9DOrlNB30jq3L4pkhccKUAA8/ocvN1Rzx9QyOtERs4CVsJRK/DF71kPYrxYsGsm6RMh4cps5g1DOmM54Ly1ii0Hd3Y/BMk8VWFgBVmhqrkJCPBHAolwZaWzLR9Vb7bcWdX9NyUYE+uB2BKfuaeBUcjDljbYVY4DdtsVWvzRZdWnyUzDpjNl1Du3aloAjVJTNDpcIOVVhrHFF66lLfJL1zJr9PQ2nFJSBaKoDe+sAvLufZVHVzYh7W0h/c6AAZ+7Tvj6q9j68G/cTCS/3n1vLKHZwNi+P+pS0WkZNMBMUl+LDLuiE4omZy71r3UFMwNJV+VJ/GC5ixVUkBStsT4gGKh0Gm4Oy3qvq7Lbmq24nPdDuDR9deR11XzP4vFu3TYzfnIyiSVmgizUYGqkIXNdKTY9pgb9D2Ix5t0+NHkVzCdU03suWkkVZAoCONCn0T35gAeW38de43mf97sMOpSvj4aa1KYUm58USI7Wxxes03bAZdRzk6UtbzMaCQ6IxO0dy7X+XsjoD16hpsBeGz9dfzHj+R/Hp8nCxZRqkEDTaCKCSywjiaoMJ1TITE9eg7Jqnq8HL6gDwiZb0u0V0Rr/rmvqjxKuaLCX7ZWXTvAY+uvm3z8CP7nzVpngqrJpZKwWnCUjIviYVlirlGOzPLI3SMVyp/elvBUjjDkNhrtufFFErQ8pmdSlbK16toBHlt/HV8uHMX/vEGALkV3RJREiSlopxwdMXOZPLZ+ix+kAHpMKIk8UtE1ygtquttwxNhphrIZ1IBzjGF3IIGxGcBj6q8bHJBG8T9vdsoWrTFEuebEZuVxhhClH6P5Zo89OG9fwHNjtNQTpD0TG9PJLEYqvEY6Rlxy+ZZGfL0Aj62/bnQCXp//eeM4KzfQVJbgMQbUjlMFIm6TpcfWlZje7NBSV6IsEVmumWIbjiloUzQX9OzYdo8L1wjw2PrrpimONfmfNyzKklrgnEkSzT5QWYQW40YShyzqsRmMXbvVxKtGuYyMKaU1ugenLDm5Ily4iT14fP11Mx+xJv+zZ3MvnfdFqxU3a1W/FTB4m3Qfsyc1XUcdVhDeUDZXSFHHLQj/Y5jtC7ZqM0CXGwB4bP11i3LhOvzPGygYtiUBiwQV/4wFO0majijGsafHyRLu0yG6q35cL1rOpVxr2s5cM2jJYMCdc10Aj6q/blRpWJ//+dmm5psMl0KA2+AFRx9jMe2WbC4jQxnikd4DU8TwUjRVacgdlhmr3bpddzuJ9zXqr2xnxJfzP29RexdtjDVZqzkqa6PyvcojGrfkXiJ8SEtml/nYskicv0ivlxbqjemwUjMw5evdg8fUX9nOiC/lf94Q2i7MURk9nW1MSj5j8eAyV6y5CN2S6qbnw3vdA1Iwq+XOSCl663udN3IzLnrt+us25cI1+Z83SXQUldqQq0b5XOT17bGpLd6ssN1VMPf8c+jG8L3NeCnMdF+Ra3fRa9dft39/LuZ/3vwHoHrqGmQFafmiQw6eyzMxS05K4bL9uA+SKUQzCnSDkqOGokXyJvbgJ/BHI+qvY69//4rl20NsmK2ou2dTsyIALv/91/8n3P2Aao71WFGi8KKv1fRC5+J67Q/507/E/SOshqN5TsmYIjVt+kcjAx98iz/4SaojbIV1rexE7/C29HcYD/DX4a0rBOF5VTu7omsb11L/AWcVlcVZHSsqGuXLLp9ha8I//w3Mv+T4Ew7nTBsmgapoCrNFObIcN4pf/Ob/mrvHTGqqgAupL8qWjWPS9m/31jAe4DjA+4+uCoQoT/zOzlrNd3qd4SdphFxsUvYwGWbTWtISc3wNOWH+kHBMfc6kpmpwPgHWwqaSUG2ZWWheYOGQGaHB+eQ/kn6b3pOgLV+ODSn94wDvr8Bvb70/LLuiPPEr8OGVWfDmr45PZyccEmsVXZGe1pRNX9SU5+AVQkNTIVPCHF/jGmyDC9j4R9LfWcQvfiETmgMMUCMN1uNCakkweZsowdYobiMSlnKA93u7NzTXlSfe+SVbfnPQXmg9LpYAQxpwEtONyEyaueWM4FPjjyjG3uOaFmBTWDNgBXGEiQpsaWhnAqIijB07Dlsy3fUGeP989xbWkyf+FF2SNEtT1E0f4DYYVlxFlbaSMPIRMk/3iMU5pME2SIWJvjckciebkQuIRRyhUvkHg/iUljG5kzVog5hV7vIlCuBrmlhvgPfNHQM8lCf+FEGsYbMIBC0qC9a0uuy2wLXVbLBaP5kjHokCRxapkQyzI4QEcwgYHRZBp+XEFTqXFuNVzMtjXLJgX4gAid24Hjwc4N3dtVSe+NNiwTrzH4WVUOlDobUqr1FuAgYllc8pmzoVrELRHSIW8ViPxNy4xwjBpyR55I6J220qQTZYR4guvUICJiSpr9gFFle4RcF/OMB7BRiX8sSfhpNSO3lvEZCQfLUVTKT78Ek1LRLhWN+yLyTnp8qWUZ46b6vxdRGXfHVqx3eI75YaLa4iNNiK4NOW7wPW6lhbSOF9/M9qw8e/aoB3d156qTzxp8pXx5BKAsYSTOIIiPkp68GmTq7sZtvyzBQaRLNxIZ+paozHWoLFeExIhRBrWitHCAHrCF7/thhD8JhYz84wg93QRV88wLuLY8zF8sQ36qF1J455bOlgnELfshKVxYOXKVuKx0jaj22sczTQqPqtV/XDgpswmGTWWMSDw3ssyUunLLrVPGjYRsH5ggHeHSWiV8kT33ycFSfMgkoOK8apCye0J6VW6GOYvffgU9RWsukEi2kUV2nl4dOYUzRik9p7bcA4ggdJ53LxKcEe17B1R8eqAd7dOepV8sTXf5lhejoL85hUdhDdknPtKHFhljOT+bdq0hxbm35p2nc8+Ja1Iw+tJykgp0EWuAAZYwMVwac5KzYMslhvgHdHRrxKnvhTYcfKsxTxtTETkjHO7rr3zjoV25lAQHrqpV7bTiy2aXMmUhTBnKS91jhtR3GEoF0oLnWhWNnYgtcc4N0FxlcgT7yz3TgNIKkscx9jtV1ZKpWW+Ub1tc1eOv5ucdgpx+FJy9pgbLE7xDyXb/f+hLHVGeitHOi6A7ybo3sF8sS7w7cgdk0nJaOn3hLj3uyD0Zp5pazFIUXUpuTTU18d1EPkDoX8SkmWTnVIozEdbTcZjoqxhNHf1JrSS/AcvHjZ/SMHhL/7i5z+POsTUh/8BvNfYMTA8n+yU/MlTZxSJDRStqvEuLQKWwDctMTQogUDyQRoTQG5Kc6oQRE1yV1jCA7ri7jdZyK0sYTRjCR0Hnnd+y7nHxNgTULqw+8wj0mQKxpYvhjm9uSUxg+TTy7s2GtLUGcywhXSKZN275GsqlclX90J6bRI1aouxmgL7Q0Nen5ziM80SqMIo8cSOo+8XplT/5DHNWsSUr/6lLN/QQ3rDyzLruEW5enpf7KqZoShEduuSFOV7DLX7Ye+GmXb6/hnNNqKsVXuMDFpb9Y9eH3C6NGEzuOuI3gpMH/I6e+zDiH1fXi15t3vA1czsLws0TGEtmPEJdiiFPwlwKbgLHAFk4P6ZyPdymYYHGE0dutsChQBl2JcBFlrEkY/N5bQeXQ18gjunuMfMfsBlxJSx3niO485fwO4fGD5T/+3fPQqkneWVdwnw/3bMPkW9Wbqg+iC765Zk+xcT98ibKZc2EdgHcLoF8cSOo/Oc8fS+OyEULF4g4sJqXVcmfMfsc7A8v1/yfGXmL9I6Fn5pRwZhsPv0TxFNlAfZCvG+Oohi82UC5f/2IsJo0cTOm9YrDoKhFPEUr/LBYTUNht9zelHXDqwfPCIw4owp3mOcIQcLttWXFe3VZ/j5H3cIc0G6oPbCR+6Y2xF2EC5cGUm6wKC5tGEzhsWqw5hNidUiKX5gFWE1GXh4/Qplw4sVzOmx9QxU78g3EF6wnZlEN4FzJ1QPSLEZz1KfXC7vd8ssGdIbNUYpVx4UapyFUHzJoTOo1McSkeNn1M5MDQfs4qQuhhX5vQZFw8suwWTcyYTgioISk2YdmkhehG4PkE7w51inyAGGaU+uCXADabGzJR1fn3lwkty0asIo8cROm9Vy1g0yDxxtPvHDAmpu+PKnM8Ix1wwsGw91YJqhteaWgjYBmmQiebmSpwKKzE19hx7jkzSWOm66oPbzZ8Yj6kxVSpYjVAuvLzYMCRo3oTQecOOjjgi3NQ4l9K5/hOGhNTdcWVOTrlgYNkEXINbpCkBRyqhp+LdRB3g0OU6rMfW2HPCFFMV9nSp+uB2woepdbLBuJQyaw/ZFysXrlXwHxI0b0LovEkiOpXGA1Ijagf+KUNC6rKNa9bQnLFqYNkEnMc1uJrg2u64ELPBHpkgWbmwKpJoDhMwNbbGzAp7Yg31wS2T5rGtzit59PrKhesWG550CZpHEzpv2NGRaxlNjbMqpmEIzygJqQfjypycs2pg2cS2RY9r8HUqkqdEgKTWtWTKoRvOBPDYBltja2SO0RGjy9UHtxwRjA11ujbKF+ti5cIR9eCnxUg6owidtyoU5tK4NLji5Q3HCtiyF2IqLGYsHViOXTXOYxucDqG0HyttqYAKqYo3KTY1ekyDXRAm2AWh9JmsVh/ccg9WJ2E8YjG201sPq5ULxxX8n3XLXuMInbft2mk80rRGjCGctJ8/GFdmEQ9Ug4FlE1ll1Y7jtiraqm5Fe04VV8lvSVBL8hiPrfFVd8+7QH3Qbu2ipTVi8cvSGivc9cj8yvH11YMHdNSERtuOslM97feYFOPKzGcsI4zW0YGAbTAOaxCnxdfiYUmVWslxiIblCeAYr9VYR1gM7GmoPrilunSxxeT3DN/2eBQ9H11+nk1adn6VK71+5+Jfct4/el10/7KBZfNryUunWSCPxPECk1rdOv1WVSrQmpC+Tl46YD3ikQYcpunSQgzVB2VHFhxHVGKDgMEY5GLlQnP7FMDzw7IacAWnO6sBr12u+XanW2AO0wQ8pknnFhsL7KYIqhkEPmEXFkwaN5KQphbkUmG72wgw7WSm9RiL9QT925hkjiVIIhphFS9HKI6/8QAjlpXqg9W2C0apyaVDwKQwrwLY3j6ADR13ZyUNByQXHQu6RY09Hu6zMqXRaNZGS/KEJs0cJEe9VH1QdvBSJv9h09eiRmy0V2uJcqHcShcdvbSNg5fxkenkVprXM9rDVnX24/y9MVtncvbKY706anNl3ASll9a43UiacVquXGhvq4s2FP62NGKfQLIQYu9q1WmdMfmUrDGt8eDS0cXozH/fjmUH6Jruvm50hBDSaEU/2Ru2LEN/dl006TSc/g7tfJERxGMsgDUEr104pfWH9lQaN+M4KWQjwZbVc2rZVNHsyHal23wZtIs2JJqtIc/WLXXRFCpJkfE9jvWlfFbsNQ9pP5ZBS0zKh4R0aMFj1IjTcTnvi0Zz2rt7NdvQb2mgbju1plsH8MmbnEk7KbK0b+wC2iy3aX3szW8xeZvDwET6hWZYwqTXSSG+wMETKum0Dq/q+x62gt2ua2ppAo309TRk9TPazfV3qL9H8z7uhGqGqxNVg/FKx0HBl9OVUORn8Q8Jx9gFttGQUDr3tzcXX9xGgN0EpzN9mdZ3GATtPhL+CjxFDmkeEU6x56kqZRusLzALXVqkCN7zMEcqwjmywDQ6OhyUe0Xao1Qpyncrg6wKp9XfWDsaZplElvQ/b3sdweeghorwBDlHzgk1JmMc/wiERICVy2VJFdMjFuLQSp3S0W3+sngt2njwNgLssFGVQdJ0tu0KH4ky1LW4yrbkuaA6Iy9oz/qEMMXMMDWyIHhsAyFZc2peV9hc7kiKvfULxCl9iddfRK1f8kk9qvbdOoBtOg7ZkOZ5MsGrSHsokgLXUp9y88smniwWyuFSIRVmjplga3yD8Uij5QS1ZiM4U3Qw5QlSm2bXjFe6jzzBFtpg+/YBbLAWG7OPynNjlCw65fukGNdkJRf7yM1fOxVzbxOJVocFoYIaGwH22mIQkrvu1E2nGuebxIgW9U9TSiukPGU+Lt++c3DJPKhyhEEbXCQLUpae2exiKy6tMPe9mDRBFCEMTWrtwxN8qvuGnt6MoihKWS5NSyBhbH8StXoAz8PLOrRgLtOT/+4vcu+7vDLnqNvztOq7fmd8sMmY9Xzn1zj8Dq8+XVdu2Nv0IIySgEdQo3xVHps3Q5i3fLFsV4aiqzAiBhbgMDEd1uh8qZZ+lwhjkgokkOIv4xNJmyncdfUUzgB4oFMBtiu71Xumpz/P+cfUP+SlwFExwWW62r7b+LSPxqxn/gvMZ5z9C16t15UbNlq+jbGJtco7p8wbYlL4alSyfWdeuu0j7JA3JFNuVAwtst7F7FhWBbPFNKIUORndWtLraFLmMu7KFVDDOzqkeaiN33YAW/r76wR4XDN/yN1z7hejPau06EddkS/6XThfcz1fI/4K736fO48vlxt2PXJYFaeUkFS8U15XE3428xdtn2kc8GQlf1vkIaNRRnOMvLTWrZbElEHeLWi1o0dlKPAh1MVgbbVquPJ5+Cr8LU5/H/+I2QlHIU2ClXM9G8v7Rr7oc/hozfUUgsPnb3D+I+7WF8kNO92GY0SNvuxiE+2Bt8prVJTkzE64sfOstxuwfxUUoyk8VjcTlsqe2qITSFoSj6Epd4KsT6BZOWmtgE3hBfir8IzZDwgV4ZTZvD8VvPHERo8v+vL1DASHTz/i9OlKueHDjK5Rnx/JB1Vb1ioXdBra16dmt7dgik10yA/FwJSVY6XjA3oy4SqM2frqDPPSRMex9qs3XQtoWxMj7/Er8GWYsXgjaVz4OYumP2+9kbxvny/6kvWsEBw+fcb5bInc8APdhpOSs01tEqIkoiZjbAqKMruLbJYddHuHFRIyJcbdEdbl2sVLaySygunutBg96Y2/JjKRCdyHV+AEFtTvIpbKIXOamknYSiB6KV/0JetZITgcjjk5ZdaskBtWO86UF0ap6ozGXJk2WNiRUlCPFir66lzdm/SLSuK7EUdPz8f1z29Skq6F1fXg8+5UVR6bszncP4Tn4KUkkdJ8UFCY1zR1i8RmL/qQL3rlei4THG7OODlnKko4oI01kd3CaM08Ia18kC3GNoVaO9iDh+hWxSyTXFABXoau7Q6q9OxYg/OVEMw6jdbtSrJ9cBcewGmaZmg+bvkUnUUaGr+ZfnMH45Ivevl61hMcXsxYLFTu1hTm2zViCp7u0o5l+2PSUh9bDj6FgYypufBDhqK2+oXkiuHFHR3zfj+9PtA8oR0xnqX8qn+sx3bFODSbbF0X8EUvWQ8jBIcjo5bRmLOljDNtcqNtOe756h3l0VhKa9hDd2l1eqmsnh0MNMT/Cqnx6BInumhLT8luljzQ53RiJeA/0dxe5NK0o2fA1+GLXr6eNQWHNUOJssQaTRlGpLHKL9fD+IrQzTOMZS9fNQD4AnRNVxvTdjC+fJdcDDWQcyB00B0t9BDwTxXgaAfzDZ/DBXzRnfWMFRwuNqocOmX6OKNkY63h5n/fFcB28McVHqnXZVI27K0i4rDLNE9lDKV/rT+udVbD8dFFu2GGZ8mOt0kAXcoX3ZkIWVtw+MNf5NjR2FbivROHmhV1/pj2egv/fMGIOWTIWrV3Av8N9imV9IWml36H6cUjqEWNv9aNc+veb2sH46PRaHSuMBxvtW+twxctq0z+QsHhux8Q7rCY4Ct8lqsx7c6Sy0dl5T89rIeEuZKoVctIk1hNpfavER6yyH1Vvm3MbsUHy4ab4hWr/OZPcsRBphnaV65/ZcdYPNNwsjN/djlf9NqCw9U5ExCPcdhKxUgLSmfROpLp4WSUr8ojdwbncbvCf+a/YzRaEc6QOvXcGO256TXc5Lab9POvB+AWY7PigWYjzhifbovuunzRawsO24ZqQQAqguBtmpmPB7ysXJfyDDaV/aPGillgz1MdQg4u5MYaEtBNNHFjkRlSpd65lp4hd2AVPTfbV7FGpyIOfmNc/XVsPfg7vzaS/3nkvLL593ANLvMuRMGpQIhiF7kUEW9QDpAUbTWYBcbp4WpacHHY1aacqQyjGZS9HI3yCBT9kUZJhVOD+zUDvEH9ddR11fzPcTDQ5TlgB0KwqdXSavk9BC0pKp0WmcuowSw07VXmXC5guzSa4p0UvRw2lbDiYUx0ExJJRzWzi6Gm8cnEkfXXsdcG/M/jAJa0+bmCgdmQ9CYlNlSYZOKixmRsgiFxkrmW4l3KdFKv1DM8tk6WxPYJZhUUzcd8Kdtgrw/gkfXXDT7+avmfVak32qhtkg6NVdUS5wgkru1YzIkSduTW1FDwVWV3JQVJVuieTc0y4iDpFwc7/BvSalvKdQM8sv662cevz/+8sQVnjVAT0W2wLllw1JiMhJRxgDjCjLQsOzSFSgZqx7lAW1JW0e03yAD3asC+GD3NbQhbe+mN5GXH1F83KDOM4n/e5JIuH4NpdQARrFPBVptUNcjj4cVMcFSRTE2NpR1LEYbYMmfWpXgP9KejaPsLUhuvLCsVXznAG9dfx9SR1ud/3hZdCLHb1GMdPqRJgqDmm76mHbvOXDtiO2QPUcKo/TWkQ0i2JFXpBoo7vij1i1Lp3ADAo+qvG3V0rM//vFnnTE4hxd5Ka/Cor5YEdsLVJyKtDgVoHgtW11pWSjolPNMnrlrVj9Fv2Qn60twMwKPqr+N/wvr8z5tZcDsDrv06tkqyzESM85Ycv6XBWA2birlNCXrI6VbD2lx2L0vQO0QVTVVLH4SE67fgsfVXv8n7sz7/85Z7cMtbE6f088wSaR4kCkCm10s6pKbJhfqiUNGLq+0gLWC6eUAZFPnLjwqtKd8EwGvWX59t7iPW4X/eAN1svgRVSY990YZg06BD1ohLMtyFTI4pKTJsS9xREq9EOaPWiO2gpms7397x6nQJkbh+Fz2q/rqRROX6/M8bJrqlVW4l6JEptKeUFuMYUbtCQ7CIttpGc6MY93x1r1vgAnRXvY5cvwWPqb9uWQm+lP95QxdNMeWhOq1x0Db55C7GcUv2ZUuN6n8iKzsvOxibC//Yfs9Na8r2Rlz02vXXDT57FP/zJi66/EJSmsJKa8QxnoqW3VLQ+jZVUtJwJ8PNX1NQCwfNgdhhHD9on7PdRdrdGPF28rJr1F+3LBdeyv+8yYfLoMYet1vX4upNAjVvwOUWnlNXJXlkzk5Il6kqeoiL0C07qno+/CYBXq/+utlnsz7/Mzvy0tmI4zm4ag23PRN3t/CWryoUVJGm+5+K8RJ0V8Hc88/XHUX/HfiAq7t+BH+x6v8t438enWmdJwFA6ZINriLGKv/95f8lT9/FnyA1NMVEvQyaXuu+gz36f/DD73E4pwqpLcvm/o0Vle78n//+L/NPvoefp1pTJye6e4A/D082FERa5/opeH9zpvh13cNm19/4v/LDe5xMWTi8I0Ta0qKlK27AS/v3/r+/x/2GO9K2c7kVMonDpq7//jc5PKCxeNPpFVzaRr01wF8C4Pu76hXuX18H4LduTr79guuFD3n5BHfI+ZRFhY8w29TYhbbLi/bvBdqKE4fUgg1pBKnV3FEaCWOWyA+m3WpORZr/j+9TKJtW8yBTF2/ZEODI9/QavHkVdGFp/Pjn4Q+u5hXapsP5sOH+OXXA1LiKuqJxiMNbhTkbdJTCy4llEt6NnqRT4dhg1V3nbdrm6dYMecA1yTOL4PWTE9L5VzPFlLBCvlG58AhehnN4uHsAYinyJ+AZ/NkVvELbfOBUuOO5syBIEtiqHU1k9XeISX5bsimrkUUhnGDxourN8SgUsCZVtKyGbyGzHXdjOhsAvOAswSRyIBddRdEZWP6GZhNK/yjwew9ehBo+3jEADu7Ay2n8mDc+TS7awUHg0OMzR0LABhqLD4hJEh/BEGyBdGlSJoXYXtr+3HS4ijzVpgi0paWXtdruGTknXBz+11qT1Q2inxaTzQCO46P3lfLpyS4fou2PH/PupwZgCxNhGlj4IvUuWEsTkqMWm6i4xCSMc9N1RDQoCVcuGItJ/MRWefais+3synowi/dESgJjkilnWnBTGvRWmaw8oR15257t7CHmCf8HOn7cwI8+NQBXMBEmAa8PMRemrNCEhLGEhDQKcGZWS319BX9PFBEwGTbRBhLbDcaV3drFcDqk5kCTd2JF1Wp0HraqBx8U0wwBTnbpCadwBA/gTH/CDrcCs93LV8E0YlmmcyQRQnjBa8JESmGUfIjK/7fkaDJpmD2QptFNVJU1bbtIAjjWQizepOKptRjbzR9Kag6xZmMLLjHOtcLT3Tx9o/0EcTT1XN3E45u24AiwEypDJXihKjQxjLprEwcmRKclaDNZCVqr/V8mYWyFADbusiY5hvgFoU2vio49RgJLn5OsReRFN6tabeetiiy0V7KFHT3HyZLx491u95sn4K1QQSPKM9hNT0wMVvAWbzDSVdrKw4zRjZMyJIHkfq1VAVCDl/bUhNKlGq0zGr05+YAceXVPCttVk0oqjVwMPt+BBefx4yPtGVkUsqY3CHDPiCM5ngupUwCdbkpd8kbPrCWHhkmtIKLEetF2499eS1jZlIPGYnlcPXeM2KD9vLS0bW3ktYNqUllpKLn5ZrsxlIzxvDu5eHxzGLctkZLEY4PgSOg2IUVVcUONzUDBEpRaMoXNmUc0tFZrTZquiLyKxrSm3DvIW9Fil+AkhXu5PhEPx9mUNwqypDvZWdKlhIJQY7vn2OsnmBeOWnYZ0m1iwbbw1U60by5om47iHRV6fOgzjMf/DAZrlP40Z7syxpLK0lJ0gqaAK1c2KQKu7tabTXkLFz0sCftuwX++MyNeNn68k5Buq23YQhUh0SNTJa1ioQ0p4nUG2y0XilF1JqODqdImloPS4Bp111DEWT0jJjVv95uX9BBV7eB3bUWcu0acSVM23YZdd8R8UbQUxJ9wdu3oMuhdt929ME+mh6JXJ8di2RxbTi6TbrDquqV4aUKR2iwT6aZbyOwEXN3DUsWr8Hn4EhwNyHuXHh7/pdaUjtR7vnDh/d8c9xD/s5f501eQ1+CuDiCvGhk1AN/4Tf74RfxPwD3toLarR0zNtsnPzmS64KIRk861dMWCU8ArasG9T9H0ZBpsDGnjtAOM2+/LuIb2iIUGXNgl5ZmKD/Tw8TlaAuihaFP5yrw18v4x1898zIdP+DDAX1bM3GAMvPgRP/cJn3zCW013nrhHkrITyvYuwOUkcHuKlRSW5C6rzIdY4ppnF7J8aAJbQepgbJYBjCY9usGXDKQxq7RZfh9eg5d1UHMVATRaD/4BHK93/1iAgYZ/+jqPn8Dn4UExmWrpa3+ZOK6MvM3bjwfzxNWA2dhs8+51XHSPJiaAhGSpWevEs5xHLXcEGFXYiCONySH3fPWq93JIsBiSWvWyc3CAN+EcXoT7rCSANloPPoa31rt/5PUA/gp8Q/jDD3hyrjzlR8VkanfOvB1XPubt17vzxAfdSVbD1pzAnfgyF3ycadOTOTXhpEUoLC1HZyNGW3dtmjeXgr2r56JNmRwdNNWaQVBddd6rh4MhviEB9EFRD/7RGvePvCbwAL4Mx/D6M541hHO4D3e7g6PafdcZVw689z7NGTwo5om7A8sPhccT6qKcl9NJl9aM/9kX+e59Hh1yPqGuCCZxuITcsmNaJ5F7d0q6J3H48TO1/+M57085q2icdu2U+W36Ldllz9Agiv4YGljoEN908EzvDOrBF98/vtJwCC/BF2AG75xxEmjmMIcjxbjoaxqOK3/4hPOZzhMPBpYPG44CM0dTVm1LjLtUWWVz1Bcf8tEx0zs8O2A2YVHRxKYOiy/aOVoAaMu0i7ubu43njjmd4ibMHU1sIDHaQNKrZND/FZYdk54oCXetjq7E7IVl9eAL7t+oHnwXXtLx44czzoRFHBztYVwtH1d+NOMkupZ5MTM+gUmq90X+Bh9zjRlmaQ+m7YMqUL/veemcecAtOJ0yq1JnVlN27di2E0+Klp1tAJ4KRw1eMI7aJjsO3R8kPSI3fUFXnIOfdQe86sIIVtWDL7h//Ok6vj8vwDk08NEcI8zz7OhBy+WwalzZeZ4+0XniRfst9pAJqQHDGLzVQ2pheZnnv1OWhwO43/AgcvAEXEVVpa4db9sGvNK8wjaENHkfFQ4Ci5i7dqnQlPoLQrHXZDvO3BIXZbJOBrOaEbML6sFL798I4FhKihjHMsPjBUZYCMFr6nvaArxqXPn4lCa+cHfSa2cP27g3Z3ziYTRrcbQNGLQmGF3F3cBdzzzX7AILx0IB9rbwn9kx2G1FW3Inic+ZLIsVvKR8Zwfj0l1fkqo8LWY1M3IX14OX3r9RKTIO+d9XzAI8qRPGPn/4NC2n6o4rN8XJ82TOIvuVA8zLKUHRFgBCetlDZlqR1gLKjS39xoE7Bt8UvA6BxuEDjU3tFsEijgA+615tmZkXKqiEENrh41iLDDZNq4pKTWR3LZfnos81LOuNa15cD956vLMsJd1rqYp51gDUQqMYm2XsxnUhD2jg1DM7SeuJxxgrmpfISSXVIJIS5qJJSvJPEQ49DQTVIbYWJ9QWa/E2+c/oPK1drmC7WSfJRNKBO5Yjvcp7Gc3dmmI/Xh1kDTEuiSnWqQf37h+fTMhGnDf6dsS8SQfQWlqqwXXGlc/PEZ/SC5mtzIV0nAshlQdM/LvUtYutrEZ/Y+EAFtq1k28zQhOwLr1AIeANzhF8t9qzTdZf2qRKO6MWE9ohBYwibbOmrFtNmg3mcS+tB28xv2uKd/agYCvOP+GkSc+0lr7RXzyufL7QbkUpjLjEWFLqOIkAGu2B0tNlO9Eau2W1qcOUvVRgKzypKIQZ5KI3q0MLzqTNRYqiZOqmtqloIRlmkBHVpHmRYV6/HixbO6UC47KOFJnoMrVyr7wYz+SlW6GUaghYbY1I6kkxA2W1fSJokUdSh2LQ1GAimRGm0MT+uu57H5l7QgOWxERpO9moLRPgTtquWCfFlGlIjQaRly9odmzMOWY+IBO5tB4sW/0+VWGUh32qYk79EidWKrjWuiLpiVNGFWFRJVktyeXWmbgBBzVl8anPuXyNJlBJOlKLTgAbi/EYHVHxWiDaVR06GnHQNpJcWcK2jJtiCfG2sEHLzuI66sGrMK47nPIInPnu799935aOK2cvmvubrE38ZzZjrELCmXM2hM7UcpXD2oC3+ECVp7xtIuxptJ0jUr3sBmBS47TVxlvJ1Sqb/E0uLdvLj0lLr29ypdd/eMX3f6lrxGlKwKQxEGvw0qHbkbwrF3uHKwVENbIV2wZ13kNEF6zD+x24aLNMfDTCbDPnEikZFyTNttxWBXDaBuM8KtI2rmaMdUY7cXcUPstqTGvBGSrFWIpNMfbdea990bvAOC1YX0qbc6smDS1mPxSJoW4fwEXvjMmhlijDRq6qale6aJEuFGoppYDoBELQzLBuh/mZNx7jkinv0EtnUp50lO9hbNK57lZaMAWuWR5Yo9/kYwcYI0t4gWM47Umnl3YmpeBPqSyNp3K7s2DSAS/39KRuEN2bS4xvowV3dFRMx/VFcp2Yp8w2nTO9hCXtHG1kF1L4KlrJr2wKfyq77R7MKpFKzWlY9UkhYxyHWW6nBWPaudvEAl3CGcNpSXPZ6R9BbBtIl6cHL3gIBi+42CYXqCx1gfGWe7Ap0h3luyXdt1MKy4YUT9xSF01G16YEdWsouW9mgDHd3veyA97H+Ya47ZmEbqMY72oPztCGvK0onL44AvgC49saZKkWRz4veWljE1FHjbRJaWv6ZKKtl875h4CziFCZhG5rx7tefsl0aRT1bMHZjm8dwL/6u7wCRysaQblQoG5yAQN5zpatMNY/+yf8z+GLcH/Qn0iX2W2oEfXP4GvwQHuIL9AYGnaO3zqAX6946nkgqZNnUhx43DIdQtMFeOPrgy/y3Yd85HlJWwjLFkU3kFwq28xPnuPhMWeS+tDLV9Otllq7pQCf3uXJDN9wFDiUTgefHaiYbdfi3b3u8+iY6TnzhgehI1LTe8lcd7s1wJSzKbahCRxKKztTLXstGAiu3a6rPuQs5pk9TWAan5f0BZmGf7Ylxzzk/A7PAs4QPPPAHeFQ2hbFHszlgZuKZsJcUmbDC40sEU403cEjczstOEypa+YxevL4QBC8oRYqWdK6b7sK25tfE+oDZgtOQ2Jg8T41HGcBE6fTWHn4JtHcu9S7uYgU5KSCkl/mcnq+5/YBXOEr6lCUCwOTOM1taOI8mSxx1NsCXBEmLKbMAg5MkwbLmpBaFOPrNSlO2HnLiEqW3tHEwd8AeiQLmn+2gxjC3k6AxREqvKcJbTEzlpLiw4rNZK6oJdidbMMGX9FULKr0AkW+2qDEPBNNm5QAt2Ik2nftNWHetubosHLo2nG4vQA7GkcVCgVCgaDixHqo9UUn1A6OshapaNR/LPRYFV8siT1cCtJE0k/3WtaNSuUZYKPnsVIW0xXWnMUxq5+En4Kvw/MqQmVXnAXj9Z+9zM98zM/Agy7F/qqj2Nh67b8HjFnPP3iBn/tkpdzwEJX/whIcQUXOaikeliCRGUk7tiwF0rItwMEhjkZ309hikFoRAmLTpEXWuHS6y+am/KB/fM50aLEhGnSMwkpxzOov4H0AvgovwJ1iGzDLtJn/9BU+fAINfwUe6FHSLhu83viV/+/HrOePX+STT2B9uWGbrMHHLldRBlhS/CJQmcRxJFqZica01XixAZsYiH1uolZxLrR/SgxVIJjkpQP4PE9sE59LKLr7kltSBogS5tyszzH8Fvw8/AS8rNOg0xUS9fIaHwb+6et8Q/gyvKRjf5OusOzGx8evA/BP4IP11uN/grca5O0lcsPLJ5YjwI4QkJBOHa0WdMZYGxPbh2W2nR9v3WxEWqgp/G3+6VZbRLSAAZ3BhdhAaUL33VUSw9yjEsvbaQ9u4A/gGXwZXoEHOuU1GSj2chf+Mo+f8IcfcAxfIKVmyunRbYQVnoevwgfw3TXXcw++xNuP4fhyueEUNttEduRVaDttddoP0eSxLe2LENk6itYxlrxBNBYrNNKSQmeaLcm9c8UsaB5WyO6675yyQIAWSDpBVoA/gxmcwEvwoDv0m58UE7gHn+fJOa8/Ywan8EKRfjsopF83eCglX/Sfr7OeaRoQfvt1CGvIDccH5BCvw1sWIzRGC/66t0VTcLZQZtm6PlAasbOJ9iwWtUo7biktTSIPxnR24jxP1ZKaqq+2RcXM9OrBAm/AAs7hDJ5bNmGb+KIfwCs8a3jnjBrOFeMjHSCdbKr+2uOLfnOd9eiA8Hvvwwq54VbP2OqwkB48Ytc4YEOiH2vTXqodabfWEOzso4qxdbqD5L6tbtNPECqbhnA708DZH4QOJUXqScmUlks7Ot6FBuZw3n2mEbaUX7kDzxHOOQk8nKWMzAzu6ZZ8sOFw4RK+6PcuXo9tB4SbMz58ApfKDXf3szjNIIbGpD5TKTRxGkEMLjLl+K3wlWXBsCUxIDU+jbOiysESqAy1MGUJpXgwbTWzNOVEziIXZrJ+VIztl1PUBxTSo0dwn2bOmfDRPD3TRTGlfbCJvO9KvuhL1hMHhB9wPuPRLGHcdOWG2xc0U+5bQtAJT0nRTewXL1pgk2+rZAdeWmz3jxAqfNQQdzTlbF8uJ5ecEIWvTkevAHpwz7w78QujlD/Lr491bD8/1vhM2yrUQRrWXNQY4fGilfctMWYjL72UL/qS9eiA8EmN88nbNdour+PBbbAjOjIa4iBhfFg6rxeKdEGcL6p3EWR1Qq2Qkhs2DrnkRnmN9tG2EAqmgPw6hoL7Oza7B+3SCrR9tRftko+Lsf2F/mkTndN2LmzuMcKTuj/mX2+4Va3ki16+nnJY+S7MefpkidxwnV+4wkXH8TKnX0tsYzYp29DOOoSW1nf7nTh2akYiWmcJOuTidSaqESrTYpwjJJNVGQr+rLI7WsqerHW6Kp/oM2pKuV7T1QY9gjqlZp41/WfKpl56FV/0kvXQFRyeQ83xaTu5E8p5dNP3dUF34ihyI3GSpeCsywSh22ZJdWto9winhqifb7VRvgktxp13vyjrS0EjvrRfZ62uyqddSWaWYlwTPAtJZ2oZ3j/Sgi/mi+6vpzesfAcWNA0n8xVyw90GVFGuZjTXEQy+6GfLGLMLL523f5E0OmxVjDoOuRiH91RKU+vtoCtH7TgmvBLvtFXWLW15H9GTdVw8ow4IlRLeHECN9ym1e9K0I+Cbnhgv4Yu+aD2HaQJ80XDqOzSGAV4+4yCqBxrsJAX6ZTIoX36QnvzhhzzMfFW2dZVLOJfo0zbce5OvwXMFaZ81mOnlTVXpDZsQNuoYWveketKb5+6JOOsgX+NTm7H49fUTlx+WLuWL7qxnOFh4BxpmJx0p2gDzA/BUARuS6phR+pUsY7MMboAHx5xNsSVfVZcYSwqCKrqon7zM+8ecCkeS4nm3rINuaWvVNnMRI1IRpxTqx8PZUZ0Br/UEduo3B3hNvmgZfs9gQPj8vIOxd2kndir3awvJ6BLvoUuOfFWNYB0LR1OQJoUySKb9IlOBx74q1+ADC2G6rOdmFdJcD8BkfualA+BdjOOzP9uUhGUEX/TwhZsUduwRr8wNuXKurCixLBgpQI0mDbJr9dIqUuV+92ngkJZ7xduCk2yZKbfWrH1VBiTg9VdzsgRjW3CVXCvAwDd+c1z9dWw9+B+8MJL/eY15ZQ/HqvTwVdsZn5WQsgRRnMaWaecu3jFvMBEmgg+FJFZsnSl0zjB9OqPYaBD7qmoVyImFvzi41usesV0julaAR9dfR15Xzv9sEruRDyk1nb+QaLU67T885GTls6YgcY+UiMa25M/pwGrbCfzkvR3e0jjtuaFtnwuagHTSb5y7boBH119HXhvwP487jJLsLJ4XnUkHX5sLbS61dpiAXRoZSCrFJ+EjpeU3puVfitngYNo6PJrAigKktmwjyQdZpfq30mmtulaAx9Zfx15Xzv+cyeuiBFUs9zq8Kq+XB9a4PVvph3GV4E3y8HENJrN55H1X2p8VyqSKwVusJDKzXOZzplWdzBUFK9e+B4+uv468xvI/b5xtSAkBHQaPvtqWzllVvEOxPbuiE6+j2pvjcKsbvI7txnRErgfH7LdXqjq0IokKzga14GzQ23SSbCQvO6r+Or7SMIr/efOkkqSdMnj9mBx2DRsiY29Uj6+qK9ZrssCKaptR6HKURdwUYeUWA2kPzVKQO8ku2nU3Anhs/XWkBx3F/7wJtCTTTIKftthue1ty9xvNYLY/zo5KSbIuKbXpbEdSyeRyYdAIwKY2neyoc3+k1XUaufYga3T9daMUx/r8z1s10ITknIO0kuoMt+TB8jK0lpayqqjsJ2qtXAYwBU932zinimgmd6mTRDnQfr88q36NAI+tv24E8Pr8zxtasBqx0+xHH9HhlrwsxxNUfKOHQaZBITNf0uccj8GXiVmXAuPEAKSdN/4GLHhs/XWj92dN/uetNuBMnVR+XWDc25JLjo5Mg5IZIq226tmCsip2zZliL213YrTlL2hcFjpCduyim3M7/eB16q/blQsv5X/esDRbtJeabLIosWy3ycavwLhtxdWzbMmHiBTiVjJo6lCLjXZsi7p9PEPnsq6X6wd4bP11i0rD5fzPm/0A6brrIsllenZs0lCJlU4abakR59enZKrKe3BZihbTxlyZ2zl1+g0wvgmA166/bhwDrcn/7Ddz0eWZuJvfSESug6NzZsox3Z04FIxz0mUjMwVOOVTq1CQ0AhdbBGVdjG/CgsfUX7esJl3K/7ytWHRv683praW/8iDOCqWLLhpljDY1ZpzK75QiaZoOTpLKl60auHS/97oBXrv+umU9+FL+5+NtLFgjqVLCdbmj7pY5zPCPLOHNCwXGOcLquOhi8CmCWvbcuO73XmMUPab+ug3A6/A/78Bwe0bcS2+tgHn4J5pyS2WbOck0F51Vq3LcjhLvZ67p1ABbaL2H67bg78BfjKi/jr3+T/ABV3ilLmNXTI2SpvxWBtt6/Z//D0z/FXaGbSBgylzlsEGp+5//xrd4/ae4d8DUUjlslfIYS3t06HZpvfQtvv0N7AHWqtjP2pW08QD/FLy//da38vo8PNlKHf5y37Dxdfe/oj4kVIgFq3koLReSR76W/bx//n9k8jonZxzWTANVwEniDsg87sOSd/z7//PvMp3jQiptGVWFX2caezzAXwfgtzYUvbr0iozs32c3Uge7varH+CNE6cvEYmzbPZ9hMaYDdjK4V2iecf6EcEbdUDVUARda2KzO/JtCuDbNQB/iTeL0EG1JSO1jbXS+nLxtPMDPw1fh5+EPrgSEKE/8Gry5A73ui87AmxwdatyMEBCPNOCSKUeRZ2P6Myb5MRvgCHmA9ywsMifU+AYXcB6Xa5GibUC5TSyerxyh0j6QgLVpdyhfArRTTLqQjwe4HOD9s92D4Ap54odXAPBWLAwB02igG5Kkc+piN4lvODIFGAZgT+EO4Si1s7fjSR7vcQETUkRm9O+MXyo9OYhfe4xt9STQ2pcZRLayCV90b4D3jR0DYAfyxJ+eywg2IL7NTMXna7S/RpQ63JhWEM8U41ZyQGjwsVS0QBrEKLu8xwZsbi4wLcCT+OGidPIOCe1PiSc9Qt+go+vYqB7cG+B9d8cAD+WJPz0Am2gxXgU9IneOqDpAAXOsOltVuMzpdakJXrdPCzXiNVUpCeOos5cxnpQT39G+XVLhs1osQVvJKPZyNq8HDwd4d7pNDuWJPxVX7MSzqUDU6gfadKiNlUFTzLeFHHDlzO4kpa7aiKhBPGKwOqxsBAmYkOIpipyXcQSPlRTf+Tii0U3EJGaZsDER2qoB3h2hu0qe+NNwUooYU8y5mILbJe6OuX+2FTKy7bieTDAemaQyQ0CPthljSWO+xmFDIYiESjM5xKd6Ik5lvLq5GrQ3aCMLvmCA9wowLuWJb9xF59hVVP6O0CrBi3ZjZSNOvRy+I6klNVRJYRBaEzdN+imiUXQ8iVF8fsp+W4JXw7WISW7fDh7lptWkCwZ4d7QTXyBPfJMYK7SijjFppGnlIVJBJBYj7eUwtiP1IBXGI1XCsjNpbjENVpSAJ2hq2LTywEly3hUYazt31J8w2+aiLx3g3fohXixPfOMYm6zCGs9LVo9MoW3MCJE7R5u/WsOIjrqBoHUO0bJE9vxBpbhsd3+Nb4/vtPCZ4oZYCitNeYuC/8UDvDvy0qvkiW/cgqNqRyzqSZa/s0mqNGjtKOoTm14zZpUauiQgVfqtQiZjq7Q27JNaSK5ExRcrGCXO1FJYh6jR6CFqK7bZdQZ4t8g0rSlPfP1RdBtqaa9diqtzJkQ9duSryi2brQXbxDwbRUpFMBHjRj8+Nt7GDKgvph9okW7LX47gu0SpGnnFQ1S1lYldOsC7hYteR574ZuKs7Ei1lBsfdz7IZoxzzCVmmVqaSySzQbBVAWDek+N4jh9E/4VqZrJjPwiv9BC1XcvOWgO8275CVyBPvAtTVlDJfZkaZGU7NpqBogAj/xEHkeAuJihWYCxGN6e8+9JtSegFXF1TrhhLGP1fak3pebgPz192/8gB4d/6WT7+GdYnpH7hH/DJzzFiYPn/vjW0SgNpTNuPIZoAEZv8tlGw4+RLxy+ZjnKa5NdFoC7UaW0aduoYse6+bXg1DLg6UfRYwmhGEjqPvF75U558SANrElK/+MdpXvmqBpaXOa/MTZaa1DOcSiLaw9j0NNNst3c+63c7EKTpkvKHzu6bPbP0RkuHAVcbRY8ijP46MIbQeeT1mhA+5PV/inyDdQipf8LTvMXbwvoDy7IruDNVZKTfV4CTSRUYdybUCnGU7KUTDxLgCknqUm5aAW6/1p6eMsOYsphLzsHrE0Y/P5bQedx1F/4yPHnMB3/IOoTU9+BL8PhtjuFKBpZXnYNJxTuv+2XqolKR2UQgHhS5novuxVySJhBNRF3SoKK1XZbbXjVwWNyOjlqWJjrWJIy+P5bQedyldNScP+HZ61xKSK3jyrz+NiHG1hcOLL/+P+PDF2gOkekKGiNWKgJ+8Z/x8Iv4DdQHzcpZyF4v19I27w9/yPGDFQvmEpKtqv/TLiWMfn4sofMm9eAH8Ao0zzh7h4sJqYtxZd5/D7hkYPneDzl5idlzNHcIB0jVlQ+8ULzw/nc5/ojzl2juE0apD7LRnJxe04dMz2iOCFNtGFpTuXA5AhcTRo8mdN4kz30nVjEC4YTZQy4gpC7GlTlrePKhGsKKgeXpCYeO0MAd/GH7yKQUlXPLOasOH3FnSphjHuDvEu4gB8g66oNbtr6eMbFIA4fIBJkgayoXriw2XEDQPJrQeROAlY6aeYOcMf+IVYTU3XFlZufMHinGywaW3YLpObVBAsbjF4QJMsVUSayjk4voPsHJOQfPWDhCgDnmDl6XIRerD24HsGtw86RMHOLvVSHrKBdeVE26gKB5NKHzaIwLOmrqBWJYZDLhASG16c0Tn+CdRhWDgWXnqRZUTnPIHuMJTfLVpkoYy5CzylHVTGZMTwkGAo2HBlkQplrJX6U+uF1wZz2uwS1SQ12IqWaPuO4baZaEFBdukksJmkcTOm+YJSvoqPFzxFA/YUhIvWxcmSdPWTWwbAKVp6rxTtPFUZfKIwpzm4IoMfaYQLWgmlG5FME2gdBgm+J7J+rtS/XBbaVLsR7bpPQnpMFlo2doWaVceHk9+MkyguZNCJ1He+kuHTWyQAzNM5YSUg/GlTk9ZunAsg1qELVOhUSAK0LABIJHLKbqaEbHZLL1VA3VgqoiOKXYiS+HRyaEKgsfIqX64HYWbLRXy/qWoylIV9gudL1OWBNgBgTNmxA6b4txDT4gi3Ri7xFSLxtXpmmYnzAcWDZgY8d503LFogz5sbonDgkKcxGsWsE1OI+rcQtlgBBCSOKD1mtqYpIU8cTvBmAT0yZe+zUzeY92fYjTtGipXLhuR0ePoHk0ofNWBX+lo8Z7pAZDk8mEw5L7dVyZZoE/pTewbI6SNbiAL5xeygW4xPRuLCGbhcO4RIeTMFYHEJkYyEO9HmJfXMDEj/LaH781wHHZEtqSQ/69UnGpzH7LKIAZEDSPJnTesJTUa+rwTepI9dLJEawYV+ZkRn9g+QirD8vF8Mq0jFQ29js6kCS3E1+jZIhgPNanHdHFqFvPJLHqFwQqbIA4jhDxcNsOCCQLDomaL/dr5lyJaJU6FxPFjO3JOh3kVMcROo8u+C+jo05GjMF3P3/FuDLn5x2M04xXULPwaS6hBYki+MrMdZJSgPHlcB7nCR5bJ9Kr5ACUn9jk5kivdd8tk95SOGrtqu9lr2IhK65ZtEl7ZKrp7DrqwZfRUSN1el7+7NJxZbywOC8neNKTch5vsTEMNsoCCqHBCqIPRjIPkm0BjvFODGtto99rCl+d3wmHkW0FPdpZtC7MMcVtGFQjJLX5bdQ2+x9ypdc313uj8xlsrfuLgWXz1cRhZvJYX0iNVBRcVcmCXZs6aEf3RQF2WI/TcCbKmGU3IOoDJGDdDub0+hYckt6PlGu2BcxmhbTdj/klhccLGJMcqRjMJP1jW2ETqLSWJ/29MAoORluJ+6LPffBZbi5gqi5h6catQpmOT7/OFf5UorRpLzCqcMltBLhwd1are3kztrSzXO0LUbXRQcdLh/RdSZ+swRm819REDrtqzC4es6Gw4JCKlSnjYVpo0xeq33PrADbFLL3RuCmObVmPN+24kfa+AojDuM4umKe2QwCf6EN906HwjujaitDs5o0s1y+k3lgbT2W2i7FJdnwbLXhJUBq/9liTctSmFC/0OqUinb0QddTWamtjbHRFuWJJ6NpqZ8vO3fZJ37Db+2GkaPYLGHs7XTTdiFQJ68SkVJFVmY6McR5UycflNCsccHFaV9FNbR4NttLxw4pQ7wJd066Z0ohVbzihaxHVExd/ay04oxUKWt+AsdiQ9OUyZ2krzN19IZIwafSTFgIBnMV73ADj7V/K8u1MaY2sJp2HWm0f41tqwajEvdHWOJs510MaAqN4aoSiPCXtN2KSi46dUxHdaMquar82O1x5jqhDGvqmoE9LfxcY3zqA7/x3HA67r9ZG4O6Cuxu12/+TP+eLP+I+HErqDDCDVmBDO4larujNe7x8om2rMug0MX0rL1+IWwdwfR+p1TNTyNmVJ85ljWzbWuGv8/C7HD/izjkHNZNYlhZcUOKVzKFUxsxxN/kax+8zPWPSFKw80rJr9Tizyj3o1gEsdwgWGoxPezDdZ1TSENE1dLdNvuKL+I84nxKesZgxXVA1VA1OcL49dFlpFV5yJMhzyCmNQ+a4BqusPJ2bB+xo8V9u3x48VVIEPS/mc3DvAbXyoYr6VgDfh5do5hhHOCXMqBZUPhWYbWZECwVJljLgMUWOCB4MUuMaxGNUQDVI50TQ+S3kFgIcu2qKkNSHVoM0SHsgoZxP2d5HH8B9woOk4x5bPkKtAHucZsdykjxuIpbUrSILgrT8G7G5oCW+K0990o7E3T6AdW4TilH5kDjds+H64kS0mz24grtwlzDHBJqI8YJQExotPvoC4JBq0lEjjQkyBZ8oH2LnRsQ4Hu1QsgDTJbO8fQDnllitkxuVskoiKbRF9VwzMDvxHAdwB7mD9yCplhHFEyUWHx3WtwCbSMMTCUCcEmSGlg4gTXkHpZXWQ7kpznK3EmCHiXInqndkQjunG5kxTKEeGye7jWz9cyMR2mGiFQ15ENRBTbCp+Gh86vAyASdgmJq2MC6hoADQ3GosP0QHbnMHjyBQvQqfhy/BUbeHd5WY/G/9LK/8Ka8Jd7UFeNWEZvzPb458Dn8DGLOe3/wGL/4xP+HXlRt+M1PE2iLhR8t+lfgxsuh7AfO2AOf+owWhSZRYQbd622hbpKWKuU+XuvNzP0OseRDa+mObgDHJUSc/pKx31QdKffQ5OIJpt8GWjlgTwMc/w5MPCR/yl1XC2a2Yut54SvOtMev55Of45BOat9aWG27p2ZVORRvnEk1hqWMVUmqa7S2YtvlIpspuF1pt0syuZS2NV14mUidCSfzQzg+KqvIYCMljIx2YK2AO34fX4GWdu5xcIAb8MzTw+j/lyWM+Dw/gjs4GD6ehNgA48kX/AI7XXM/XAN4WHr+9ntywqoCakCqmKP0rmQrJJEErG2Upg1JObr01lKQy4jskWalKYfJ/EDLMpjNSHFEUAde2fltaDgmrNaWQ9+AAb8I5vKjz3L1n1LriB/BXkG/wwR9y/oRX4LlioHA4LzP2inzRx/DWmutRweFjeP3tNeSGlaE1Fde0OS11yOpmbIp2u/jF1n2RRZviJM0yBT3IZl2HWImKjQOxIyeU325b/qWyU9Moj1o07tS0G7qJDoGHg5m8yeCxMoEH8GU45tnrNM84D2l297DQ9t1YP7jki/7RmutRweEA77/HWXOh3HCxkRgldDQkAjNTMl2Iloc1qN5JfJeeTlyTRzxURTdn1Ixv2uKjs12AbdEWlBtmVdk2k7FFwj07PCZ9XAwW3dG+8xKzNFr4EnwBZpy9Qzhh3jDXebBpYcpuo4fQ44u+fD1dweEnHzI7v0xuuOALRUV8rXpFyfSTQYkhd7IHm07jpyhlkCmI0ALYqPTpUxXS+z4jgDj1Pflvmz5ecuItpIBxyTHpSTGWd9g1ApfD/bvwUhL4nT1EzqgX7cxfCcNmb3mPL/qi9SwTHJ49oj5ZLjccbTG3pRmlYi6JCG0mQrAt1+i2UXTZ2dv9IlQpN5naMYtviaXlTrFpoMsl3bOAFEa8sqPj2WCMrx3Yjx99qFwO59Aw/wgx+HlqNz8oZvA3exRDvuhL1jMQHPaOJ0+XyA3fp1OfM3qObEVdhxjvynxNMXQV4+GJyvOEFqeQBaIbbO7i63rpxCltdZShPFxkjM2FPVkn3TG+Rp9pO3l2RzFegGfxGDHIAh8SteR0C4HopXzRF61nheDw6TFN05Ebvq8M3VKKpGjjO6r7nhudTEGMtYM92HTDaR1FDMXJ1eThsbKfywyoWwrzRSXkc51flG3vIid62h29bIcFbTGhfV+faaB+ohj7dPN0C2e2lC96+XouFByen9AsunLDJZ9z7NExiUc0OuoYW6UZkIyx2YUR2z6/TiRjyKMx5GbbjLHvHuf7YmtKghf34LJfx63Yg8vrvN2zC7lY0x0tvKezo4HmGYDU+Gab6dFL+KI761lDcNifcjLrrr9LWZJctG1FfU1uwhoQE22ObjdfkSzY63CbU5hzs21WeTddH2BaL11Gi7lVdlxP1nkxqhnKhVY6knS3EPgVGg1JpN5cP/hivujOelhXcPj8HC/LyI6MkteVjlolBdMmF3a3DbsuAYhL44dxzthWSN065xxUd55Lmf0wRbOYOqH09/o9WbO2VtFdaMb4qBgtFJoT1SqoN8wPXMoXLb3p1PUEhxfnnLzGzBI0Ku7FxrKsNJj/8bn/H8fPIVOd3rfrklUB/DOeO+nkghgSPzrlPxluCMtOnDL4Yml6dK1r3vsgMxgtPOrMFUZbEUbTdIzii5beq72G4PD0DKnwjmBULUVFmy8t+k7fZ3pKc0Q4UC6jpVRqS9Umv8bxw35flZVOU1X7qkjnhZlsMbk24qQ6Hz7QcuL6sDC0iHHki96Uh2UdvmgZnjIvExy2TeJdMDZNSbdZyAHe/Yd1xsQhHiKzjh7GxQ4yqMPaywPkjMamvqrYpmO7Knad+ZQC5msCuAPWUoxrxVhrGv7a+KLXFhyONdTMrZ7ke23qiO40ZJUyzgYyX5XyL0mV7NiUzEs9mjtbMN0dERqwyAJpigad0B3/zRV7s4PIfXSu6YV/MK7+OrYe/JvfGMn/PHJe2fyUdtnFrKRNpXV0Y2559aWPt/G4BlvjTMtXlVIWCnNyA3YQBDmYIodFz41PvXPSa6rq9lWZawZ4dP115HXV/M/tnFkkrBOdzg6aP4pID+MZnTJ1SuuB6iZlyiox4HT2y3YBtkUKWooacBQUDTpjwaDt5poBHl1/HXltwP887lKKXxNUEyPqpGTyA699UqY/lt9yGdlUKra0fFWS+36iylVWrAyd7Uw0CZM0z7xKTOduznLIjG2Hx8cDPLb+OvK6Bv7n1DYci4CxUuRxrjBc0bb4vD3rN5Zz36ntLb83eVJIB8LiIzCmn6SMPjlX+yNlTjvIGjs+QzHPf60Aj62/jrzG8j9vYMFtm1VoRWCJdmw7z9N0t+c8cxZpPeK4aTRicS25QhrVtUp7U578chk4q04Wx4YoQSjFryUlpcQ1AbxZ/XVMknIU//OGl7Q6z9Zpxi0+3yFhSkjUDpnCIUhLWVX23KQ+L9vKvFKI0ZWFQgkDLvBoylrHNVmaw10zwCPrr5tlodfnf94EWnQ0lFRWy8pW9LbkLsyUVDc2NSTHGDtnD1uMtchjbCeb1mpxFP0YbcClhzdLu6lfO8Bj6q+bdT2sz/+8SZCV7VIxtt0DUn9L7r4cLYWDSXnseEpOGFuty0qbOVlS7NNzs5FOGJUqQpl2Q64/yBpZf90sxbE+//PGdZ02HSipCbmD6NItmQ4Lk5XUrGpDMkhbMm2ZVheNYV+VbUWTcv99+2NyX1VoafSuC+AN6q9bFIMv5X/eagNWXZxEa9JjlMwNWb00akGUkSoepp1/yRuuqHGbUn3UdBSTxBU6SEVklzWRUkPndVvw2PrrpjvxOvzPmwHc0hpmq82npi7GRro8dXp0KXnUQmhZbRL7NEVp1uuZmO45vuzKsHrktS3GLWXODVjw+vXXLYx4Hf7njRPd0i3aoAGX6W29GnaV5YdyDj9TFkakje7GHYzDoObfddHtOSpoi2SmzJHrB3hM/XUDDEbxP2/oosszcRlehWXUvzHv4TpBVktHqwenFo8uLVmy4DKLa5d3RtLrmrM3aMFr1183E4sewf+85VWeg1c5ag276NZrM9IJVNcmLEvDNaV62aq+14IAOGFsBt973Ra8Xv11YzXwNfmft7Jg2oS+XOyoC8/cwzi66Dhmgk38kUmP1CUiYWOX1bpD2zWXt2FCp7uq8703APAa9dfNdscR/M/bZLIyouVxqJfeWvG9Je+JVckHQ9+CI9NWxz+blX/KYYvO5n2tAP/vrlZ7+8/h9y+9qeB/Hnt967e5mevX10rALDWK//FaAT5MXdBXdP0C/BAes792c40H+AiAp1e1oH8HgH94g/Lttx1gp63op1eyoM/Bvw5/G/7xFbqJPcCXnmBiwDPb/YKO4FX4OjyCb289db2/Noqicw4i7N6TVtoz8tNwDH+8x/i6Ae7lmaQVENzJFb3Di/BFeAwz+Is9SjeQySpPqbLFlNmyz47z5a/AF+AYFvDmHqibSXTEzoT4Gc3OALaqAP4KPFUJ6n+1x+rGAM6Zd78bgJ0a8QN4GU614vxwD9e1Amy6CcskNrczLx1JIp6HE5UZD/DBHrFr2oNlgG4Odv226BodoryjGJ9q2T/AR3vQrsOCS0ctXZi3ruLlhpFDJYl4HmYtjQCP9rhdn4suySLKDt6wLcC52h8xPlcjju1fn+yhuw4LZsAGUuo2b4Fx2UwQu77uqRHXGtg92aN3tQCbFexc0uk93vhTXbct6y7MulLycoUljx8ngDMBg1tvJjAazpEmOtxlzclvj1vQf1Tx7QlPDpGpqgtdSKz/d9/hdy1vTfFHSmC9dGDZbLiezz7Ac801HirGZsWjydfZyPvHXL/Y8Mjzg8BxTZiuwKz4Eb8sBE9zznszmjvFwHKPIWUnwhqfVRcd4Ck0K6ate48m1oOfrX3/yOtvAsJ8zsPAM89sjnddmuLuDPjX9Bu/L7x7xpMzFk6nWtyQfPg278Gn4Aekz2ZgOmU9eJ37R14vwE/BL8G3aibCiWMWWDQ0ZtkPMnlcGeAu/Ag+8ZyecU5BPuy2ILD+sQqyZhAKmn7XZd+jIMTN9eBL7x95xVLSX4On8EcNlXDqmBlqS13jG4LpmGbkF/0CnOi3H8ETOIXzmnmtb0a16Tzxj1sUvQCBiXZGDtmB3KAefPH94xcUa/6vwRn80GOFyjEXFpba4A1e8KQfFF+259tx5XS4egYn8fQsLGrqGrHbztr+uByTahWuL1NUGbDpsnrwBfePPwHHIf9X4RnM4Z2ABWdxUBlqQ2PwhuDxoS0vvqB1JzS0P4h2nA/QgTrsJFn+Y3AOjs9JFC07CGWX1oNX3T/yHOzgDjwPn1PM3g9Jk9lZrMEpxnlPmBbjyo2+KFXRU52TJM/2ALcY57RUzjObbjqxVw++4P6RAOf58pcVsw9Daje3htriYrpDOonre3CudSe6bfkTEgHBHuDiyu5MCsc7BHhYDx7ePxLjqigXZsw+ijMHFhuwBmtoTPtOxOrTvYJDnC75dnUbhfwu/ZW9AgYd+peL68HD+0emKquiXHhWjJg/UrkJYzuiaL3E9aI/ytrCvAd4GcYZMCkSQxfUg3v3j8c4e90j5ZTPdvmJJGHnOCI2nHS8081X013pHuBlV1gB2MX1YNmWLHqqGN/TWmG0y6clJWthxNUl48q38Bi8vtMKyzzpFdSDhxZ5WBA5ZLt8Jv3895DduBlgbPYAj8C4B8hO68FDkoh5lydC4FiWvBOVqjYdqjiLv92t8yPDjrDaiHdUD15qkSURSGmXJwOMSxWAXYwr3zaAufJ66l+94vv3AO+vPcD7aw/w/toDvL/2AO+vPcD7aw/wHuD9tQd4f+0B3l97gPfXHuD9tQd4f+0B3l97gG8LwP8G/AL8O/A5OCq0Ys2KIdv/qOIXG/4mvFAMF16gZD+2Xvu/B8as5+8bfllWyg0zaNO5bfXj6vfhhwD86/Aq3NfRS9t9WPnhfnvCIw/CT8GLcFTMnpntdF/z9V+PWc/vWoIH+FL3Znv57PitcdGP4R/C34avw5fgRVUInCwbsn1yyA8C8zm/BH8NXoXnVE6wVPjdeCI38kX/3+Ct9dbz1pTmHFRu+Hm4O9Ch3clr99negxfwj+ER/DR8EV6B5+DuQOnTgUw5rnkY+FbNU3gNXh0o/JYTuWOvyBf9FvzX663HH/HejO8LwAl8Hl5YLTd8q7sqA3wbjuExfAFegQdwfyDoSkWY8swzEf6o4Qyewefg+cHNbqMQruSL/u/WWc+E5g7vnnEXgDmcDeSGb/F4cBcCgT+GGRzDU3hZYburAt9TEtHgbM6JoxJ+6NMzzTcf6c2bycv2+KK/f+l6LBzw5IwfqZJhA3M472pWT/ajKxnjv4AFnMEpnBTPND6s2J7qHbPAqcMK74T2mZ4VGB9uJA465It+/eL1WKhYOD7xHOkr1ajK7d0C4+ke4Hy9qXZwpgLr+Znm/uNFw8xQOSy8H9IzjUrd9+BIfenYaylf9FsXr8fBAadnPIEDna8IBcwlxnuA0/Wv6GAWPd7dDIKjMdSWueAsBj4M7TOd06qBbwDwKr7oleuxMOEcTuEZTHWvDYUO7aHqAe0Bbq+HEFRzOz7WVoTDQkVds7A4sIIxfCQdCefFRoIOF/NFL1mPab/nvOakSL/Q1aFtNpUb/nFOVX6gzyg/1nISyDfUhsokIzaBR9Kxm80s5mK+6P56il1jXic7nhQxsxSm3OwBHl4fFdLqi64nDQZvqE2at7cWAp/IVvrN6/BFL1mPhYrGMBfOi4PyjuSGf6wBBh7p/FZTghCNWGgMzlBbrNJoPJX2mW5mwZfyRffXo7OFi5pZcS4qZUrlViptrXtw+GQoyhDPS+ANjcGBNRiLCQDPZPMHuiZfdFpPSTcQwwKYdRNqpkjm7AFeeT0pJzALgo7g8YYGrMHS0iocy+YTm2vyRUvvpXCIpQ5pe666TJrcygnScUf/p0NDs/iAI/nqDHC8TmQT8x3NF91l76oDdQGwu61Z6E0ABv7uO1dbf/37Zlv+Zw/Pbh8f1s4Avur6657/+YYBvur6657/+YYBvur6657/+YYBvur6657/+aYBvuL6657/+VMA8FXWX/f8zzcN8BXXX/f8zzcNMFdbf93zP38KLPiK6697/uebtuArrr/u+Z9vGmCusP6653/+1FjwVdZf9/zPN7oHX339dc//fNMu+irrr3v+50+Bi+Zq6697/uebA/jz8Pudf9ht/fWv517J/XUzAP8C/BAeX9WCDrUpZ3/dEMBxgPcfbtTVvsYV5Yn32u03B3Ac4P3b8I+vxNBKeeL9dRMAlwO83959qGO78sT769oB7g3w/vGVYFzKE++v6wV4OMD7F7tckFkmT7y/rhHgpQO8b+4Y46XyxPvrugBeNcB7BRiX8sT767oAvmCA9woAHsoT76+rBJjLBnh3txOvkifeX1dswZcO8G6N7sXyxPvr6i340gHe3TnqVfLE++uKAb50gHcXLnrX8sR7gNdPRqwzwLu7Y/FO5Yn3AK9jXCMGeHdgxDuVJ75VAI8ljP7PAb3/RfjcZfePHBB+79dpfpH1CanN30d+mT1h9GqAxxJGM5LQeeQ1+Tb+EQJrElLb38VHQ94TRq900aMIo8cSOo+8Dp8QfsB8zpqE1NO3OI9Zrj1h9EV78PqE0WMJnUdeU6E+Jjyk/hbrEFIfeWbvId8H9oTRFwdZaxJGvziW0Hn0gqYB/wyZ0PwRlxJST+BOw9m77Amj14ii1yGM/txYQudN0qDzGe4EqfA/5GJCagsHcPaEPWH0esekSwmjRxM6b5JEcZ4ww50ilvAOFxBSx4yLW+A/YU8YvfY5+ALC6NGEzhtmyZoFZoarwBLeZxUhtY4rc3bKnjB6TKJjFUHzJoTOozF2YBpsjcyxDgzhQ1YRUse8+J4wenwmaylB82hC5w0zoRXUNXaRBmSMQUqiWSWkLsaVqc/ZE0aPTFUuJWgeTei8SfLZQeMxNaZSIzbII4aE1Nmr13P2hNHjc9E9guYNCZ032YlNwESMLcZiLQHkE4aE1BFg0yAR4z1h9AiAGRA0jyZ03tyIxWMajMPWBIsxYJCnlITU5ShiHYdZ94TR4wCmSxg9jtB5KyPGYzymAYexWEMwAPIsAdYdV6aObmNPGD0aYLoEzaMJnTc0Ygs+YDw0GAtqxBjkuP38bMRWCHn73xNGjz75P73WenCEJnhwyVe3AEe8TtKdJcYhBl97wuhNAObK66lvD/9J9NS75v17wuitAN5fe4D31x7g/bUHeH/tAd5fe4D3AO+vPcD7aw/w/toDvL/2AO+vPcD7aw/w/toDvAd4f/24ABzZ8o+KLsSLS+Pv/TqTb3P4hKlQrTGh+fbIBT0Axqznnb+L/V2mb3HkN5Mb/nEHeK7d4IcDld6lmDW/iH9E+AH1MdOw/Jlu2T1xNmY98sv4wHnD7D3uNHu54WUuOsBTbQuvBsPT/UfzNxGYzwkP8c+Yz3C+r/i6DcyRL/rZ+utRwWH5PmfvcvYEt9jLDS/bg0/B64DWKrQM8AL8FPwS9beQCe6EMKNZYJol37jBMy35otdaz0Bw2H/C2Smc7+WGB0HWDELBmOByA3r5QONo4V+DpzR/hFS4U8wMW1PXNB4TOqYz9urxRV++ntWCw/U59Ty9ebdWbrgfRS9AYKKN63ZokZVygr8GZ/gfIhZXIXPsAlNjPOLBby5c1eOLvmQ9lwkOy5x6QV1j5TYqpS05JtUgUHUp5toHGsVfn4NX4RnMCe+AxTpwmApTYxqMxwfCeJGjpXzRF61nbcHhUBPqWze9svwcHJ+S6NPscKrEjug78Dx8Lj3T8D4YxGIdxmJcwhi34fzZUr7olevZCw5vkOhoClq5zBPZAnygD/Tl9EzDh6kl3VhsHYcDEb+hCtJSvuiV69kLDm+WycrOTArHmB5/VYyP6jOVjwgGawk2zQOaTcc1L+aLXrKeveDwZqlKrw8U9Y1p66uK8dEzdYwBeUQAY7DbyYNezBfdWQ97weEtAKYQg2xJIkuveAT3dYeLGH+ShrWNwZgN0b2YL7qznr3g8JYAo5bQBziPjx7BPZ0d9RCQp4UZbnFdzBddor4XHN4KYMrB2qHFRIzzcLAHQZ5the5ovui94PCWAPefaYnxIdzRwdHCbuR4B+tbiy96Lzi8E4D7z7S0mEPd+eqO3cT53Z0Y8SV80XvB4Z0ADJi/f7X113f+7p7/+UYBvur6657/+YYBvur6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+VMA8FXWX/f8z58OgK+y/rrnf75RgLna+uue//lTA/CV1V/3/M837aKvvv6653++UQvmauuve/7nTwfAV1N/3fM/fzr24Cuuv+75nz8FFnxl9dc9//MOr/8/glixwRuUfM4AAAAASUVORK5CYII="; } getSearchTexture() { return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAAhCAAAAABIXyLAAAAAOElEQVRIx2NgGAWjYBSMglEwEICREYRgFBZBqDCSLA2MGPUIVQETE9iNUAqLR5gIeoQKRgwXjwAAGn4AtaFeYLEAAAAASUVORK5CYII="; } }; //#endregion //#region node_modules/three-stdlib/shaders/FilmShader.js var FilmShader = { uniforms: { tDiffuse: { value: null }, time: { value: 0 }, nIntensity: { value: .5 }, sIntensity: { value: .05 }, sCount: { value: 4096 }, grayscale: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` #include // control parameter uniform float time; uniform bool grayscale; // noise effect intensity value (0 = no effect, 1 = full effect) uniform float nIntensity; // scanlines effect intensity value (0 = no effect, 1 = full effect) uniform float sIntensity; // scanlines effect count value (0 = no effect, 4096 = full effect) uniform float sCount; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { // sample the source vec4 cTextureScreen = texture2D( tDiffuse, vUv ); // make some noise float dx = rand( vUv + time ); // add noise vec3 cResult = cTextureScreen.rgb + cTextureScreen.rgb * clamp( 0.1 + dx, 0.0, 1.0 ); // get us a sine and cosine vec2 sc = vec2( sin( vUv.y * sCount ), cos( vUv.y * sCount ) ); // add scanlines cResult += cTextureScreen.rgb * vec3( sc.x, sc.y, sc.x ) * sIntensity; // interpolate between source and result by intensity cResult = cTextureScreen.rgb + clamp( nIntensity, 0.0,1.0 ) * ( cResult - cTextureScreen.rgb ); // convert to grayscale if desired if( grayscale ) { cResult = vec3( cResult.r * 0.3 + cResult.g * 0.59 + cResult.b * 0.11 ); } gl_FragColor = vec4( cResult, cTextureScreen.a ); } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/FilmPass.js var __defProp$22 = Object.defineProperty; var __defNormalProp$22 = (obj, key, value) => key in obj ? __defProp$22(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$22 = (obj, key, value) => { __defNormalProp$22(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var FilmPass = class extends Pass { constructor(noiseIntensity, scanlinesIntensity, scanlinesCount, grayscale) { super(); __publicField$22(this, "material"); __publicField$22(this, "fsQuad"); __publicField$22(this, "uniforms"); if (FilmShader === void 0) console.error("THREE.FilmPass relies on FilmShader"); const shader = FilmShader; this.uniforms = UniformsUtils.clone(shader.uniforms); this.material = new ShaderMaterial({ uniforms: this.uniforms, vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }); if (grayscale !== void 0) this.uniforms.grayscale.value = grayscale; if (noiseIntensity !== void 0) this.uniforms.nIntensity.value = noiseIntensity; if (scanlinesIntensity !== void 0) this.uniforms.sIntensity.value = scanlinesIntensity; if (scanlinesCount !== void 0) this.uniforms.sCount.value = scanlinesCount; this.fsQuad = new FullScreenQuad(this.material); } render(renderer, writeBuffer, readBuffer, deltaTime) { this.uniforms["tDiffuse"].value = readBuffer.texture; this.uniforms["time"].value += deltaTime; if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); } } }; //#endregion //#region node_modules/three-stdlib/shaders/CopyShader.js var CopyShader = { uniforms: { tDiffuse: { value: null }, opacity: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform float opacity; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = opacity * texel; } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/OutlinePass.js var __defProp$21 = Object.defineProperty; var __defNormalProp$21 = (obj, key, value) => key in obj ? __defProp$21(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$21 = (obj, key, value) => { __defNormalProp$21(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var OutlinePass = class extends Pass { constructor(resolution, scene, camera, selectedObjects) { super(); __publicField$21(this, "renderScene"); __publicField$21(this, "renderCamera"); __publicField$21(this, "selectedObjects"); __publicField$21(this, "visibleEdgeColor"); __publicField$21(this, "hiddenEdgeColor"); __publicField$21(this, "edgeGlow"); __publicField$21(this, "usePatternTexture"); __publicField$21(this, "edgeThickness"); __publicField$21(this, "edgeStrength"); __publicField$21(this, "downSampleRatio"); __publicField$21(this, "pulsePeriod"); __publicField$21(this, "resolution"); __publicField$21(this, "renderTargetMaskBuffer"); __publicField$21(this, "depthMaterial"); __publicField$21(this, "prepareMaskMaterial"); __publicField$21(this, "renderTargetDepthBuffer"); __publicField$21(this, "renderTargetMaskDownSampleBuffer"); __publicField$21(this, "renderTargetBlurBuffer1"); __publicField$21(this, "renderTargetBlurBuffer2"); __publicField$21(this, "edgeDetectionMaterial"); __publicField$21(this, "renderTargetEdgeBuffer1"); __publicField$21(this, "renderTargetEdgeBuffer2"); __publicField$21(this, "separableBlurMaterial1"); __publicField$21(this, "separableBlurMaterial2"); __publicField$21(this, "overlayMaterial"); __publicField$21(this, "materialCopy"); __publicField$21(this, "oldClearAlpha"); __publicField$21(this, "fsQuad"); __publicField$21(this, "tempPulseColor1"); __publicField$21(this, "tempPulseColor2"); __publicField$21(this, "textureMatrix"); __publicField$21(this, "patternTexture"); __publicField$21(this, "_visibilityCache"); __publicField$21(this, "_oldClearColor"); __publicField$21(this, "copyUniforms"); __publicField$21(this, "BlurDirectionX", new Vector2(1, 0)); __publicField$21(this, "BlurDirectionY", new Vector2(0, 1)); this.renderScene = scene; this.renderCamera = camera; this.selectedObjects = selectedObjects !== void 0 ? selectedObjects : []; this.visibleEdgeColor = new Color(1, 1, 1); this.hiddenEdgeColor = new Color(.1, .04, .02); this.edgeGlow = 0; this.usePatternTexture = false; this.edgeThickness = 1; this.edgeStrength = 3; this.downSampleRatio = 2; this.pulsePeriod = 0; this._visibilityCache = /* @__PURE__ */ new Map(); this.resolution = resolution !== void 0 ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); const resx = Math.round(this.resolution.x / this.downSampleRatio); const resy = Math.round(this.resolution.y / this.downSampleRatio); this.renderTargetMaskBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y); this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask"; this.renderTargetMaskBuffer.texture.generateMipmaps = false; this.depthMaterial = new MeshDepthMaterial(); this.depthMaterial.side = 2; this.depthMaterial.depthPacking = RGBADepthPacking; this.depthMaterial.blending = 0; this.prepareMaskMaterial = this.getPrepareMaskMaterial(); this.prepareMaskMaterial.side = 2; this.prepareMaskMaterial.fragmentShader = replaceDepthToViewZ(this.prepareMaskMaterial.fragmentShader, this.renderCamera); this.renderTargetDepthBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y); this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth"; this.renderTargetDepthBuffer.texture.generateMipmaps = false; this.renderTargetMaskDownSampleBuffer = new WebGLRenderTarget(resx, resy); this.renderTargetMaskDownSampleBuffer.texture.name = "OutlinePass.depthDownSample"; this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = false; this.renderTargetBlurBuffer1 = new WebGLRenderTarget(resx, resy); this.renderTargetBlurBuffer1.texture.name = "OutlinePass.blur1"; this.renderTargetBlurBuffer1.texture.generateMipmaps = false; this.renderTargetBlurBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2)); this.renderTargetBlurBuffer2.texture.name = "OutlinePass.blur2"; this.renderTargetBlurBuffer2.texture.generateMipmaps = false; this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(); this.renderTargetEdgeBuffer1 = new WebGLRenderTarget(resx, resy); this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1"; this.renderTargetEdgeBuffer1.texture.generateMipmaps = false; this.renderTargetEdgeBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2)); this.renderTargetEdgeBuffer2.texture.name = "OutlinePass.edge2"; this.renderTargetEdgeBuffer2.texture.generateMipmaps = false; const MAX_EDGE_THICKNESS = 4; const MAX_EDGE_GLOW = 4; this.separableBlurMaterial1 = this.getSeperableBlurMaterial(MAX_EDGE_THICKNESS); this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy); this.separableBlurMaterial1.uniforms["kernelRadius"].value = 1; this.separableBlurMaterial2 = this.getSeperableBlurMaterial(MAX_EDGE_GLOW); this.separableBlurMaterial2.uniforms["texSize"].value.set(Math.round(resx / 2), Math.round(resy / 2)); this.separableBlurMaterial2.uniforms["kernelRadius"].value = MAX_EDGE_GLOW; this.overlayMaterial = this.getOverlayMaterial(); if (CopyShader === void 0) console.error("THREE.OutlinePass relies on CopyShader"); 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: 0, depthTest: false, depthWrite: false, transparent: true }); this.enabled = true; this.needsSwap = false; this._oldClearColor = new Color(); this.oldClearAlpha = 1; this.fsQuad = new FullScreenQuad(this.materialCopy); this.tempPulseColor1 = new Color(); this.tempPulseColor2 = new Color(); this.textureMatrix = new Matrix4(); function replaceDepthToViewZ(string, camera2) { const type = camera2.isPerspectiveCamera ? "perspective" : "orthographic"; return string.replace(/DEPTH_TO_VIEW_Z/g, type + "DepthToViewZ"); } } dispose() { this.renderTargetMaskBuffer.dispose(); this.renderTargetDepthBuffer.dispose(); this.renderTargetMaskDownSampleBuffer.dispose(); this.renderTargetBlurBuffer1.dispose(); this.renderTargetBlurBuffer2.dispose(); this.renderTargetEdgeBuffer1.dispose(); this.renderTargetEdgeBuffer2.dispose(); } setSize(width, height) { this.renderTargetMaskBuffer.setSize(width, height); this.renderTargetDepthBuffer.setSize(width, height); let resx = Math.round(width / this.downSampleRatio); let resy = Math.round(height / this.downSampleRatio); this.renderTargetMaskDownSampleBuffer.setSize(resx, resy); this.renderTargetBlurBuffer1.setSize(resx, resy); this.renderTargetEdgeBuffer1.setSize(resx, resy); this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy); resx = Math.round(resx / 2); resy = Math.round(resy / 2); this.renderTargetBlurBuffer2.setSize(resx, resy); this.renderTargetEdgeBuffer2.setSize(resx, resy); this.separableBlurMaterial2.uniforms["texSize"].value.set(resx, resy); } changeVisibilityOfSelectedObjects(bVisible) { const cache = this._visibilityCache; function gatherSelectedMeshesCallBack(object) { if (object.isMesh) if (bVisible === true) object.visible = cache.get(object); else { cache.set(object, object.visible); object.visible = bVisible; } } for (let i = 0; i < this.selectedObjects.length; i++) this.selectedObjects[i].traverse(gatherSelectedMeshesCallBack); } changeVisibilityOfNonSelectedObjects(bVisible) { const cache = this._visibilityCache; const selectedMeshes = []; function gatherSelectedMeshesCallBack(object) { if (object.isMesh) selectedMeshes.push(object); } for (let i = 0; i < this.selectedObjects.length; i++) this.selectedObjects[i].traverse(gatherSelectedMeshesCallBack); function VisibilityChangeCallBack(object) { if (object.isMesh || object.isSprite) { let bFound = false; for (let i = 0; i < selectedMeshes.length; i++) if (selectedMeshes[i].id === object.id) { bFound = true; break; } if (bFound === false) { const visibility = object.visible; if (bVisible === false || cache.get(object) === true) object.visible = bVisible; cache.set(object, visibility); } } else if (object.isPoints || object.isLine) if (bVisible === true) object.visible = cache.get(object); else { cache.set(object, object.visible); object.visible = bVisible; } } this.renderScene.traverse(VisibilityChangeCallBack); } updateTextureMatrix() { this.textureMatrix.set(.5, 0, 0, .5, 0, .5, 0, .5, 0, 0, .5, .5, 0, 0, 0, 1); this.textureMatrix.multiply(this.renderCamera.projectionMatrix); this.textureMatrix.multiply(this.renderCamera.matrixWorldInverse); } render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) { if (this.selectedObjects.length > 0) { renderer.getClearColor(this._oldClearColor); this.oldClearAlpha = renderer.getClearAlpha(); const oldAutoClear = renderer.autoClear; renderer.autoClear = false; if (maskActive) renderer.state.buffers.stencil.setTest(false); renderer.setClearColor(16777215, 1); this.changeVisibilityOfSelectedObjects(false); const currentBackground = this.renderScene.background; this.renderScene.background = null; this.renderScene.overrideMaterial = this.depthMaterial; renderer.setRenderTarget(this.renderTargetDepthBuffer); renderer.clear(); renderer.render(this.renderScene, this.renderCamera); this.changeVisibilityOfSelectedObjects(true); this._visibilityCache.clear(); this.updateTextureMatrix(); this.changeVisibilityOfNonSelectedObjects(false); this.renderScene.overrideMaterial = this.prepareMaskMaterial; this.prepareMaskMaterial.uniforms["cameraNearFar"].value.set(this.renderCamera.near, this.renderCamera.far); this.prepareMaskMaterial.uniforms["depthTexture"].value = this.renderTargetDepthBuffer.texture; this.prepareMaskMaterial.uniforms["textureMatrix"].value = this.textureMatrix; renderer.setRenderTarget(this.renderTargetMaskBuffer); renderer.clear(); renderer.render(this.renderScene, this.renderCamera); this.renderScene.overrideMaterial = null; this.changeVisibilityOfNonSelectedObjects(true); this._visibilityCache.clear(); this.renderScene.background = currentBackground; this.fsQuad.material = this.materialCopy; this.copyUniforms["tDiffuse"].value = this.renderTargetMaskBuffer.texture; renderer.setRenderTarget(this.renderTargetMaskDownSampleBuffer); renderer.clear(); this.fsQuad.render(renderer); this.tempPulseColor1.copy(this.visibleEdgeColor); this.tempPulseColor2.copy(this.hiddenEdgeColor); if (this.pulsePeriod > 0) { const scalar = 1.25 / 2 + Math.cos(performance.now() * .01 / this.pulsePeriod) * .75 / 2; this.tempPulseColor1.multiplyScalar(scalar); this.tempPulseColor2.multiplyScalar(scalar); } this.fsQuad.material = this.edgeDetectionMaterial; this.edgeDetectionMaterial.uniforms["maskTexture"].value = this.renderTargetMaskDownSampleBuffer.texture; this.edgeDetectionMaterial.uniforms["texSize"].value.set(this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height); this.edgeDetectionMaterial.uniforms["visibleEdgeColor"].value = this.tempPulseColor1; this.edgeDetectionMaterial.uniforms["hiddenEdgeColor"].value = this.tempPulseColor2; renderer.setRenderTarget(this.renderTargetEdgeBuffer1); renderer.clear(); this.fsQuad.render(renderer); this.fsQuad.material = this.separableBlurMaterial1; this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture; this.separableBlurMaterial1.uniforms["direction"].value = this.BlurDirectionX; this.separableBlurMaterial1.uniforms["kernelRadius"].value = this.edgeThickness; renderer.setRenderTarget(this.renderTargetBlurBuffer1); renderer.clear(); this.fsQuad.render(renderer); this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetBlurBuffer1.texture; this.separableBlurMaterial1.uniforms["direction"].value = this.BlurDirectionY; renderer.setRenderTarget(this.renderTargetEdgeBuffer1); renderer.clear(); this.fsQuad.render(renderer); this.fsQuad.material = this.separableBlurMaterial2; this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture; this.separableBlurMaterial2.uniforms["direction"].value = this.BlurDirectionX; renderer.setRenderTarget(this.renderTargetBlurBuffer2); renderer.clear(); this.fsQuad.render(renderer); this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetBlurBuffer2.texture; this.separableBlurMaterial2.uniforms["direction"].value = this.BlurDirectionY; renderer.setRenderTarget(this.renderTargetEdgeBuffer2); renderer.clear(); this.fsQuad.render(renderer); this.fsQuad.material = this.overlayMaterial; this.overlayMaterial.uniforms["maskTexture"].value = this.renderTargetMaskBuffer.texture; this.overlayMaterial.uniforms["edgeTexture1"].value = this.renderTargetEdgeBuffer1.texture; this.overlayMaterial.uniforms["edgeTexture2"].value = this.renderTargetEdgeBuffer2.texture; this.overlayMaterial.uniforms["patternTexture"].value = this.patternTexture; this.overlayMaterial.uniforms["edgeStrength"].value = this.edgeStrength; this.overlayMaterial.uniforms["edgeGlow"].value = this.edgeGlow; this.overlayMaterial.uniforms["usePatternTexture"].value = this.usePatternTexture; if (maskActive) renderer.state.buffers.stencil.setTest(true); renderer.setRenderTarget(readBuffer); this.fsQuad.render(renderer); renderer.setClearColor(this._oldClearColor, this.oldClearAlpha); renderer.autoClear = oldAutoClear; } if (this.renderToScreen) { this.fsQuad.material = this.materialCopy; this.copyUniforms["tDiffuse"].value = readBuffer.texture; renderer.setRenderTarget(null); this.fsQuad.render(renderer); } } getPrepareMaskMaterial() { return new ShaderMaterial({ uniforms: { depthTexture: { value: null }, cameraNearFar: { value: new Vector2(.5, .5) }, textureMatrix: { value: null } }, vertexShader: `#include #include varying vec4 projTexCoord; varying vec4 vPosition; uniform mat4 textureMatrix; void main() { #include #include #include #include #include vPosition = mvPosition; vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 ); projTexCoord = textureMatrix * worldPosition; }`, fragmentShader: `#include varying vec4 vPosition; varying vec4 projTexCoord; uniform sampler2D depthTexture; uniform vec2 cameraNearFar; void main() { float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord )); float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y ); float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0; gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0); }` }); } getEdgeDetectionMaterial() { return new ShaderMaterial({ uniforms: { maskTexture: { value: null }, texSize: { value: new Vector2(.5, .5) }, visibleEdgeColor: { value: new Vector3(1, 1, 1) }, hiddenEdgeColor: { value: new Vector3(1, 1, 1) } }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: `varying vec2 vUv; uniform sampler2D maskTexture; uniform vec2 texSize; uniform vec3 visibleEdgeColor; uniform vec3 hiddenEdgeColor; void main() { vec2 invSize = 1.0 / texSize; vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize); vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy); vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy); vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw); vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw); float diff1 = (c1.r - c2.r)*0.5; float diff2 = (c3.r - c4.r)*0.5; float d = length( vec2(diff1, diff2) ); float a1 = min(c1.g, c2.g); float a2 = min(c3.g, c4.g); float visibilityFactor = min(a1, a2); vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor; gl_FragColor = vec4(edgeColor, 1.0) * vec4(d); }` }); } getSeperableBlurMaterial(maxRadius) { return new ShaderMaterial({ defines: { MAX_RADIUS: maxRadius }, uniforms: { colorTexture: { value: null }, texSize: { value: new Vector2(.5, .5) }, direction: { value: new Vector2(.5, .5) }, kernelRadius: { value: 1 } }, 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; uniform float kernelRadius; float gaussianPdf(in float x, in float sigma) { return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma; } void main() { vec2 invSize = 1.0 / texSize; float weightSum = gaussianPdf(0.0, kernelRadius); vec4 diffuseSum = texture2D( colorTexture, vUv) * weightSum; vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS); vec2 uvOffset = delta; for( int i = 1; i <= MAX_RADIUS; i ++ ) { float w = gaussianPdf(uvOffset.x, kernelRadius); vec4 sample1 = texture2D( colorTexture, vUv + uvOffset); vec4 sample2 = texture2D( colorTexture, vUv - uvOffset); diffuseSum += ((sample1 + sample2) * w); weightSum += (2.0 * w); uvOffset += delta; } gl_FragColor = diffuseSum/weightSum; }` }); } getOverlayMaterial() { return new ShaderMaterial({ uniforms: { maskTexture: { value: null }, edgeTexture1: { value: null }, edgeTexture2: { value: null }, patternTexture: { value: null }, edgeStrength: { value: 1 }, edgeGlow: { value: 1 }, usePatternTexture: { value: 0 } }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: `varying vec2 vUv; uniform sampler2D maskTexture; uniform sampler2D edgeTexture1; uniform sampler2D edgeTexture2; uniform sampler2D patternTexture; uniform float edgeStrength; uniform float edgeGlow; uniform bool usePatternTexture; void main() { vec4 edgeValue1 = texture2D(edgeTexture1, vUv); vec4 edgeValue2 = texture2D(edgeTexture2, vUv); vec4 maskColor = texture2D(maskTexture, vUv); vec4 patternColor = texture2D(patternTexture, 6.0 * vUv); float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5; vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow; vec4 finalColor = edgeStrength * maskColor.r * edgeValue; if(usePatternTexture) finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r); gl_FragColor = finalColor; }`, blending: 2, depthTest: false, depthWrite: false, transparent: true }); } }; //#endregion //#region 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: /* @__PURE__ */ new Vector2() }, cameraProjectionMatrix: { value: /* @__PURE__ */ new Matrix4() }, cameraInverseProjectionMatrix: { value: /* @__PURE__ */ new Matrix4() }, kernelRadius: { value: 8 }, minDistance: { value: .005 }, maxDistance: { value: .05 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDepth; uniform float cameraNear; uniform float cameraFar; varying vec2 vUv; #include 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: /* @__PURE__ */ new Vector2() } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform vec2 resolution; varying vec2 vUv; void main() { vec2 texelSize = ( 1.0 / resolution ); float result = 0.0; for ( int i = - 2; i <= 2; i ++ ) { for ( int j = - 2; j <= 2; j ++ ) { vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize; result += texture2D( tDiffuse, vUv + offset ).r; } } gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 ); } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/SSAOPass.js var __defProp$20 = Object.defineProperty; var __defNormalProp$20 = (obj, key, value) => key in obj ? __defProp$20(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$20 = (obj, key, value) => { __defNormalProp$20(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var SSAOPass = /* @__PURE__ */ (() => { 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 = .005; this.maxDistance = .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: 0 }); 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 = 0; 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: 0 }); 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: 208, blendDst: 200, blendEquation: 100, blendSrcAlpha: 206, blendDstAlpha: 200, blendEquationAlpha: 100 }); 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 = 0; 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 = 0; 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 = 0; 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 = 0; 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 = 0; this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; this.copyMaterial.blending = 5; 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 i = 0; i < kernelSize; i++) { const sample = new Vector3(); sample.x = Math.random() * 2 - 1; sample.y = Math.random() * 2 - 1; sample.z = Math.random(); sample.normalize(); let scale = i / kernelSize; scale = MathUtils.lerp(.1, 1, scale * scale); sample.multiplyScalar(scale); 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 size = width * height; const data = new Float32Array(size); for (let i = 0; i < size; i++) { const x = Math.random() * 2 - 1; const y = Math.random() * 2 - 1; data[i] = simplex.noise3d(x, y, 0); } 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) { object.visible = cache.get(object); }); cache.clear(); } }; let SSAOPass2 = _SSAOPass; __publicField$20(SSAOPass2, "OUTPUT", { Default: 0, SSAO: 1, Blur: 2, Beauty: 3, Depth: 4, Normal: 5 }); return SSAOPass2; })(); //#endregion //#region node_modules/three-stdlib/postprocessing/SavePass.js var SavePass = class extends Pass { constructor(renderTarget) { super(); if (CopyShader === void 0) console.error("THREE.SavePass relies on CopyShader"); const shader = CopyShader; this.textureID = "tDiffuse"; this.uniforms = UniformsUtils.clone(shader.uniforms); this.material = new ShaderMaterial({ uniforms: this.uniforms, vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader, blending: 0 }); this.renderTarget = renderTarget; if (this.renderTarget === void 0) { this.renderTarget = new WebGLRenderTarget(window.innerWidth, window.innerHeight); this.renderTarget.texture.name = "SavePass.rt"; } this.needsSwap = false; this.fsQuad = new FullScreenQuad(this.material); } render(renderer, writeBuffer, readBuffer) { if (this.uniforms[this.textureID]) this.uniforms[this.textureID].value = readBuffer.texture; renderer.setRenderTarget(this.renderTarget); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); } }; //#endregion //#region node_modules/three-stdlib/shaders/BokehShader.js var BokehShader = { defines: { DEPTH_PACKING: 1, PERSPECTIVE_CAMERA: 1 }, uniforms: { tColor: { value: null }, tDepth: { value: null }, focus: { value: 1 }, aspect: { value: 1 }, aperture: { value: .025 }, maxblur: { value: .01 }, nearClip: { value: 1 }, farClip: { value: 1e3 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` #include varying vec2 vUv; uniform sampler2D tColor; uniform sampler2D tDepth; uniform float maxblur; // max blur amount uniform float aperture; // aperture - bigger values for shallower depth of field uniform float nearClip; uniform float farClip; uniform float focus; uniform float aspect; #include float getDepth( const in vec2 screenPosition ) { #if DEPTH_PACKING == 1 return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) ); #else return texture2D( tDepth, screenPosition ).x; #endif } float getViewZ( const in float depth ) { #if PERSPECTIVE_CAMERA == 1 return perspectiveDepthToViewZ( depth, nearClip, farClip ); #else return orthographicDepthToViewZ( depth, nearClip, farClip ); #endif } void main() { vec2 aspectcorrect = vec2( 1.0, aspect ); float viewZ = getViewZ( getDepth( vUv ) ); float factor = ( focus + viewZ ); // viewZ is <= 0, so this is a difference equation vec2 dofblur = vec2 ( clamp( factor * aperture, -maxblur, maxblur ) ); vec2 dofblur9 = dofblur * 0.9; vec2 dofblur7 = dofblur * 0.7; vec2 dofblur4 = dofblur * 0.4; vec4 col = vec4( 0.0 ); col += texture2D( tColor, vUv.xy ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur ); col += texture2D( tColor, vUv.xy + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur9 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur7 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.4, 0.0 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur4 ); col += texture2D( tColor, vUv.xy + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur4 ); gl_FragColor = col / 41.0; gl_FragColor.a = 1.0; } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/BokehPass.js var __defProp$19 = Object.defineProperty; var __defNormalProp$19 = (obj, key, value) => key in obj ? __defProp$19(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$19 = (obj, key, value) => { __defNormalProp$19(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var BokehPass = class extends Pass { constructor(scene, camera, params) { super(); __publicField$19(this, "scene"); __publicField$19(this, "camera"); __publicField$19(this, "renderTargetDepth"); __publicField$19(this, "materialDepth"); __publicField$19(this, "materialBokeh"); __publicField$19(this, "fsQuad"); __publicField$19(this, "_oldClearColor"); __publicField$19(this, "uniforms"); this.scene = scene; this.camera = camera; const focus = params.focus !== void 0 ? params.focus : 1; const aspect = params.aspect !== void 0 ? params.aspect : camera.aspect; const aperture = params.aperture !== void 0 ? params.aperture : .025; const maxblur = params.maxblur !== void 0 ? params.maxblur : 1; const width = params.width || window.innerWidth || 1; const height = params.height || window.innerHeight || 1; this.renderTargetDepth = new WebGLRenderTarget(width, height, { minFilter: NearestFilter, magFilter: NearestFilter }); this.renderTargetDepth.texture.name = "BokehPass.depth"; this.materialDepth = new MeshDepthMaterial(); this.materialDepth.depthPacking = RGBADepthPacking; this.materialDepth.blending = 0; if (BokehShader === void 0) console.error("BokehPass relies on BokehShader"); const bokehShader = BokehShader; const bokehUniforms = UniformsUtils.clone(bokehShader.uniforms); bokehUniforms["tDepth"].value = this.renderTargetDepth.texture; bokehUniforms["focus"].value = focus; bokehUniforms["aspect"].value = aspect; bokehUniforms["aperture"].value = aperture; bokehUniforms["maxblur"].value = maxblur; bokehUniforms["nearClip"].value = camera.near; bokehUniforms["farClip"].value = camera.far; this.materialBokeh = new ShaderMaterial({ defines: Object.assign({}, bokehShader.defines), uniforms: bokehUniforms, vertexShader: bokehShader.vertexShader, fragmentShader: bokehShader.fragmentShader }); this.uniforms = bokehUniforms; this.needsSwap = false; this.fsQuad = new FullScreenQuad(this.materialBokeh); this._oldClearColor = new Color(); } render(renderer, writeBuffer, readBuffer) { this.scene.overrideMaterial = this.materialDepth; renderer.getClearColor(this._oldClearColor); const oldClearAlpha = renderer.getClearAlpha(); const oldAutoClear = renderer.autoClear; renderer.autoClear = false; renderer.setClearColor(16777215); renderer.setClearAlpha(1); renderer.setRenderTarget(this.renderTargetDepth); renderer.clear(); renderer.render(this.scene, this.camera); this.uniforms["tColor"].value = readBuffer.texture; this.uniforms["nearClip"].value = this.camera.near; this.uniforms["farClip"].value = this.camera.far; if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); renderer.clear(); this.fsQuad.render(renderer); } this.scene.overrideMaterial = null; renderer.setClearColor(this._oldClearColor); renderer.setClearAlpha(oldClearAlpha); renderer.autoClear = oldAutoClear; } }; //#endregion //#region node_modules/three-stdlib/postprocessing/TexturePass.js var TexturePass = class extends Pass { constructor(map, opacity) { super(); const shader = CopyShader; this.map = map; this.opacity = opacity !== void 0 ? opacity : 1; this.uniforms = UniformsUtils.clone(shader.uniforms); this.material = new ShaderMaterial({ uniforms: this.uniforms, vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader, depthTest: false, depthWrite: false, premultipliedAlpha: true }); this.needsSwap = false; this.fsQuad = new FullScreenQuad(null); } render(renderer, writeBuffer, readBuffer) { const oldAutoClear = renderer.autoClear; renderer.autoClear = false; this.fsQuad.material = this.material; this.uniforms["opacity"].value = this.opacity; this.uniforms["tDiffuse"].value = this.map; this.material.transparent = this.opacity < 1; renderer.setRenderTarget(this.renderToScreen ? null : readBuffer); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); renderer.autoClear = oldAutoClear; } dispose() { this.material.dispose(); this.fsQuad.dispose(); } }; //#endregion //#region node_modules/three-stdlib/shaders/LuminosityShader.js var LuminosityShader = { uniforms: { tDiffuse: { value: null } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` #include uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); float l = linearToRelativeLuminance( texel.rgb ); gl_FragColor = vec4( l, l, l, texel.w ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/ToneMapShader.js var ToneMapShader = { uniforms: { tDiffuse: { value: null }, averageLuminance: { value: 1 }, luminanceMap: { value: null }, maxLuminance: { value: 16 }, minLuminance: { value: .01 }, middleGrey: { value: .6 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` #include uniform sampler2D tDiffuse; varying vec2 vUv; uniform float middleGrey; uniform float minLuminance; uniform float maxLuminance; #ifdef ADAPTED_LUMINANCE uniform sampler2D luminanceMap; #else uniform float averageLuminance; #endif vec3 ToneMap( vec3 vColor ) { #ifdef ADAPTED_LUMINANCE // Get the calculated average luminance float fLumAvg = texture2D(luminanceMap, vec2(0.5, 0.5)).r; #else float fLumAvg = averageLuminance; #endif // Calculate the luminance of the current pixel float fLumPixel = linearToRelativeLuminance( vColor ); // Apply the modified operator (Eq. 4) float fLumScaled = (fLumPixel * middleGrey) / max( minLuminance, fLumAvg ); float fLumCompressed = (fLumScaled * (1.0 + (fLumScaled / (maxLuminance * maxLuminance)))) / (1.0 + fLumScaled); return fLumCompressed * vColor; } void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = vec4( ToneMap( texel.xyz ), texel.w ); } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/AdaptiveToneMappingPass.js var AdaptiveToneMappingPass = class extends Pass { constructor(adaptive, resolution) { super(); this.resolution = resolution !== void 0 ? resolution : 256; this.needsInit = true; this.adaptive = adaptive !== void 0 ? !!adaptive : true; this.luminanceRT = null; this.previousLuminanceRT = null; this.currentLuminanceRT = null; const copyShader = CopyShader; this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); this.materialCopy = new ShaderMaterial({ uniforms: this.copyUniforms, vertexShader: copyShader.vertexShader, fragmentShader: copyShader.fragmentShader, blending: 0, depthTest: false }); this.materialLuminance = new ShaderMaterial({ uniforms: UniformsUtils.clone(LuminosityShader.uniforms), vertexShader: LuminosityShader.vertexShader, fragmentShader: LuminosityShader.fragmentShader, blending: 0 }); this.adaptLuminanceShader = { defines: { MIP_LEVEL_1X1: (Math.log(this.resolution) / Math.log(2)).toFixed(1) }, uniforms: { lastLum: { value: null }, currentLum: { value: null }, minLuminance: { value: .01 }, delta: { value: .016 }, tau: { value: 1 } }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: `varying vec2 vUv; uniform sampler2D lastLum; uniform sampler2D currentLum; uniform float minLuminance; uniform float delta; uniform float tau; void main() { vec4 lastLum = texture2D( lastLum, vUv, MIP_LEVEL_1X1 ); vec4 currentLum = texture2D( currentLum, vUv, MIP_LEVEL_1X1 ); float fLastLum = max( minLuminance, lastLum.r ); float fCurrentLum = max( minLuminance, currentLum.r ); //The adaption seems to work better in extreme lighting differences //if the input luminance is squared. fCurrentLum *= fCurrentLum; // Adapt the luminance using Pattanaik's technique float fAdaptedLum = fLastLum + (fCurrentLum - fLastLum) * (1.0 - exp(-delta * tau)); // "fAdaptedLum = sqrt(fAdaptedLum); gl_FragColor.r = fAdaptedLum; }` }; this.materialAdaptiveLum = new ShaderMaterial({ uniforms: UniformsUtils.clone(this.adaptLuminanceShader.uniforms), vertexShader: this.adaptLuminanceShader.vertexShader, fragmentShader: this.adaptLuminanceShader.fragmentShader, defines: Object.assign({}, this.adaptLuminanceShader.defines), blending: 0 }); this.materialToneMap = new ShaderMaterial({ uniforms: UniformsUtils.clone(ToneMapShader.uniforms), vertexShader: ToneMapShader.vertexShader, fragmentShader: ToneMapShader.fragmentShader, blending: 0 }); this.fsQuad = new FullScreenQuad(null); } render(renderer, writeBuffer, readBuffer, deltaTime) { if (this.needsInit) { this.reset(renderer); this.luminanceRT.texture.type = readBuffer.texture.type; this.previousLuminanceRT.texture.type = readBuffer.texture.type; this.currentLuminanceRT.texture.type = readBuffer.texture.type; this.needsInit = false; } if (this.adaptive) { this.fsQuad.material = this.materialLuminance; this.materialLuminance.uniforms.tDiffuse.value = readBuffer.texture; renderer.setRenderTarget(this.currentLuminanceRT); this.fsQuad.render(renderer); this.fsQuad.material = this.materialAdaptiveLum; this.materialAdaptiveLum.uniforms.delta.value = deltaTime; this.materialAdaptiveLum.uniforms.lastLum.value = this.previousLuminanceRT.texture; this.materialAdaptiveLum.uniforms.currentLum.value = this.currentLuminanceRT.texture; renderer.setRenderTarget(this.luminanceRT); this.fsQuad.render(renderer); this.fsQuad.material = this.materialCopy; this.copyUniforms.tDiffuse.value = this.luminanceRT.texture; renderer.setRenderTarget(this.previousLuminanceRT); this.fsQuad.render(renderer); } this.fsQuad.material = this.materialToneMap; this.materialToneMap.uniforms.tDiffuse.value = readBuffer.texture; if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); } } reset() { if (this.luminanceRT) this.luminanceRT.dispose(); if (this.currentLuminanceRT) this.currentLuminanceRT.dispose(); if (this.previousLuminanceRT) this.previousLuminanceRT.dispose(); this.luminanceRT = new WebGLRenderTarget(this.resolution, this.resolution); this.luminanceRT.texture.name = "AdaptiveToneMappingPass.l"; this.luminanceRT.texture.generateMipmaps = false; this.previousLuminanceRT = new WebGLRenderTarget(this.resolution, this.resolution); this.previousLuminanceRT.texture.name = "AdaptiveToneMappingPass.pl"; this.previousLuminanceRT.texture.generateMipmaps = false; const pars = { minFilter: LinearMipmapLinearFilter, generateMipmaps: true }; this.currentLuminanceRT = new WebGLRenderTarget(this.resolution, this.resolution, pars); this.currentLuminanceRT.texture.name = "AdaptiveToneMappingPass.cl"; if (this.adaptive) { this.materialToneMap.defines["ADAPTED_LUMINANCE"] = ""; this.materialToneMap.uniforms.luminanceMap.value = this.luminanceRT.texture; } this.fsQuad.material = new MeshBasicMaterial({ color: 7829367 }); this.materialLuminance.needsUpdate = true; this.materialAdaptiveLum.needsUpdate = true; this.materialToneMap.needsUpdate = true; } setAdaptive(adaptive) { if (adaptive) { this.adaptive = true; this.materialToneMap.defines["ADAPTED_LUMINANCE"] = ""; this.materialToneMap.uniforms.luminanceMap.value = this.luminanceRT.texture; } else { this.adaptive = false; delete this.materialToneMap.defines["ADAPTED_LUMINANCE"]; this.materialToneMap.uniforms.luminanceMap.value = null; } this.materialToneMap.needsUpdate = true; } setAdaptionRate(rate) { if (rate) this.materialAdaptiveLum.uniforms.tau.value = Math.abs(rate); } setMinLuminance(minLum) { if (minLum) { this.materialToneMap.uniforms.minLuminance.value = minLum; this.materialAdaptiveLum.uniforms.minLuminance.value = minLum; } } setMaxLuminance(maxLum) { if (maxLum) this.materialToneMap.uniforms.maxLuminance.value = maxLum; } setAverageLuminance(avgLum) { if (avgLum) this.materialToneMap.uniforms.averageLuminance.value = avgLum; } setMiddleGrey(middleGrey) { if (middleGrey) this.materialToneMap.uniforms.middleGrey.value = middleGrey; } dispose() { if (this.luminanceRT) this.luminanceRT.dispose(); if (this.previousLuminanceRT) this.previousLuminanceRT.dispose(); if (this.currentLuminanceRT) this.currentLuminanceRT.dispose(); if (this.materialLuminance) this.materialLuminance.dispose(); if (this.materialAdaptiveLum) this.materialAdaptiveLum.dispose(); if (this.materialCopy) this.materialCopy.dispose(); if (this.materialToneMap) this.materialToneMap.dispose(); } }; //#endregion //#region node_modules/three-stdlib/shaders/LuminosityHighPassShader.js var LuminosityHighPassShader = { shaderID: "luminosityHighPass", uniforms: { tDiffuse: { value: null }, luminosityThreshold: { value: 1 }, smoothWidth: { value: 1 }, defaultColor: { value: /* @__PURE__ */ new Color(0) }, defaultOpacity: { value: 0 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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 ); } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/UnrealBloomPass.js var __defProp$18 = Object.defineProperty; var __defNormalProp$18 = (obj, key, value) => key in obj ? __defProp$18(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$18 = (obj, key, value) => { __defNormalProp$18(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var UnrealBloomPass = /* @__PURE__ */ (() => { 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 i = 0; i < this.nMips; i++) { const renderTargetHorizonal = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); renderTargetHorizonal.texture.name = "UnrealBloomPass.h" + i; renderTargetHorizonal.texture.generateMipmaps = false; this.renderTargetsHorizontal.push(renderTargetHorizonal); const renderTargetVertical = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); renderTargetVertical.texture.name = "UnrealBloomPass.v" + i; renderTargetVertical.texture.generateMipmaps = false; this.renderTargetsVertical.push(renderTargetVertical); resx = Math.round(resx / 2); resy = Math.round(resy / 2); } const highPassShader = LuminosityHighPassShader; this.highPassUniforms = UniformsUtils.clone(highPassShader.uniforms); this.highPassUniforms["luminosityThreshold"].value = threshold; this.highPassUniforms["smoothWidth"].value = .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 i = 0; i < this.nMips; i++) { this.separableBlurMaterials.push(this.getSeperableBlurMaterial(kernelSizeArray[i])); this.separableBlurMaterials[i].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 = .1; this.compositeMaterial.needsUpdate = true; const bloomFactors = [ 1, .8, .6, .4, .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: 2, 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 i = 0; i < this.renderTargetsHorizontal.length; i++) this.renderTargetsHorizontal[i].dispose(); for (let i = 0; i < this.renderTargetsVertical.length; i++) this.renderTargetsVertical[i].dispose(); this.renderTargetBright.dispose(); for (let i = 0; i < this.separableBlurMaterials.length; i++) this.separableBlurMaterials[i].dispose(); this.compositeMaterial.dispose(); this.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 i = 0; i < this.nMips; i++) { this.renderTargetsHorizontal[i].setSize(resx, resy); this.renderTargetsVertical[i].setSize(resx, resy); this.separableBlurMaterials[i].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 i = 0; i < this.nMips; i++) { this.fsQuad.material = this.separableBlurMaterials[i]; this.separableBlurMaterials[i].uniforms["colorTexture"].value = inputRenderTarget.texture; this.separableBlurMaterials[i].uniforms["direction"].value = _UnrealBloomPass.BlurDirectionX; renderer.setRenderTarget(this.renderTargetsHorizontal[i]); renderer.clear(); this.fsQuad.render(renderer); this.separableBlurMaterials[i].uniforms["colorTexture"].value = this.renderTargetsHorizontal[i].texture; this.separableBlurMaterials[i].uniforms["direction"].value = _UnrealBloomPass.BlurDirectionY; renderer.setRenderTarget(this.renderTargetsVertical[i]); renderer.clear(); this.fsQuad.render(renderer); inputRenderTarget = this.renderTargetsVertical[i]; } this.fsQuad.material = this.compositeMaterial; this.compositeMaterial.uniforms["bloomStrength"].value = this.strength; this.compositeMaterial.uniforms["bloomRadius"].value = this.radius; this.compositeMaterial.uniforms["bloomTintColors"].value = this.bloomTintColors; 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(.5, .5) }, direction: { value: new Vector2(.5, .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; __publicField$18(UnrealBloomPass2, "BlurDirectionX", new Vector2(1, 0)); __publicField$18(UnrealBloomPass2, "BlurDirectionY", new Vector2(0, 1)); return UnrealBloomPass2; })(); //#endregion //#region node_modules/three-stdlib/postprocessing/CubeTexturePass.js var CubeTexturePass = class extends Pass { constructor(camera, tCube, opacity = 1) { super(); this.camera = camera; this.needsSwap = false; this.cubeShader = ShaderLib["cube"]; this.cubeMesh = new Mesh(new BoxGeometry(10, 10, 10), new ShaderMaterial({ uniforms: UniformsUtils.clone(this.cubeShader.uniforms), vertexShader: this.cubeShader.vertexShader, fragmentShader: this.cubeShader.fragmentShader, depthTest: false, depthWrite: false, side: 1 })); Object.defineProperty(this.cubeMesh.material, "envMap", { get: function() { return this.uniforms.tCube.value; } }); this.tCube = tCube; this.opacity = opacity; this.cubeScene = new Scene(); this.cubeCamera = new PerspectiveCamera(); this.cubeScene.add(this.cubeMesh); } render(renderer, writeBuffer, readBuffer) { const oldAutoClear = renderer.autoClear; renderer.autoClear = false; this.cubeCamera.projectionMatrix.copy(this.camera.projectionMatrix); this.cubeCamera.quaternion.setFromRotationMatrix(this.camera.matrixWorld); this.cubeMesh.material.uniforms.tCube.value = this.tCube; this.cubeMesh.material.uniforms.tFlip.value = this.tCube.isCubeTexture && this.tCube.isRenderTargetTexture === false ? -1 : 1; this.cubeMesh.material.uniforms.opacity.value = this.opacity; this.cubeMesh.material.transparent = this.opacity < 1; renderer.setRenderTarget(this.renderToScreen ? null : readBuffer); if (this.clear) renderer.clear(); renderer.render(this.cubeScene, this.cubeCamera); renderer.autoClear = oldAutoClear; } dispose() { this.cubeMesh.geometry.dispose(); this.cubeMesh.material.dispose(); } }; //#endregion //#region 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: /* @__PURE__ */ new Vector2(512, 512) }, cameraNear: { value: 1 }, cameraFar: { value: 100 }, cameraProjectionMatrix: { value: /* @__PURE__ */ new Matrix4() }, cameraInverseProjectionMatrix: { value: /* @__PURE__ */ new Matrix4() }, scale: { value: 1 }, intensity: { value: .1 }, bias: { value: .5 }, minResolution: { value: 0 }, kernelRadius: { value: 100 }, randomSeed: { value: 0 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` #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; } ` }; //#endregion //#region 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: /* @__PURE__ */ new Vector2(512, 512) }, sampleUvOffsets: { value: [/* @__PURE__ */ new Vector2(0, 0)] }, sampleWeights: { value: [1] }, tDepth: { value: null }, cameraNear: { value: 10 }, cameraFar: { value: 1e3 }, depthCutoff: { value: 10 } }, vertexShader: ` #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: ` #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 i = 0; i <= kernelRadius; i++) weights.push(gaussian(i, stdDev)); return weights; }, createSampleOffsets: (kernelRadius, uvIncrement) => { const offsets = []; for (let i = 0; i <= kernelRadius; i++) offsets.push(uvIncrement.clone().multiplyScalar(i)); 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; } }; //#endregion //#region node_modules/three-stdlib/postprocessing/SAOPass.js var __defProp$17 = Object.defineProperty; var __defNormalProp$17 = (obj, key, value) => key in obj ? __defProp$17(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$17 = (obj, key, value) => { __defNormalProp$17(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var SAOPass = /* @__PURE__ */ (() => { 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: .5, saoIntensity: .18, saoScale: 1, saoKernelRadius: 100, saoMinResolution: 0, saoBlur: true, saoBlurRadius: 8, saoBlurStdDev: 4, saoBlurDepthCutoff: .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 = 0; this.normalMaterial = new MeshNormalMaterial(); this.normalMaterial.blending = 0; 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 = 0; 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 = 0; 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 = 0; this.materialCopy = new ShaderMaterial({ uniforms: UniformsUtils.clone(CopyShader.uniforms), vertexShader: CopyShader.vertexShader, fragmentShader: CopyShader.fragmentShader, blending: 0 }); this.materialCopy.transparent = true; this.materialCopy.depthTest = false; this.materialCopy.depthWrite = false; this.materialCopy.blending = 5; this.materialCopy.blendSrc = 208; this.materialCopy.blendDst = 200; this.materialCopy.blendEquation = 100; this.materialCopy.blendSrcAlpha = 206; this.materialCopy.blendDstAlpha = 200; this.materialCopy.blendEquationAlpha = 100; this.depthCopy = new ShaderMaterial({ uniforms: UniformsUtils.clone(UnpackDepthRGBAShader.uniforms), vertexShader: UnpackDepthRGBAShader.vertexShader, fragmentShader: UnpackDepthRGBAShader.fragmentShader, blending: 0 }); this.fsQuad = new FullScreenQuad(null); } render(renderer, writeBuffer, readBuffer) { if (this.renderToScreen) { this.materialCopy.blending = 0; 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 = 5; else outputMaterial.blending = 0; 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(); } } __publicField$17(SAOPass2, "OUTPUT", { Beauty: 1, Default: 0, SAO: 2, Depth: 3, Normal: 4 }); return SAOPass2; })(); //#endregion //#region node_modules/three-stdlib/shaders/AfterimageShader.js var AfterimageShader = { uniforms: { damp: { value: .96 }, tOld: { value: null }, tNew: { value: null } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform float damp; uniform sampler2D tOld; uniform sampler2D tNew; varying vec2 vUv; vec4 when_gt( vec4 x, float y ) { return max( sign( x - y ), 0.0 ); } void main() { vec4 texelOld = texture2D( tOld, vUv ); vec4 texelNew = texture2D( tNew, vUv ); texelOld *= damp * when_gt( texelOld, 0.1 ); gl_FragColor = max(texelNew, texelOld); } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/AfterimagePass.js var __defProp$16 = Object.defineProperty; var __defNormalProp$16 = (obj, key, value) => key in obj ? __defProp$16(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$16 = (obj, key, value) => { __defNormalProp$16(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var AfterimagePass = class extends Pass { constructor(damp = .96, shader = AfterimageShader) { super(); __publicField$16(this, "shader"); __publicField$16(this, "uniforms"); __publicField$16(this, "textureComp"); __publicField$16(this, "textureOld"); __publicField$16(this, "shaderMaterial"); __publicField$16(this, "compFsQuad"); __publicField$16(this, "copyFsQuad"); this.shader = shader; this.uniforms = UniformsUtils.clone(shader.uniforms); this.uniforms["damp"].value = damp; this.textureComp = new WebGLRenderTarget(window.innerWidth, window.innerHeight, { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }); this.textureOld = new WebGLRenderTarget(window.innerWidth, window.innerHeight, { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }); this.shaderMaterial = new ShaderMaterial({ uniforms: this.uniforms, vertexShader: this.shader.vertexShader, fragmentShader: this.shader.fragmentShader }); this.compFsQuad = new FullScreenQuad(this.shaderMaterial); let material = new MeshBasicMaterial(); this.copyFsQuad = new FullScreenQuad(material); } render(renderer, writeBuffer, readBuffer) { this.uniforms["tOld"].value = this.textureOld.texture; this.uniforms["tNew"].value = readBuffer.texture; renderer.setRenderTarget(this.textureComp); this.compFsQuad.render(renderer); this.copyFsQuad.material.map = this.textureComp.texture; if (this.renderToScreen) { renderer.setRenderTarget(null); this.copyFsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); this.copyFsQuad.render(renderer); } let temp = this.textureOld; this.textureOld = this.textureComp; this.textureComp = temp; } setSize(width, height) { this.textureComp.setSize(width, height); this.textureOld.setSize(width, height); } }; //#endregion //#region node_modules/three-stdlib/postprocessing/MaskPass.js var __defProp$15 = Object.defineProperty; var __defNormalProp$15 = (obj, key, value) => key in obj ? __defProp$15(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$15 = (obj, key, value) => { __defNormalProp$15(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var MaskPass = class extends Pass { constructor(scene, camera) { super(); __publicField$15(this, "scene"); __publicField$15(this, "camera"); __publicField$15(this, "inverse"); this.scene = scene; this.camera = camera; this.clear = true; this.needsSwap = false; this.inverse = false; } render(renderer, writeBuffer, readBuffer) { const context = 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(context.REPLACE, context.REPLACE, context.REPLACE); state.buffers.stencil.setFunc(context.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(context.EQUAL, 1, 4294967295); state.buffers.stencil.setOp(context.KEEP, context.KEEP, context.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); } }; //#endregion //#region node_modules/three-stdlib/postprocessing/EffectComposer.js var __defProp$14 = Object.defineProperty; var __defNormalProp$14 = (obj, key, value) => key in obj ? __defProp$14(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$14 = (obj, key, value) => { __defNormalProp$14(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var EffectComposer = class { constructor(renderer, renderTarget) { __publicField$14(this, "renderer"); __publicField$14(this, "_pixelRatio"); __publicField$14(this, "_width"); __publicField$14(this, "_height"); __publicField$14(this, "renderTarget1"); __publicField$14(this, "renderTarget2"); __publicField$14(this, "writeBuffer"); __publicField$14(this, "readBuffer"); __publicField$14(this, "renderToScreen"); __publicField$14(this, "passes", []); __publicField$14(this, "copyPass"); __publicField$14(this, "clock"); this.renderer = renderer; if (renderTarget === void 0) { const parameters = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }; const size = renderer.getSize(new Vector2()); this._pixelRatio = renderer.getPixelRatio(); this._width = size.width; this._height = size.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 = 0; 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, index) { this.passes.splice(index, 0, pass); pass.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio); } removePass(pass) { const index = this.passes.indexOf(pass); if (index !== -1) this.passes.splice(index, 1); } isLastEnabledPass(passIndex) { for (let i = passIndex + 1; i < this.passes.length; i++) if (this.passes[i].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 i = 0; i < il; i++) { const pass = this.passes[i]; if (pass.enabled === false) continue; pass.renderToScreen = this.renderToScreen && this.isLastEnabledPass(i); pass.render(this.renderer, this.writeBuffer, this.readBuffer, deltaTime, maskActive); if (pass.needsSwap) { if (maskActive) { const context = this.renderer.getContext(); const stencil = this.renderer.state.buffers.stencil; stencil.setFunc(context.NOTEQUAL, 1, 4294967295); this.copyPass.render(this.renderer, this.writeBuffer, this.readBuffer, deltaTime); stencil.setFunc(context.EQUAL, 1, 4294967295); } this.swapBuffers(); } if (MaskPass !== void 0) { if (pass instanceof MaskPass) maskActive = true; else if (pass instanceof ClearMaskPass) maskActive = false; } } this.renderer.setRenderTarget(currentRenderTarget); } reset(renderTarget) { if (renderTarget === void 0) { const size = this.renderer.getSize(new Vector2()); this._pixelRatio = this.renderer.getPixelRatio(); this._width = size.width; this._height = size.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 i = 0; i < this.passes.length; i++) this.passes[i].setSize(effectiveWidth, effectiveHeight); } setPixelRatio(pixelRatio) { this._pixelRatio = pixelRatio; this.setSize(this._width, this._height); } dispose() { this.renderTarget1.dispose(); this.renderTarget2.dispose(); this.copyPass.dispose(); } }; //#endregion //#region node_modules/three-stdlib/shaders/DotScreenShader.js var DotScreenShader = { uniforms: { tDiffuse: { value: null }, tSize: { value: /* @__PURE__ */ new Vector2(256, 256) }, center: { value: /* @__PURE__ */ new Vector2(.5, .5) }, angle: { value: 1.57 }, scale: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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 ); } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/DotScreenPass.js var __defProp$13 = Object.defineProperty; var __defNormalProp$13 = (obj, key, value) => key in obj ? __defProp$13(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$13 = (obj, key, value) => { __defNormalProp$13(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var DotScreenPass = class extends Pass { constructor(center, angle, scale) { super(); __publicField$13(this, "material"); __publicField$13(this, "fsQuad"); __publicField$13(this, "uniforms"); if (DotScreenShader === void 0) console.error("THREE.DotScreenPass relies on THREE.DotScreenShader"); const shader = DotScreenShader; this.uniforms = UniformsUtils.clone(shader.uniforms); if (center !== void 0) this.uniforms["center"].value.copy(center); if (angle !== void 0) this.uniforms["angle"].value = angle; if (scale !== void 0) this.uniforms["scale"].value = scale; this.material = new ShaderMaterial({ uniforms: this.uniforms, vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }); this.fsQuad = new FullScreenQuad(this.material); } render(renderer, writeBuffer, readBuffer) { this.uniforms["tDiffuse"].value = readBuffer.texture; this.uniforms["tSize"].value.set(readBuffer.width, readBuffer.height); if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); } } }; //#endregion //#region 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: /* @__PURE__ */ new Vector2() }, cameraProjectionMatrix: { value: /* @__PURE__ */ new Matrix4() }, cameraInverseProjectionMatrix: { value: /* @__PURE__ */ new Matrix4() }, opacity: { value: .5 }, maxDistance: { value: 180 }, cameraRange: { value: 0 }, surfDist: { value: .007 }, thickTolerance: { value: .03 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` // 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: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDepth; uniform float cameraNear; uniform float cameraFar; varying vec2 vUv; #include 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: /* @__PURE__ */ new Vector2() }, opacity: { value: .5 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform vec2 resolution; varying vec2 vUv; void main() { //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); } ` }; //#endregion //#region node_modules/three-stdlib/postprocessing/SSRPass.js var __defProp$12 = Object.defineProperty; var __defNormalProp$12 = (obj, key, value) => key in obj ? __defProp$12(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$12 = (obj, key, value) => { __defNormalProp$12(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var SSRPass = /* @__PURE__ */ (() => { 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: 0 }); 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 = 0; 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: 0 }); 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: 204, blendDst: 205, blendEquation: 100, blendSrcAlpha: 204, blendDstAlpha: 205, blendEquationAlpha: 100 }); 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 = 0; 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 = 1; this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); this.copyMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture; this.copyMaterial.blending = 0; this.renderPass(renderer, this.copyMaterial, this.renderToScreen ? null : writeBuffer); } else { this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; this.copyMaterial.blending = 0; 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 = 1; 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 = 0; 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 = 0; this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; this.copyMaterial.blending = 1; this.renderPass(renderer, this.copyMaterial, this.prevRenderTarget); } break; case _SSRPass.OUTPUT.Beauty: this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; this.copyMaterial.blending = 0; 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 = 0; 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 = 0; 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; __publicField$12(SSRPass2, "OUTPUT", { Default: 0, SSR: 1, Beauty: 3, Depth: 4, Normal: 5, Metalness: 7 }); return SSRPass2; })(); //#endregion //#region node_modules/three-stdlib/postprocessing/SSAARenderPass.js var SSAARenderPass = class extends Pass { constructor(scene, camera, clearColor, clearAlpha) { super(); this.scene = scene; this.camera = camera; this.sampleLevel = 4; this.unbiased = true; this.clearColor = clearColor !== void 0 ? clearColor : 0; this.clearAlpha = clearAlpha !== void 0 ? clearAlpha : 0; this._oldClearColor = new Color(); const copyShader = CopyShader; this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); this.copyMaterial = new ShaderMaterial({ uniforms: this.copyUniforms, vertexShader: copyShader.vertexShader, fragmentShader: copyShader.fragmentShader, transparent: true, depthTest: false, depthWrite: false, premultipliedAlpha: true, blending: 2 }); this.fsQuad = new FullScreenQuad(this.copyMaterial); } dispose() { if (this.sampleRenderTarget) { this.sampleRenderTarget.dispose(); this.sampleRenderTarget = null; } this.copyMaterial.dispose(); this.fsQuad.dispose(); } setSize(width, height) { if (this.sampleRenderTarget) this.sampleRenderTarget.setSize(width, height); } render(renderer, writeBuffer, readBuffer) { if (!this.sampleRenderTarget) { this.sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, { type: HalfFloatType }); this.sampleRenderTarget.texture.name = "SSAARenderPass.sample"; } const jitterOffsets = _JitterVectors$1[Math.max(0, Math.min(this.sampleLevel, 5))]; const autoClear = renderer.autoClear; renderer.autoClear = false; renderer.getClearColor(this._oldClearColor); const oldClearAlpha = renderer.getClearAlpha(); const baseSampleWeight = 1 / jitterOffsets.length; const roundingRange = 1 / 32; this.copyUniforms["tDiffuse"].value = this.sampleRenderTarget.texture; const viewOffset = { fullWidth: readBuffer.width, fullHeight: readBuffer.height, offsetX: 0, offsetY: 0, width: readBuffer.width, height: readBuffer.height }; const originalViewOffset = Object.assign({}, this.camera.view); if (originalViewOffset.enabled) Object.assign(viewOffset, originalViewOffset); for (let i = 0; i < jitterOffsets.length; i++) { const jitterOffset = jitterOffsets[i]; if (this.camera.setViewOffset) this.camera.setViewOffset(viewOffset.fullWidth, viewOffset.fullHeight, viewOffset.offsetX + jitterOffset[0] * .0625, viewOffset.offsetY + jitterOffset[1] * .0625, viewOffset.width, viewOffset.height); let sampleWeight = baseSampleWeight; if (this.unbiased) { const uniformCenteredDistribution = -.5 + (i + .5) / jitterOffsets.length; sampleWeight += roundingRange * uniformCenteredDistribution; } this.copyUniforms["opacity"].value = sampleWeight; renderer.setClearColor(this.clearColor, this.clearAlpha); renderer.setRenderTarget(this.sampleRenderTarget); renderer.clear(); renderer.render(this.scene, this.camera); renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer); if (i === 0) { renderer.setClearColor(0, 0); renderer.clear(); } this.fsQuad.render(renderer); } if (this.camera.setViewOffset && originalViewOffset.enabled) this.camera.setViewOffset(originalViewOffset.fullWidth, originalViewOffset.fullHeight, originalViewOffset.offsetX, originalViewOffset.offsetY, originalViewOffset.width, originalViewOffset.height); else if (this.camera.clearViewOffset) this.camera.clearViewOffset(); renderer.autoClear = autoClear; renderer.setClearColor(this._oldClearColor, oldClearAlpha); } }; var _JitterVectors$1 = [ [[0, 0]], [[4, 4], [-4, -4]], [ [-2, -6], [6, -2], [-6, 2], [2, 6] ], [ [1, -3], [-1, 3], [5, 1], [-3, -5], [-5, 5], [-7, -1], [3, 7], [7, -7] ], [ [1, 1], [-1, -3], [-3, 2], [4, -1], [-5, -2], [2, 5], [5, 3], [3, -5], [-2, 6], [0, -7], [-4, -6], [-6, 4], [-8, 0], [7, -4], [6, 7], [-7, -8] ], [ [-4, -7], [-7, -5], [-3, -5], [-5, -4], [-1, -4], [-2, -2], [-6, -1], [-4, 0], [-7, 1], [-1, 2], [-6, 3], [-3, 3], [-7, 6], [-3, 6], [-5, 7], [-1, 7], [5, -7], [1, -6], [6, -5], [4, -4], [2, -3], [7, -2], [1, -1], [4, -1], [2, 1], [6, 2], [0, 4], [4, 4], [2, 5], [7, 5], [5, 6], [3, 7] ] ]; //#endregion //#region node_modules/three-stdlib/postprocessing/TAARenderPass.js var TAARenderPass = class extends SSAARenderPass { constructor(scene, camera, clearColor, clearAlpha) { super(scene, camera, clearColor, clearAlpha); this.sampleLevel = 0; this.accumulate = false; this.accumulateIndex = -1; } render(renderer, writeBuffer, readBuffer, deltaTime) { if (this.accumulate === false) { super.render(renderer, writeBuffer, readBuffer, deltaTime); this.accumulateIndex = -1; return; } const jitterOffsets = _JitterVectors[5]; if (this.sampleRenderTarget === void 0) { this.sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, { type: HalfFloatType }); this.sampleRenderTarget.texture.name = "TAARenderPass.sample"; } if (this.holdRenderTarget === void 0) { this.holdRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, { type: HalfFloatType }); this.holdRenderTarget.texture.name = "TAARenderPass.hold"; } if (this.accumulateIndex === -1) { super.render(renderer, this.holdRenderTarget, readBuffer, deltaTime); this.accumulateIndex = 0; } const autoClear = renderer.autoClear; renderer.autoClear = false; renderer.getClearColor(this._oldClearColor); const oldClearAlpha = renderer.getClearAlpha(); const sampleWeight = 1 / jitterOffsets.length; if (this.accumulateIndex >= 0 && this.accumulateIndex < jitterOffsets.length) { this.copyUniforms["opacity"].value = sampleWeight; this.copyUniforms["tDiffuse"].value = writeBuffer.texture; const numSamplesPerFrame = Math.pow(2, this.sampleLevel); for (let i = 0; i < numSamplesPerFrame; i++) { const jitterOffset = jitterOffsets[this.accumulateIndex]; if (this.camera.setViewOffset) this.camera.setViewOffset(readBuffer.width, readBuffer.height, jitterOffset[0] * .0625, jitterOffset[1] * .0625, readBuffer.width, readBuffer.height); renderer.setRenderTarget(writeBuffer); renderer.setClearColor(this.clearColor, this.clearAlpha); renderer.clear(); renderer.render(this.scene, this.camera); renderer.setRenderTarget(this.sampleRenderTarget); if (this.accumulateIndex === 0) { renderer.setClearColor(0, 0); renderer.clear(); } this.fsQuad.render(renderer); this.accumulateIndex++; if (this.accumulateIndex >= jitterOffsets.length) break; } if (this.camera.clearViewOffset) this.camera.clearViewOffset(); } renderer.setClearColor(this.clearColor, this.clearAlpha); const accumulationWeight = this.accumulateIndex * sampleWeight; if (accumulationWeight > 0) { this.copyUniforms["opacity"].value = 1; this.copyUniforms["tDiffuse"].value = this.sampleRenderTarget.texture; renderer.setRenderTarget(writeBuffer); renderer.clear(); this.fsQuad.render(renderer); } if (accumulationWeight < 1) { this.copyUniforms["opacity"].value = 1 - accumulationWeight; this.copyUniforms["tDiffuse"].value = this.holdRenderTarget.texture; renderer.setRenderTarget(writeBuffer); this.fsQuad.render(renderer); } renderer.autoClear = autoClear; renderer.setClearColor(this._oldClearColor, oldClearAlpha); } dispose() { super.dispose(); if (this.sampleRenderTarget !== void 0) this.sampleRenderTarget.dispose(); if (this.holdRenderTarget !== void 0) this.holdRenderTarget.dispose(); } }; var _JitterVectors = [ [[0, 0]], [[4, 4], [-4, -4]], [ [-2, -6], [6, -2], [-6, 2], [2, 6] ], [ [1, -3], [-1, 3], [5, 1], [-3, -5], [-5, 5], [-7, -1], [3, 7], [7, -7] ], [ [1, 1], [-1, -3], [-3, 2], [4, -1], [-5, -2], [2, 5], [5, 3], [3, -5], [-2, 6], [0, -7], [-4, -6], [-6, 4], [-8, 0], [7, -4], [6, 7], [-7, -8] ], [ [-4, -7], [-7, -5], [-3, -5], [-5, -4], [-1, -4], [-2, -2], [-6, -1], [-4, 0], [-7, 1], [-1, 2], [-6, 3], [-3, 3], [-7, 6], [-3, 6], [-5, 7], [-1, 7], [5, -7], [1, -6], [6, -5], [4, -4], [2, -3], [7, -2], [1, -1], [4, -1], [2, 1], [6, 2], [0, 4], [4, 4], [2, 5], [7, 5], [5, 6], [3, 7] ] ]; //#endregion //#region node_modules/three-stdlib/postprocessing/RenderPass.js var __defProp$11 = Object.defineProperty; var __defNormalProp$11 = (obj, key, value) => key in obj ? __defProp$11(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$11 = (obj, key, value) => { __defNormalProp$11(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var RenderPass = class extends Pass { constructor(scene, camera, overrideMaterial, clearColor, clearAlpha = 0) { super(); __publicField$11(this, "scene"); __publicField$11(this, "camera"); __publicField$11(this, "overrideMaterial"); __publicField$11(this, "clearColor"); __publicField$11(this, "clearAlpha"); __publicField$11(this, "clearDepth", false); __publicField$11(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; } }; //#endregion //#region node_modules/three-stdlib/postprocessing/RenderPixelatedPass.js var RenderPixelatedPass = class extends Pass { constructor(resolution, pixelSize, scene, camera, options = {}) { var _a, _b; super(); this.pixelSize = pixelSize; this.resolution = new Vector2(); this.renderResolution = new Vector2(); this.setSize(resolution.x, resolution.y); this.fsQuad = new FullScreenQuad(this.material()); this.scene = scene; this.camera = camera; this.normalEdgeStrength = (_a = options.normalEdgeStrength) != null ? _a : .3; this.depthEdgeStrength = (_b = options.depthEdgeStrength) != null ? _b : .4; this.rgbRenderTarget = pixelRenderTarget(this.renderResolution, RGBAFormat, true); this.normalRenderTarget = pixelRenderTarget(this.renderResolution, RGBAFormat, false); this.normalMaterial = new MeshNormalMaterial(); } dispose() { this.rgbRenderTarget.dispose(); this.normalRenderTarget.dispose(); this.fsQuad.dispose(); } setSize(width, height) { var _a, _b, _c; this.resolution.set(width, height); this.renderResolution.set(width / this.pixelSize | 0, height / this.pixelSize | 0); const { x, y } = this.renderResolution; (_a = this.rgbRenderTarget) == null || _a.setSize(x, y); (_b = this.normalRenderTarget) == null || _b.setSize(x, y); (_c = this.fsQuad) == null || _c.material.uniforms.resolution.value.set(x, y, 1 / x, 1 / y); } setPixelSize(pixelSize) { this.pixelSize = pixelSize; this.setSize(this.resolution.x, this.resolution.y); } render(renderer, writeBuffer) { const uniforms = this.fsQuad.material.uniforms; uniforms.normalEdgeStrength.value = this.normalEdgeStrength; uniforms.depthEdgeStrength.value = this.depthEdgeStrength; renderer.setRenderTarget(this.rgbRenderTarget); renderer.render(this.scene, this.camera); const overrideMaterial_old = this.scene.overrideMaterial; renderer.setRenderTarget(this.normalRenderTarget); this.scene.overrideMaterial = this.normalMaterial; renderer.render(this.scene, this.camera); this.scene.overrideMaterial = overrideMaterial_old; uniforms.tDiffuse.value = this.rgbRenderTarget.texture; uniforms.tDepth.value = this.rgbRenderTarget.depthTexture; uniforms.tNormal.value = this.normalRenderTarget.texture; if (this.renderToScreen) renderer.setRenderTarget(null); else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); } this.fsQuad.render(renderer); } material() { return new ShaderMaterial({ uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, tNormal: { value: null }, resolution: { value: new Vector4(this.renderResolution.x, this.renderResolution.y, 1 / this.renderResolution.x, 1 / this.renderResolution.y) }, normalEdgeStrength: { value: 0 }, depthEdgeStrength: { value: 0 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform sampler2D tNormal; uniform vec4 resolution; uniform float normalEdgeStrength; uniform float depthEdgeStrength; varying vec2 vUv; float getDepth(int x, int y) { return texture2D( tDepth, vUv + vec2(x, y) * resolution.zw ).r; } vec3 getNormal(int x, int y) { return texture2D( tNormal, vUv + vec2(x, y) * resolution.zw ).rgb * 2.0 - 1.0; } float depthEdgeIndicator(float depth, vec3 normal) { float diff = 0.0; diff += clamp(getDepth(1, 0) - depth, 0.0, 1.0); diff += clamp(getDepth(-1, 0) - depth, 0.0, 1.0); diff += clamp(getDepth(0, 1) - depth, 0.0, 1.0); diff += clamp(getDepth(0, -1) - depth, 0.0, 1.0); return floor(smoothstep(0.01, 0.02, diff) * 2.) / 2.; } float neighborNormalEdgeIndicator(int x, int y, float depth, vec3 normal) { float depthDiff = getDepth(x, y) - depth; vec3 neighborNormal = getNormal(x, y); // Edge pixels should yield to faces who's normals are closer to the bias normal. vec3 normalEdgeBias = vec3(1., 1., 1.); // This should probably be a parameter. float normalDiff = dot(normal - neighborNormal, normalEdgeBias); float normalIndicator = clamp(smoothstep(-.01, .01, normalDiff), 0.0, 1.0); // Only the shallower pixel should detect the normal edge. float depthIndicator = clamp(sign(depthDiff * .25 + .0025), 0.0, 1.0); return (1.0 - dot(normal, neighborNormal)) * depthIndicator * normalIndicator; } float normalEdgeIndicator(float depth, vec3 normal) { float indicator = 0.0; indicator += neighborNormalEdgeIndicator(0, -1, depth, normal); indicator += neighborNormalEdgeIndicator(0, 1, depth, normal); indicator += neighborNormalEdgeIndicator(-1, 0, depth, normal); indicator += neighborNormalEdgeIndicator(1, 0, depth, normal); return step(0.1, indicator); } void main() { vec4 texel = texture2D( tDiffuse, vUv ); float depth = 0.0; vec3 normal = vec3(0.0); if (depthEdgeStrength > 0.0 || normalEdgeStrength > 0.0) { depth = getDepth(0, 0); normal = getNormal(0, 0); } float dei = 0.0; if (depthEdgeStrength > 0.0) dei = depthEdgeIndicator(depth, normal); float nei = 0.0; if (normalEdgeStrength > 0.0) nei = normalEdgeIndicator(depth, normal); float Strength = dei > 0.0 ? (1.0 - depthEdgeStrength * dei) : (1.0 + normalEdgeStrength * nei); gl_FragColor = texel * Strength; } ` }); } }; function pixelRenderTarget(resolution, pixelFormat, useDepthTexture) { const renderTarget = new WebGLRenderTarget(resolution.x, resolution.y, !useDepthTexture ? void 0 : { depthTexture: new DepthTexture(resolution.x, resolution.y), depthBuffer: true }); renderTarget.texture.format = pixelFormat; renderTarget.texture.minFilter = NearestFilter; renderTarget.texture.magFilter = NearestFilter; renderTarget.texture.generateMipmaps = false; renderTarget.stencilBuffer = false; return renderTarget; } //#endregion //#region 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: /* @__PURE__ */ new Vector2(.001953125, 0) }, cKernel: { value: [] } }, vertexShader: ` 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: ` 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 kernelSize = Math.min(2 * Math.ceil(sigma * 3) + 1, 25); const halfWidth = (kernelSize - 1) * .5; const values = new Array(kernelSize); let sum = 0; for (let i = 0; i < kernelSize; ++i) { values[i] = gauss(i - halfWidth, sigma); sum += values[i]; } for (let i = 0; i < kernelSize; ++i) values[i] /= sum; return values; } }; //#endregion //#region node_modules/three-stdlib/postprocessing/BloomPass.js var __defProp$10 = Object.defineProperty; var __defNormalProp$10 = (obj, key, value) => key in obj ? __defProp$10(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$10 = (obj, key, value) => { __defNormalProp$10(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var BloomPass = class extends Pass { constructor(strength = 1, kernelSize = 25, sigma = 4, resolution = 256) { super(); __publicField$10(this, "renderTargetX"); __publicField$10(this, "renderTargetY"); __publicField$10(this, "materialCombine"); __publicField$10(this, "materialConvolution"); __publicField$10(this, "fsQuad"); __publicField$10(this, "combineUniforms"); __publicField$10(this, "convolutionUniforms"); __publicField$10(this, "blurX", new Vector2(.001953125, 0)); __publicField$10(this, "blurY", new Vector2(0, .001953125)); this.renderTargetX = new WebGLRenderTarget(resolution, resolution); this.renderTargetX.texture.name = "BloomPass.x"; this.renderTargetY = new WebGLRenderTarget(resolution, resolution); this.renderTargetY.texture.name = "BloomPass.y"; this.combineUniforms = UniformsUtils.clone(CombineShader.uniforms); this.combineUniforms["strength"].value = strength; this.materialCombine = new ShaderMaterial({ uniforms: this.combineUniforms, vertexShader: CombineShader.vertexShader, fragmentShader: CombineShader.fragmentShader, blending: 2, transparent: true }); if (ConvolutionShader === void 0) console.error("BloomPass relies on ConvolutionShader"); const convolutionShader = ConvolutionShader; this.convolutionUniforms = UniformsUtils.clone(convolutionShader.uniforms); this.convolutionUniforms["uImageIncrement"].value = this.blurX; this.convolutionUniforms["cKernel"].value = ConvolutionShader.buildKernel(sigma); this.materialConvolution = new ShaderMaterial({ uniforms: this.convolutionUniforms, vertexShader: convolutionShader.vertexShader, fragmentShader: convolutionShader.fragmentShader, defines: { KERNEL_SIZE_FLOAT: kernelSize.toFixed(1), KERNEL_SIZE_INT: kernelSize.toFixed(0) } }); this.needsSwap = false; this.fsQuad = new FullScreenQuad(this.materialConvolution); } render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) { if (maskActive) renderer.state.buffers.stencil.setTest(false); this.fsQuad.material = this.materialConvolution; this.convolutionUniforms["tDiffuse"].value = readBuffer.texture; this.convolutionUniforms["uImageIncrement"].value = this.blurX; renderer.setRenderTarget(this.renderTargetX); renderer.clear(); this.fsQuad.render(renderer); this.convolutionUniforms["tDiffuse"].value = this.renderTargetX.texture; this.convolutionUniforms["uImageIncrement"].value = this.blurY; renderer.setRenderTarget(this.renderTargetY); renderer.clear(); this.fsQuad.render(renderer); this.fsQuad.material = this.materialCombine; this.combineUniforms["tDiffuse"].value = this.renderTargetY.texture; if (maskActive) renderer.state.buffers.stencil.setTest(true); renderer.setRenderTarget(readBuffer); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); } }; var CombineShader = { uniforms: { tDiffuse: { value: null }, strength: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`, fragmentShader: ` uniform float strength; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = strength * texel; }` }; //#endregion //#region node_modules/three-stdlib/postprocessing/WaterPass.js var __defProp$9 = Object.defineProperty; var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$9 = (obj, key, value) => { __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var WaterPass = class extends Pass { constructor() { super(); __publicField$9(this, "material"); __publicField$9(this, "fsQuad"); __publicField$9(this, "factor"); __publicField$9(this, "time"); __publicField$9(this, "uniforms"); this.uniforms = { tex: { value: null }, time: { value: 0 }, factor: { value: 0 }, resolution: { value: new Vector2(64, 64) } }; this.material = new ShaderMaterial({ uniforms: this.uniforms, vertexShader: ` varying vec2 vUv; void main(){ vUv = uv; vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0); gl_Position = projectionMatrix * modelViewPosition; }`, fragmentShader: ` uniform float time; uniform float factor; uniform vec2 resolution; uniform sampler2D tex; varying vec2 vUv; void main() { vec2 uv1 = vUv; vec2 uv = gl_FragCoord.xy/resolution.xy; float frequency = 6.0 * factor; float amplitude = 0.015 * factor; float x = uv1.y * frequency + time * .7; float y = uv1.x * frequency + time * .3; uv1.x += cos(x+y) * amplitude * cos(y); uv1.y += sin(x-y) * amplitude * cos(y); vec4 rgba = texture2D(tex, uv1); gl_FragColor = rgba; }` }); this.fsQuad = new FullScreenQuad(this.material); this.factor = 0; this.time = 0; } render(renderer, writeBuffer, readBuffer) { this.uniforms["tex"].value = readBuffer.texture; this.uniforms["time"].value = this.time; this.uniforms["factor"].value = this.factor; if (this.renderToScreen) { renderer.setRenderTarget(null); this.fsQuad.render(renderer); } else { renderer.setRenderTarget(writeBuffer); if (this.clear) renderer.clear(); this.fsQuad.render(renderer); } } }; //#endregion //#region node_modules/three-stdlib/webxr/ARButton.js var ARButton = { createButton(renderer, sessionInit = {}) { const button = document.createElement("button"); function showStartAR() { if (sessionInit.domOverlay === void 0) { const overlay = document.createElement("div"); overlay.style.display = "none"; document.body.appendChild(overlay); const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.setAttribute("width", "38px"); svg.setAttribute("height", "38px"); svg.style.position = "absolute"; svg.style.right = "20px"; svg.style.top = "20px"; svg.addEventListener("click", function() { currentSession?.end(); }); overlay.appendChild(svg); const path = document.createElementNS("http://www.w3.org/2000/svg", "path"); path.setAttribute("d", "M 12,12 L 28,28 M 28,12 12,28"); path.setAttribute("stroke", "#fff"); path.setAttribute("stroke-width", "2px"); svg.appendChild(path); if (sessionInit.optionalFeatures === void 0) sessionInit.optionalFeatures = []; sessionInit.optionalFeatures.push("dom-overlay"); sessionInit.domOverlay = { root: overlay }; } let currentSession = null; async function onSessionStarted(session) { session.addEventListener("end", onSessionEnded); renderer.xr.setReferenceSpaceType("local"); await renderer.xr.setSession(session); button.textContent = "STOP AR"; sessionInit.domOverlay.root.style.display = ""; currentSession = session; } function onSessionEnded() { currentSession.removeEventListener("end", onSessionEnded); button.textContent = "START AR"; sessionInit.domOverlay.root.style.display = "none"; currentSession = null; } button.style.display = ""; button.style.cursor = "pointer"; button.style.left = "calc(50% - 50px)"; button.style.width = "100px"; button.textContent = "START AR"; button.onmouseenter = () => { button.style.opacity = "1.0"; }; button.onmouseleave = () => { button.style.opacity = "0.5"; }; button.onclick = () => { if (currentSession === null) navigator.xr.requestSession("immersive-ar", sessionInit).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 showARNotSupported() { disableButton(); button.textContent = "AR 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) { button.id = "ARButton"; button.style.display = "none"; stylizeElement(button); navigator.xr.isSessionSupported("immersive-ar").then(function(supported) { supported ? showStartAR() : showARNotSupported(); }).catch(showARNotSupported); 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; } } }; //#endregion //#region node_modules/three-stdlib/_polyfill/LoaderUtils.js function decodeText$1(array) { if (typeof TextDecoder !== "undefined") return new TextDecoder().decode(array); let s = ""; for (let i = 0, il = array.length; i < il; i++) s += String.fromCharCode(array[i]); try { return decodeURIComponent(escape(s)); } catch (e) { return s; } } //#endregion //#region node_modules/three-stdlib/loaders/GLTFLoader.js var SRGBColorSpace$1 = "srgb"; var LinearSRGBColorSpace$1 = "srgb-linear"; var sRGBEncoding$1 = 3001; var LinearEncoding$1 = 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 GLTFMaterialsClearcoatExtension(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 GLTFMaterialsSheenExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsTransmissionExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsVolumeExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsIorExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsEmissiveStrengthExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsSpecularExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsIridescenceExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsAnisotropyExtension(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(e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); scope.manager.itemEnd(url); }; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function(data) { try { scope.parse(data, resourcePath, function(gltf) { onLoad(gltf); scope.manager.itemEnd(url); }, _onError); } catch (e) { _onError(e); } }, onProgress, _onError); } setDRACOLoader(dracoLoader) { this.dracoLoader = dracoLoader; 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 extensions = {}; const plugins = {}; if (typeof data === "string") json = JSON.parse(data); else if (data instanceof ArrayBuffer) if (decodeText$1(new Uint8Array(data.slice(0, 4))) === BINARY_EXTENSION_HEADER_MAGIC) { try { extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data); } catch (error) { if (onError) onError(error); return; } json = JSON.parse(extensions[EXTENSIONS.KHR_BINARY_GLTF].content); } else json = JSON.parse(decodeText$1(new Uint8Array(data))); else json = data; if (json.asset === void 0 || json.asset.version[0] < 2) { if (onError) onError(/* @__PURE__ */ new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")); return; } const parser = new GLTFParser(json, { path: path || this.resourcePath || "", crossOrigin: this.crossOrigin, requestHeader: this.requestHeader, manager: this.manager, ktx2Loader: this.ktx2Loader, meshoptDecoder: this.meshoptDecoder }); parser.fileLoader.setRequestHeader(this.requestHeader); for (let i = 0; i < this.pluginCallbacks.length; i++) { const plugin = this.pluginCallbacks[i](parser); if (!plugin.name) console.error("THREE.GLTFLoader: Invalid plugin found: missing name"); plugins[plugin.name] = plugin; extensions[plugin.name] = true; } if (json.extensionsUsed) for (let i = 0; i < json.extensionsUsed.length; ++i) { const extensionName = json.extensionsUsed[i]; const extensionsRequired = json.extensionsRequired || []; switch (extensionName) { case EXTENSIONS.KHR_MATERIALS_UNLIT: extensions[extensionName] = new GLTFMaterialsUnlitExtension(); break; case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader); break; case EXTENSIONS.KHR_TEXTURE_TRANSFORM: extensions[extensionName] = new GLTFTextureTransformExtension(); break; case EXTENSIONS.KHR_MESH_QUANTIZATION: extensions[extensionName] = new GLTFMeshQuantizationExtension(); break; default: if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === void 0) console.warn("THREE.GLTFLoader: Unknown extension \"" + extensionName + "\"."); } } parser.setExtensions(extensions); parser.setPlugins(plugins); parser.parse(onLoad, onError); } 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 lightDef = ((json.extensions && json.extensions[this.name] || {}).lights || [])[lightIndex]; let lightNode; const color = new Color(16777215); if (lightDef.color !== void 0) color.setRGB(lightDef.color[0], lightDef.color[1], lightDef.color[2], LinearSRGBColorSpace$1); 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, index) { if (type !== "light") return; return this._loadLight(index); } createNodeAttachment(nodeIndex) { const self2 = this; const parser = this.parser; const nodeDef = parser.json.nodes[nodeIndex]; const lightIndex = (nodeDef.extensions && nodeDef.extensions[this.name] || {}).light; if (lightIndex === void 0) return null; return this._loadLight(lightIndex).then(function(light) { return parser._getNodeRef(self2.cache, lightIndex, light); }); } }; var GLTFMaterialsUnlitExtension = class { constructor() { this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } getMaterialType() { return MeshBasicMaterial; } extendParams(materialParams, materialDef, parser) { const pending = []; materialParams.color = new Color(1, 1, 1); materialParams.opacity = 1; const metallicRoughness = materialDef.pbrMetallicRoughness; if (metallicRoughness) { if (Array.isArray(metallicRoughness.baseColorFactor)) { const array = metallicRoughness.baseColorFactor; materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace$1); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== void 0) pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace$1)); } return Promise.all(pending); } }; var GLTFMaterialsEmissiveStrengthExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; } extendMaterialParams(materialIndex, materialParams) { const materialDef = this.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 GLTFMaterialsClearcoatExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; } getMaterialType(materialIndex) { const materialDef = this.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 scale = extension.clearcoatNormalTexture.scale; materialParams.clearcoatNormalScale = new Vector2(scale, scale); } } return Promise.all(pending); } }; var GLTFMaterialsDispersionExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION; } getMaterialType(materialIndex) { const materialDef = this.parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const materialDef = this.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 GLTFMaterialsIridescenceExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE; } getMaterialType(materialIndex) { const materialDef = this.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 GLTFMaterialsSheenExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; } getMaterialType(materialIndex) { const materialDef = this.parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return Promise.resolve(); const pending = []; materialParams.sheenColor = new Color(0, 0, 0); materialParams.sheenRoughness = 0; materialParams.sheen = 1; const extension = materialDef.extensions[this.name]; if (extension.sheenColorFactor !== void 0) { const colorFactor = extension.sheenColorFactor; materialParams.sheenColor.setRGB(colorFactor[0], colorFactor[1], colorFactor[2], LinearSRGBColorSpace$1); } if (extension.sheenRoughnessFactor !== void 0) materialParams.sheenRoughness = extension.sheenRoughnessFactor; if (extension.sheenColorTexture !== void 0) pending.push(parser.assignTexture(materialParams, "sheenColorMap", extension.sheenColorTexture, SRGBColorSpace$1)); if (extension.sheenRoughnessTexture !== void 0) pending.push(parser.assignTexture(materialParams, "sheenRoughnessMap", extension.sheenRoughnessTexture)); return Promise.all(pending); } }; var GLTFMaterialsTransmissionExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; } getMaterialType(materialIndex) { const materialDef = this.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 GLTFMaterialsVolumeExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; } getMaterialType(materialIndex) { const materialDef = this.parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return Promise.resolve(); const pending = []; const extension = materialDef.extensions[this.name]; materialParams.thickness = extension.thicknessFactor !== void 0 ? extension.thicknessFactor : 0; if (extension.thicknessTexture !== void 0) pending.push(parser.assignTexture(materialParams, "thicknessMap", extension.thicknessTexture)); materialParams.attenuationDistance = extension.attenuationDistance || Infinity; const colorArray = extension.attenuationColor || [ 1, 1, 1 ]; materialParams.attenuationColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace$1); return Promise.all(pending); } }; var GLTFMaterialsIorExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_IOR; } getMaterialType(materialIndex) { const materialDef = this.parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const materialDef = this.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 GLTFMaterialsSpecularExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; } getMaterialType(materialIndex) { const materialDef = this.parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return Promise.resolve(); const pending = []; const extension = materialDef.extensions[this.name]; materialParams.specularIntensity = extension.specularFactor !== void 0 ? extension.specularFactor : 1; if (extension.specularTexture !== void 0) pending.push(parser.assignTexture(materialParams, "specularIntensityMap", extension.specularTexture)); const colorArray = extension.specularColorFactor || [ 1, 1, 1 ]; materialParams.specularColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace$1); if (extension.specularColorTexture !== void 0) pending.push(parser.assignTexture(materialParams, "specularColorMap", extension.specularColorTexture, SRGBColorSpace$1)); return Promise.all(pending); } }; var GLTFMaterialsBumpExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.EXT_MATERIALS_BUMP; } getMaterialType(materialIndex) { const materialDef = this.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 GLTFMaterialsAnisotropyExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY; } getMaterialType(materialIndex) { const materialDef = this.parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return Promise.resolve(); const pending = []; const extension = materialDef.extensions[this.name]; if (extension.anisotropyStrength !== void 0) materialParams.anisotropy = extension.anisotropyStrength; if (extension.anisotropyRotation !== void 0) materialParams.anisotropyRotation = extension.anisotropyRotation; if (extension.anisotropyTexture !== void 0) pending.push(parser.assignTexture(materialParams, "anisotropyMap", extension.anisotropyTexture)); return Promise.all(pending); } }; var GLTFTextureBasisUExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_TEXTURE_BASISU; } loadTexture(textureIndex) { const parser = this.parser; const json = parser.json; const textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[this.name]) return null; const extension = textureDef.extensions[this.name]; const loader = parser.options.ktx2Loader; if (!loader) if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures"); else return null; return parser.loadTextureImage(textureIndex, extension.source, loader); } }; var GLTFTextureWebPExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.EXT_TEXTURE_WEBP; 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 loader = parser.textureLoader; if (source.uri) { const handler = parser.options.manager.getHandler(source.uri); if (handler !== null) loader = handler; } return this.detectSupport().then(function(isSupported) { if (isSupported) return parser.loadTextureImage(textureIndex, extension.source, loader); 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 loader = parser.textureLoader; if (source.uri) { const handler = parser.options.manager.getHandler(source.uri); if (handler !== null) loader = handler; } return this.detectSupport().then(function(isSupported) { if (isSupported) return parser.loadTextureImage(textureIndex, extension.source, loader); 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(index) { const json = this.parser.json; const bufferView = json.bufferViews[index]; if (bufferView.extensions && bufferView.extensions[this.name]) { const extensionDef = bufferView.extensions[this.name]; const buffer = this.parser.getDependency("buffer", extensionDef.buffer); const decoder = this.parser.options.meshoptDecoder; if (!decoder || !decoder.supported) if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files"); else return null; return buffer.then(function(res) { const byteOffset = extensionDef.byteOffset || 0; const byteLength = extensionDef.byteLength || 0; const count = extensionDef.count; const stride = extensionDef.byteStride; const source = new Uint8Array(res, byteOffset, byteLength); if (decoder.decodeGltfBufferAsync) return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function(res2) { return res2.buffer; }); else return decoder.ready.then(function() { const result = new ArrayBuffer(count * stride); decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter); return result; }); }); } else return null; } }; var 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_CONSTANTS.TRIANGLES && primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP && primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN && primitive.mode !== void 0) return null; const attributesDef = nodeDef.extensions[this.name].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 p = new Vector3(); const q = new Quaternion(); const s = new Vector3(1, 1, 1); const instancedMesh = new InstancedMesh(mesh.geometry, mesh.material, count); for (let i = 0; i < count; i++) { if (attributes.TRANSLATION) p.fromBufferAttribute(attributes.TRANSLATION, i); if (attributes.ROTATION) q.fromBufferAttribute(attributes.ROTATION, i); if (attributes.SCALE) s.fromBufferAttribute(attributes.SCALE, i); instancedMesh.setMatrixAt(i, m.compose(p, q, s)); } for (const attributeName in attributes) if (attributeName === "_COLOR_0") { const attr = attributes[attributeName]; instancedMesh.instanceColor = new InstancedBufferAttribute(attr.array, attr.itemSize, attr.normalized); } else if (attributeName !== "TRANSLATION" && attributeName !== "ROTATION" && attributeName !== "SCALE") mesh.geometry.setAttribute(attributeName, attributes[attributeName]); Object3D.prototype.copy.call(instancedMesh, mesh); this.parser.assignFinalMaterial(instancedMesh); instancedMeshes.push(instancedMesh); } if (nodeObject.isGroup) { nodeObject.clear(); nodeObject.add(...instancedMeshes); return nodeObject; } return instancedMeshes[0]; }); } }; var BINARY_EXTENSION_HEADER_MAGIC = "glTF"; var BINARY_EXTENSION_HEADER_LENGTH = 12; var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 1313821514, BIN: 5130562 }; var GLTFBinaryExtension = class { constructor(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$1(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$1(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, dracoLoader) { if (!dracoLoader) throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided."); this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader; this.dracoLoader.preload(); } decodePrimitive(primitive, parser) { const json = this.json; const dracoLoader = this.dracoLoader; const bufferViewIndex = primitive.extensions[this.name].bufferView; const gltfAttributeMap = primitive.extensions[this.name].attributes; const threeAttributeMap = {}; const attributeNormalizedMap = {}; const attributeTypeMap = {}; for (const attributeName in gltfAttributeMap) { const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]; } for (const attributeName in primitive.attributes) { const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); if (gltfAttributeMap[attributeName] !== void 0) { const accessorDef = json.accessors[primitive.attributes[attributeName]]; attributeTypeMap[threeAttributeName] = WEBGL_COMPONENT_TYPES[accessorDef.componentType].name; attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true; } } return parser.getDependency("bufferView", bufferViewIndex).then(function(bufferView) { return new Promise(function(resolve, reject) { dracoLoader.decodeDracoFile(bufferView, function(geometry) { for (const attributeName in geometry.attributes) { const attribute = geometry.attributes[attributeName]; const normalized = attributeNormalizedMap[attributeName]; if (normalized !== void 0) attribute.normalized = normalized; } resolve(geometry); }, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace$1, 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_(index) { const result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize, offset = index * valueSize * 3 + valueSize; for (let i = 0; i !== valueSize; i++) result[i] = values[offset + i]; return result; } interpolate_(i1, t0, t, t1) { const result = this.resultBuffer; const values = this.sampleValues; const stride = this.valueSize; const stride2 = stride * 2; const stride3 = stride * 3; const td = t1 - t0; const p = (t - t0) / td; const pp = p * p; const ppp = pp * p; const offset1 = i1 * stride3; const offset0 = offset1 - stride3; const s2 = -2 * ppp + 3 * pp; const s3 = ppp - pp; const s0 = 1 - s2; const s1 = s3 - pp + p; for (let i = 0; i !== stride; i++) { const p0 = values[offset0 + i + stride]; const m0 = values[offset0 + i + stride2] * td; const p1 = values[offset1 + i + stride]; const m1 = values[offset1 + i] * td; result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; } return result; } }; var _q = /* @__PURE__ */ new Quaternion(); var GLTFCubicSplineQuaternionInterpolant = class extends GLTFCubicSplineInterpolant { interpolate_(i1, t0, t, t1) { const result = super.interpolate_(i1, t0, t, t1); _q.fromArray(result).normalize().toArray(result); return result; } }; var WEBGL_CONSTANTS = { FLOAT: 5126, 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", ...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_PROPERTIES = { scale: "scale", translation: "position", rotation: "quaternion", weights: "morphTargetInfluences" }; var INTERPOLATION = { CUBICSPLINE: void 0, 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: 0 }); 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(geometry, targets, parser) { let hasMorphPosition = false; let hasMorphNormal = false; let hasMorphColor = false; for (let i = 0, il = targets.length; i < il; i++) { const target = targets[i]; if (target.POSITION !== void 0) hasMorphPosition = true; if (target.NORMAL !== void 0) hasMorphNormal = true; if (target.COLOR_0 !== void 0) hasMorphColor = true; if (hasMorphPosition && hasMorphNormal && hasMorphColor) break; } if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) return Promise.resolve(geometry); const pendingPositionAccessors = []; const pendingNormalAccessors = []; const pendingColorAccessors = []; for (let i = 0, il = targets.length; i < il; i++) { const target = targets[i]; if (hasMorphPosition) { const pendingAccessor = target.POSITION !== void 0 ? parser.getDependency("accessor", target.POSITION) : geometry.attributes.position; pendingPositionAccessors.push(pendingAccessor); } if (hasMorphNormal) { const pendingAccessor = target.NORMAL !== void 0 ? parser.getDependency("accessor", target.NORMAL) : geometry.attributes.normal; pendingNormalAccessors.push(pendingAccessor); } if (hasMorphColor) { const pendingAccessor = target.COLOR_0 !== void 0 ? parser.getDependency("accessor", target.COLOR_0) : geometry.attributes.color; pendingColorAccessors.push(pendingAccessor); } } return Promise.all([ Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors), Promise.all(pendingColorAccessors) ]).then(function(accessors) { const morphPositions = accessors[0]; const morphNormals = accessors[1]; const morphColors = accessors[2]; if (hasMorphPosition) geometry.morphAttributes.position = morphPositions; if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals; if (hasMorphColor) geometry.morphAttributes.color = morphColors; geometry.morphTargetsRelative = true; return geometry; }); } function updateMorphTargets(mesh, meshDef) { mesh.updateMorphTargets(); if (meshDef.weights !== void 0) for (let i = 0, il = meshDef.weights.length; i < il; i++) mesh.morphTargetInfluences[i] = meshDef.weights[i]; if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) { const targetNames = meshDef.extras.targetNames; if (mesh.morphTargetInfluences.length === targetNames.length) { mesh.morphTargetDictionary = {}; for (let i = 0, il = targetNames.length; i < il; i++) mesh.morphTargetDictionary[targetNames[i]] = i; } else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names."); } } function createPrimitiveKey(primitiveDef) { let geometryKey; const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]; if (dracoExtension) geometryKey = "draco:" + dracoExtension.bufferView + ":" + dracoExtension.indices + ":" + createAttributesKey(dracoExtension.attributes); else geometryKey = primitiveDef.indices + ":" + createAttributesKey(primitiveDef.attributes) + ":" + primitiveDef.mode; if (primitiveDef.targets !== void 0) for (let i = 0, il = primitiveDef.targets.length; i < il; i++) geometryKey += ":" + createAttributesKey(primitiveDef.targets[i]); return geometryKey; } function createAttributesKey(attributes) { let attributesKey = ""; const keys = Object.keys(attributes).sort(); for (let i = 0, il = keys.length; i < il; i++) attributesKey += keys[i] + ":" + attributes[keys[i]] + ";"; return attributesKey; } function getNormalizedComponentScale(constructor) { switch (constructor) { case Int8Array: return 1 / 127; case Uint8Array: return 1 / 255; case Int16Array: return 1 / 32767; case Uint16Array: return 1 / 65535; default: throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type."); } } function getImageURIMimeType(uri) { if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0) return "image/jpeg"; if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0) return "image/webp"; return "image/png"; } var _identityMatrix = /* @__PURE__ */ 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(extensions) { this.extensions = extensions; } setPlugins(plugins) { this.plugins = plugins; } parse(onLoad, onError) { const parser = this; const json = this.json; const extensions = this.extensions; this.cache.removeAll(); this.nodeCache = {}; this._invokeAll(function(ext) { return ext._markDefs && ext._markDefs(); }); Promise.all(this._invokeAll(function(ext) { return ext.beforeRoot && ext.beforeRoot(); })).then(function() { return Promise.all([ parser.getDependencies("scene"), parser.getDependencies("animation"), parser.getDependencies("camera") ]); }).then(function(dependencies) { const result = { scene: dependencies[0][json.scene || 0], scenes: dependencies[0], animations: dependencies[1], cameras: dependencies[2], asset: json.asset, parser, userData: {} }; addUnknownExtensionsToUserData(extensions, result, json); assignExtrasToUserData(result, json); return Promise.all(parser._invokeAll(function(ext) { return ext.afterRoot && ext.afterRoot(result); })).then(function() { for (const scene of result.scenes) scene.updateMatrixWorld(); onLoad(result); }); }).catch(onError); } /** * Marks the special nodes/meshes in json for efficient parse. */ _markDefs() { const nodeDefs = this.json.nodes || []; const skinDefs = this.json.skins || []; const meshDefs = this.json.meshes || []; for (let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) { const joints = skinDefs[skinIndex].joints; for (let i = 0, il = joints.length; i < il; i++) nodeDefs[joints[i]].isBone = true; } for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) { const nodeDef = nodeDefs[nodeIndex]; if (nodeDef.mesh !== void 0) { this._addNodeRef(this.meshCache, nodeDef.mesh); if (nodeDef.skin !== void 0) meshDefs[nodeDef.mesh].isSkinnedMesh = true; } if (nodeDef.camera !== void 0) this._addNodeRef(this.cameraCache, nodeDef.camera); } } /** * Counts references to shared node / Object3D resources. These resources * can be reused, or "instantiated", at multiple nodes in the scene * hierarchy. Mesh, Camera, and Light instances are instantiated and must * be marked. Non-scenegraph resources (like Materials, Geometries, and * Textures) can be reused directly and are not marked here. * * Example: CesiumMilkTruck sample model reuses "Wheel" meshes. */ _addNodeRef(cache, index) { if (index === void 0) return; if (cache.refs[index] === void 0) cache.refs[index] = cache.uses[index] = 0; cache.refs[index]++; } /** Returns a reference to a shared resource, cloning it if necessary. */ _getNodeRef(cache, index, object) { if (cache.refs[index] <= 1) return object; const ref = object.clone(); const updateMappings = (original, clone) => { const mappings = this.associations.get(original); if (mappings != null) this.associations.set(clone, mappings); for (const [i, child] of original.children.entries()) updateMappings(child, clone.children[i]); }; updateMappings(object, ref); ref.name += "_instance_" + cache.uses[index]++; return ref; } _invokeOne(func) { const extensions = Object.values(this.plugins); extensions.push(this); for (let i = 0; i < extensions.length; i++) { const result = func(extensions[i]); if (result) return result; } return null; } _invokeAll(func) { const extensions = Object.values(this.plugins); extensions.unshift(this); const pending = []; for (let i = 0; i < extensions.length; i++) { const result = func(extensions[i]); if (result) pending.push(result); } return pending; } /** * Requests the specified dependency asynchronously, with caching. * @param {string} type * @param {number} index * @return {Promise} */ getDependency(type, index) { const cacheKey = type + ":" + index; let dependency = this.cache.get(cacheKey); if (!dependency) { switch (type) { case "scene": dependency = this.loadScene(index); break; case "node": dependency = this._invokeOne(function(ext) { return ext.loadNode && ext.loadNode(index); }); break; case "mesh": dependency = this._invokeOne(function(ext) { return ext.loadMesh && ext.loadMesh(index); }); break; case "accessor": dependency = this.loadAccessor(index); break; case "bufferView": dependency = this._invokeOne(function(ext) { return ext.loadBufferView && ext.loadBufferView(index); }); break; case "buffer": dependency = this.loadBuffer(index); break; case "material": dependency = this._invokeOne(function(ext) { return ext.loadMaterial && ext.loadMaterial(index); }); break; case "texture": dependency = this._invokeOne(function(ext) { return ext.loadTexture && ext.loadTexture(index); }); break; case "skin": dependency = this.loadSkin(index); break; case "animation": dependency = this._invokeOne(function(ext) { return ext.loadAnimation && ext.loadAnimation(index); }); break; case "camera": dependency = this.loadCamera(index); break; default: dependency = this._invokeOne(function(ext) { return ext != this && ext.getDependency && ext.getDependency(type, index); }); 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, index) { return parser.getDependency(type, index); })); 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 loader = this.fileLoader; if (bufferDef.type && bufferDef.type !== "arraybuffer") throw new Error("THREE.GLTFLoader: " + bufferDef.type + " buffer type is not supported."); if (bufferDef.uri === void 0 && bufferIndex === 0) return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body); const options = this.options; return new Promise(function(resolve, reject) { loader.load(LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, void 0, function() { reject(/* @__PURE__ */ 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(buffer) { const byteLength = bufferViewDef.byteLength || 0; const byteOffset = bufferViewDef.byteOffset || 0; return buffer.slice(byteOffset, byteOffset + byteLength); }); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @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 i = 0, il = sparseIndices.length; i < il; i++) { const index = sparseIndices[i]; bufferAttribute.setX(index, sparseValues[i * itemSize]); if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]); if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]); if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * 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 sourceIndex = json.textures[textureIndex].source; const sourceDef = json.images[sourceIndex]; let loader = this.textureLoader; if (sourceDef.uri) { const handler = options.manager.getHandler(sourceDef.uri); if (handler !== null) loader = handler; } return this.loadTextureImage(textureIndex, sourceIndex, loader); } loadTextureImage(textureIndex, sourceIndex, loader) { const parser = this; const json = this.json; const textureDef = json.textures[textureIndex]; const sourceDef = json.images[sourceIndex]; const cacheKey = (sourceDef.uri || sourceDef.bufferView) + ":" + textureDef.sampler; if (this.textureCache[cacheKey]) return this.textureCache[cacheKey]; const promise = this.loadImageSource(sourceIndex, loader).then(function(texture) { texture.flipY = false; texture.name = textureDef.name || sourceDef.name || ""; if (texture.name === "" && typeof sourceDef.uri === "string" && sourceDef.uri.startsWith("data:image/") === false) texture.name = sourceDef.uri; const sampler = (json.samplers || {})[textureDef.sampler] || {}; texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || 1006; texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || 1008; texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || 1e3; texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || 1e3; parser.associations.set(texture, { textures: textureIndex }); return texture; }).catch(function() { return null; }); this.textureCache[cacheKey] = promise; return promise; } loadImageSource(sourceIndex, loader) { const parser = this; const json = this.json; const options = this.options; if (this.sourceCache[sourceIndex] !== void 0) return this.sourceCache[sourceIndex].then((texture) => texture.clone()); const sourceDef = json.images[sourceIndex]; const URL = 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 = URL.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 (loader.isImageBitmapLoader === true) onLoad = function(imageBitmap) { const texture = new Texture(imageBitmap); texture.needsUpdate = true; resolve(texture); }; loader.load(LoaderUtils.resolveURL(sourceURI2, options.path), onLoad, void 0, reject); }); }).then(function(texture) { if (isObjectURL === true) URL.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$1 ? SRGBColorSpace$1 : LinearSRGBColorSpace$1; if ("colorSpace" in texture) texture.colorSpace = colorSpace; else texture.encoding = colorSpace === SRGBColorSpace$1 ? sRGBEncoding$1 : LinearEncoding$1; } 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 geometry = mesh.geometry; let material = mesh.material; const useDerivativeTangents = geometry.attributes.tangent === void 0; const useVertexColors = geometry.attributes.color !== void 0; const useFlatShading = geometry.attributes.normal === void 0; if (mesh.isPoints) { const cacheKey = "PointsMaterial:" + material.uuid; let pointsMaterial = this.cache.get(cacheKey); if (!pointsMaterial) { pointsMaterial = new PointsMaterial(); Material.prototype.copy.call(pointsMaterial, material); pointsMaterial.color.copy(material.color); pointsMaterial.map = material.map; pointsMaterial.sizeAttenuation = false; this.cache.add(cacheKey, pointsMaterial); } material = pointsMaterial; } else if (mesh.isLine) { const cacheKey = "LineBasicMaterial:" + material.uuid; let lineMaterial = this.cache.get(cacheKey); if (!lineMaterial) { lineMaterial = new LineBasicMaterial(); Material.prototype.copy.call(lineMaterial, material); lineMaterial.color.copy(material.color); lineMaterial.map = material.map; this.cache.add(cacheKey, lineMaterial); } material = lineMaterial; } if (useDerivativeTangents || useVertexColors || useFlatShading) { let cacheKey = "ClonedMaterial:" + material.uuid + ":"; if (useDerivativeTangents) cacheKey += "derivative-tangents:"; if (useVertexColors) cacheKey += "vertex-colors:"; if (useFlatShading) cacheKey += "flat-shading:"; let cachedMaterial = this.cache.get(cacheKey); if (!cachedMaterial) { cachedMaterial = material.clone(); if (useVertexColors) cachedMaterial.vertexColors = true; if (useFlatShading) cachedMaterial.flatShading = true; if (useDerivativeTangents) { if (cachedMaterial.normalScale) cachedMaterial.normalScale.y *= -1; if (cachedMaterial.clearcoatNormalScale) cachedMaterial.clearcoatNormalScale.y *= -1; } this.cache.add(cacheKey, cachedMaterial); this.associations.set(cachedMaterial, this.associations.get(material)); } material = cachedMaterial; } mesh.material = material; } getMaterialType() { return MeshStandardMaterial; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex * @return {Promise} */ loadMaterial(materialIndex) { const parser = this; const json = this.json; const extensions = this.extensions; const materialDef = json.materials[materialIndex]; let materialType; const materialParams = {}; const materialExtensions = materialDef.extensions || {}; const pending = []; if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) { const kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT]; materialType = kmuExtension.getMaterialType(); pending.push(kmuExtension.extendParams(materialParams, materialDef, parser)); } else { const metallicRoughness = materialDef.pbrMetallicRoughness || {}; materialParams.color = new Color(1, 1, 1); materialParams.opacity = 1; if (Array.isArray(metallicRoughness.baseColorFactor)) { const array = metallicRoughness.baseColorFactor; materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace$1); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== void 0) pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace$1)); 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 = 2; 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 : .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 scale = materialDef.normalTexture.scale; materialParams.normalScale.set(scale, scale); } } if (materialDef.occlusionTexture !== void 0 && materialType !== MeshBasicMaterial) { pending.push(parser.assignTexture(materialParams, "aoMap", materialDef.occlusionTexture)); if (materialDef.occlusionTexture.strength !== void 0) materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; } if (materialDef.emissiveFactor !== void 0 && materialType !== MeshBasicMaterial) { const emissiveFactor = materialDef.emissiveFactor; materialParams.emissive = new Color().setRGB(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2], LinearSRGBColorSpace$1); } if (materialDef.emissiveTexture !== void 0 && materialType !== MeshBasicMaterial) pending.push(parser.assignTexture(materialParams, "emissiveMap", materialDef.emissiveTexture, SRGBColorSpace$1)); return Promise.all(pending).then(function() { const material = new materialType(materialParams); if (materialDef.name) material.name = materialDef.name; assignExtrasToUserData(material, materialDef); parser.associations.set(material, { materials: materialIndex }); if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef); return material; }); } /** When Object3D instances are targeted by animation, they need unique names. */ 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 extensions = this.extensions; const cache = this.primitiveCache; function createDracoPrimitive(primitive) { return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function(geometry) { return addPrimitiveAttributes(geometry, primitive, parser); }); } const pending = []; for (let i = 0, il = primitives.length; i < il; i++) { const primitive = primitives[i]; const cacheKey = createPrimitiveKey(primitive); const cached = cache[cacheKey]; if (cached) pending.push(cached.promise); else { let geometryPromise; if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) geometryPromise = createDracoPrimitive(primitive); else geometryPromise = addPrimitiveAttributes(new BufferGeometry(), primitive, parser); cache[cacheKey] = { primitive, promise: geometryPromise }; pending.push(geometryPromise); } } return Promise.all(pending); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes * @param {number} meshIndex * @return {Promise} */ loadMesh(meshIndex) { const parser = this; const json = this.json; const extensions = this.extensions; const meshDef = json.meshes[meshIndex]; const primitives = meshDef.primitives; const pending = []; for (let i = 0, il = primitives.length; i < il; i++) { const material = primitives[i].material === void 0 ? createDefaultMaterial(this.cache) : this.getDependency("material", primitives[i].material); pending.push(material); } pending.push(parser.loadGeometries(primitives)); return Promise.all(pending).then(function(results) { const materials = results.slice(0, results.length - 1); const geometries = results[results.length - 1]; const meshes = []; for (let i = 0, il = geometries.length; i < il; i++) { const geometry = geometries[i]; const primitive = primitives[i]; let mesh; const material = materials[i]; if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === void 0) { mesh = meshDef.isSkinnedMesh === true ? new SkinnedMesh(geometry, material) : new Mesh(geometry, material); if (mesh.isSkinnedMesh === true) mesh.normalizeSkinWeights(); if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) mesh.geometry = toTrianglesDrawMode(mesh.geometry, 1); else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) mesh.geometry = toTrianglesDrawMode(mesh.geometry, 2); } else if (primitive.mode === WEBGL_CONSTANTS.LINES) mesh = new LineSegments(geometry, material); else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) mesh = new Line(geometry, material); else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) mesh = new LineLoop(geometry, material); else if (primitive.mode === WEBGL_CONSTANTS.POINTS) mesh = new Points(geometry, material); else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: " + primitive.mode); if (Object.keys(mesh.geometry.morphAttributes).length > 0) updateMorphTargets(mesh, meshDef); mesh.name = parser.createUniqueName(meshDef.name || "mesh_" + meshIndex); assignExtrasToUserData(mesh, meshDef); if (primitive.extensions) addUnknownExtensionsToUserData(extensions, mesh, primitive); parser.assignFinalMaterial(mesh); meshes.push(mesh); } for (let i = 0, il = meshes.length; i < il; i++) parser.associations.set(meshes[i], { meshes: meshIndex, primitives: i }); if (meshes.length === 1) { if (meshDef.extensions) addUnknownExtensionsToUserData(extensions, meshes[0], meshDef); return meshes[0]; } const group = new Group(); if (meshDef.extensions) addUnknownExtensionsToUserData(extensions, group, meshDef); parser.associations.set(group, { meshes: meshIndex }); for (let i = 0, il = meshes.length; i < il; i++) group.add(meshes[i]); return group; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras * @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 i = 0, il = skinDef.joints.length; i < il; i++) pending.push(this._loadNodeShallow(skinDef.joints[i])); if (skinDef.inverseBindMatrices !== void 0) pending.push(this.getDependency("accessor", skinDef.inverseBindMatrices)); else pending.push(null); return Promise.all(pending).then(function(results) { const inverseBindMatrices = results.pop(); const jointNodes = results; const bones = []; const boneInverses = []; for (let i = 0, il = jointNodes.length; i < il; i++) { const jointNode = jointNodes[i]; if (jointNode) { bones.push(jointNode); const mat = new Matrix4(); if (inverseBindMatrices !== null) mat.fromArray(inverseBindMatrices.array, i * 16); boneInverses.push(mat); } else console.warn("THREE.GLTFLoader: Joint \"%s\" could not be found.", skinDef.joints[i]); } return new Skeleton(bones, boneInverses); }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @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 i = 0, il = animationDef.channels.length; i < il; i++) { const channel = animationDef.channels[i]; const sampler = animationDef.samplers[channel.sampler]; const target = channel.target; const name = target.node; const input = animationDef.parameters !== void 0 ? animationDef.parameters[sampler.input] : sampler.input; const output = animationDef.parameters !== void 0 ? animationDef.parameters[sampler.output] : sampler.output; if (target.node === void 0) continue; pendingNodes.push(this.getDependency("node", name)); pendingInputAccessors.push(this.getDependency("accessor", input)); pendingOutputAccessors.push(this.getDependency("accessor", output)); pendingSamplers.push(sampler); pendingTargets.push(target); } return Promise.all([ Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets) ]).then(function(dependencies) { const nodes = dependencies[0]; const inputAccessors = dependencies[1]; const outputAccessors = dependencies[2]; const samplers = dependencies[3]; const targets = dependencies[4]; const tracks = []; for (let i = 0, il = nodes.length; i < il; i++) { const node = nodes[i]; const inputAccessor = inputAccessors[i]; const outputAccessor = outputAccessors[i]; const sampler = samplers[i]; const target = targets[i]; if (node === void 0) continue; if (node.updateMatrix) node.updateMatrix(); const createdTracks = parser._createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target); if (createdTracks) for (let 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(o) { if (!o.isMesh) return; for (let i = 0, il = nodeDef.weights.length; i < il; i++) o.morphTargetInfluences[i] = nodeDef.weights[i]; }); return node; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy * @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 i = 0, il = childrenDef.length; i < il; i++) childPending.push(parser.getDependency("node", childrenDef[i])); const skeletonPending = nodeDef.skin === void 0 ? Promise.resolve(null) : parser.getDependency("skin", nodeDef.skin); return Promise.all([ nodePending, Promise.all(childPending), skeletonPending ]).then(function(results) { const node = results[0]; const children = results[1]; const skeleton = results[2]; if (skeleton !== null) node.traverse(function(mesh) { if (!mesh.isSkinnedMesh) return; mesh.bind(skeleton, _identityMatrix); }); for (let i = 0, il = children.length; i < il; i++) node.add(children[i]); return node; }); } _loadNodeShallow(nodeIndex) { const json = this.json; const extensions = this.extensions; const parser = this; if (this.nodeCache[nodeIndex] !== void 0) return this.nodeCache[nodeIndex]; const nodeDef = json.nodes[nodeIndex]; const nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : ""; const pending = []; const meshPromise = parser._invokeOne(function(ext) { return ext.createNodeMesh && ext.createNodeMesh(nodeIndex); }); if (meshPromise) pending.push(meshPromise); if (nodeDef.camera !== void 0) pending.push(parser.getDependency("camera", nodeDef.camera).then(function(camera) { return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera); })); parser._invokeAll(function(ext) { return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex); }).forEach(function(promise) { pending.push(promise); }); this.nodeCache[nodeIndex] = Promise.all(pending).then(function(objects) { let node; if (nodeDef.isBone === true) node = new Bone(); else if (objects.length > 1) node = new Group(); else if (objects.length === 1) node = objects[0]; else node = new Object3D(); if (node !== objects[0]) for (let i = 0, il = objects.length; i < il; i++) node.add(objects[i]); if (nodeDef.name) { node.userData.name = nodeDef.name; node.name = nodeName; } assignExtrasToUserData(node, nodeDef); if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef); if (nodeDef.matrix !== void 0) { const matrix = new Matrix4(); matrix.fromArray(nodeDef.matrix); node.applyMatrix4(matrix); } 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 extensions = this.extensions; const sceneDef = this.json.scenes[sceneIndex]; const parser = this; const scene = new Group(); if (sceneDef.name) scene.name = parser.createUniqueName(sceneDef.name); assignExtrasToUserData(scene, sceneDef); if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef); const nodeIds = sceneDef.nodes || []; const pending = []; for (let i = 0, il = nodeIds.length; i < il; i++) pending.push(parser.getDependency("node", nodeIds[i])); return Promise.all(pending).then(function(nodes) { for (let i = 0, il = nodes.length; i < il; i++) scene.add(nodes[i]); const reduceAssociations = (node) => { const reducedAssociations = /* @__PURE__ */ new Map(); for (const [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, target) { const tracks = []; const targetName = node.name ? node.name : node.uuid; const targetNames = []; if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) node.traverse(function(object) { if (object.morphTargetInfluences) targetNames.push(object.name ? object.name : object.uuid); }); else targetNames.push(targetName); let TypedKeyframeTrack; switch (PATH_PROPERTIES[target.path]) { case PATH_PROPERTIES.weights: TypedKeyframeTrack = NumberKeyframeTrack; break; case PATH_PROPERTIES.rotation: TypedKeyframeTrack = QuaternionKeyframeTrack; break; case PATH_PROPERTIES.position: case PATH_PROPERTIES.scale: TypedKeyframeTrack = VectorKeyframeTrack; break; default: switch (outputAccessor.itemSize) { case 1: TypedKeyframeTrack = NumberKeyframeTrack; break; 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_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); if (sampler.interpolation === "CUBICSPLINE") this._createCubicSplineTrackInterpolant(track); tracks.push(track); } return tracks; } _getArrayFromAccessor(accessor) { let outputArray = accessor.array; if (accessor.normalized) { const scale = getNormalizedComponentScale(outputArray.constructor); const scaled = new Float32Array(outputArray.length); for (let j = 0, jl = outputArray.length; j < jl; j++) scaled[j] = outputArray[j] * scale; outputArray = scaled; } return outputArray; } _createCubicSplineTrackInterpolant(track) { track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) { return new (this instanceof QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant)(this.times, this.values, this.getValueSize() / 3, result); }; track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; } }; function computeBounds(geometry, primitiveDef, parser) { const attributes = primitiveDef.attributes; const box = new Box3(); if (attributes.POSITION !== void 0) { const accessor = parser.json.accessors[attributes.POSITION]; const min = accessor.min; const max = accessor.max; if (min !== void 0 && max !== void 0) { box.set(new Vector3(min[0], min[1], min[2]), new Vector3(max[0], max[1], max[2])); if (accessor.normalized) { const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); box.min.multiplyScalar(boxScale); box.max.multiplyScalar(boxScale); } } else { console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); return; } } else return; const targets = primitiveDef.targets; if (targets !== void 0) { const maxDisplacement = new Vector3(); const vector = new Vector3(); for (let i = 0, il = targets.length; i < il; i++) { const target = targets[i]; if (target.POSITION !== void 0) { const accessor = parser.json.accessors[target.POSITION]; const min = accessor.min; const max = accessor.max; if (min !== void 0 && max !== void 0) { vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0]))); vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1]))); vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2]))); if (accessor.normalized) { const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); vector.multiplyScalar(boxScale); } maxDisplacement.max(vector); } else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); } } box.expandByVector(maxDisplacement); } geometry.boundingBox = box; const sphere = new Sphere(); box.getCenter(sphere.center); sphere.radius = box.min.distanceTo(box.max) / 2; geometry.boundingSphere = sphere; } function addPrimitiveAttributes(geometry, primitiveDef, parser) { const attributes = primitiveDef.attributes; const pending = []; function assignAttributeAccessor(accessorIndex, attributeName) { return parser.getDependency("accessor", accessorIndex).then(function(accessor) { geometry.setAttribute(attributeName, accessor); }); } for (const gltfAttributeName in attributes) { const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); if (threeAttributeName in geometry.attributes) continue; pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName)); } if (primitiveDef.indices !== void 0 && !geometry.index) { const accessor = parser.getDependency("accessor", primitiveDef.indices).then(function(accessor2) { geometry.setIndex(accessor2); }); pending.push(accessor); } assignExtrasToUserData(geometry, primitiveDef); computeBounds(geometry, primitiveDef, parser); return Promise.all(pending).then(function() { return primitiveDef.targets !== void 0 ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry; }); } //#endregion //#region node_modules/three-stdlib/webxr/XRHandMeshModel.js var __defProp$8 = Object.defineProperty; var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$8 = (obj, key, value) => { __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var DEFAULT_HAND_PROFILE_PATH = "https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"; var XRHandMeshModel = class { constructor(handModel, controller, path = DEFAULT_HAND_PROFILE_PATH, handedness, customModelPath) { __publicField$8(this, "controller"); __publicField$8(this, "handModel"); __publicField$8(this, "bones"); this.controller = controller; this.handModel = handModel; this.bones = []; const loader = new GLTFLoader(); if (!customModelPath) loader.setPath(path); loader.load(customModelPath != null ? customModelPath : `${handedness}.glb`, (gltf) => { const object = gltf.scene.children[0]; this.handModel.add(object); const mesh = object.getObjectByProperty("type", "SkinnedMesh"); mesh.frustumCulled = false; mesh.castShadow = true; mesh.receiveShadow = true; [ "wrist", "thumb-metacarpal", "thumb-phalanx-proximal", "thumb-phalanx-distal", "thumb-tip", "index-finger-metacarpal", "index-finger-phalanx-proximal", "index-finger-phalanx-intermediate", "index-finger-phalanx-distal", "index-finger-tip", "middle-finger-metacarpal", "middle-finger-phalanx-proximal", "middle-finger-phalanx-intermediate", "middle-finger-phalanx-distal", "middle-finger-tip", "ring-finger-metacarpal", "ring-finger-phalanx-proximal", "ring-finger-phalanx-intermediate", "ring-finger-phalanx-distal", "ring-finger-tip", "pinky-finger-metacarpal", "pinky-finger-phalanx-proximal", "pinky-finger-phalanx-intermediate", "pinky-finger-phalanx-distal", "pinky-finger-tip" ].forEach((jointName) => { const bone = object.getObjectByName(jointName); if (bone !== void 0) bone.jointName = jointName; else console.warn(`Couldn't find ${jointName} in ${handedness} hand mesh`); this.bones.push(bone); }); }); } updateMesh() { const XRJoints = this.controller.joints; for (let i = 0; i < this.bones.length; i++) { const bone = this.bones[i]; if (bone) { const XRJoint = XRJoints[bone.jointName]; if (XRJoint.visible) { const position = XRJoint.position; bone.position.copy(position); bone.quaternion.copy(XRJoint.quaternion); } } } } }; //#endregion //#region node_modules/three-stdlib/webxr/OculusHandModel.js var __defProp$7 = Object.defineProperty; var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$7 = (obj, key, value) => { __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var TOUCH_RADIUS = .01; var POINTING_JOINT = "index-finger-tip"; var OculusHandModel = class extends Object3D { constructor(controller, leftModelPath, rightModelPath) { super(); __publicField$7(this, "controller"); __publicField$7(this, "motionController"); __publicField$7(this, "envMap"); __publicField$7(this, "mesh"); __publicField$7(this, "xrInputSource"); this.controller = controller; this.motionController = null; this.envMap = null; this.mesh = null; this.xrInputSource = null; controller.addEventListener("connected", (event) => { const xrInputSource = event.data; if (xrInputSource.hand && !this.motionController) { this.xrInputSource = xrInputSource; this.motionController = new XRHandMeshModel(this, controller, void 0, xrInputSource.handedness, xrInputSource.handedness === "left" ? leftModelPath : rightModelPath); } }); controller.addEventListener("disconnected", () => { this.dispose(); }); } updateMatrixWorld(force) { super.updateMatrixWorld(force); if (this.motionController) this.motionController.updateMesh(); } getPointerPosition() { const indexFingerTip = this.controller.joints[POINTING_JOINT]; if (indexFingerTip) return indexFingerTip.position; else return null; } intersectBoxObject(boxObject) { const pointerPosition = this.getPointerPosition(); if (pointerPosition) { const indexSphere = new Sphere(pointerPosition, TOUCH_RADIUS); const box = new Box3().setFromObject(boxObject); return indexSphere.intersectsBox(box); } else return false; } checkButton(button) { if (this.intersectBoxObject(button)) button.onPress(); else button.onClear(); if (button.isPressed()) button.whilePressed(); } dispose() { this.clear(); this.motionController = null; } }; //#endregion //#region node_modules/three-stdlib/webxr/OculusHandPointerModel.js var PINCH_MAX = .05; var PINCH_THRESHOLD = .02; var PINCH_MIN = .01; var POINTER_ADVANCE_MAX = .02; var POINTER_OPACITY_MAX = 1; var POINTER_OPACITY_MIN = .4; var POINTER_FRONT_RADIUS = .002; var POINTER_REAR_RADIUS = .01; var POINTER_REAR_RADIUS_MIN = .003; var POINTER_LENGTH = .035; var POINTER_SEGMENTS = 16; var POINTER_RINGS = 12; var POINTER_HEMISPHERE_ANGLE = 110; var YAXIS = /* @__PURE__ */ new Vector3(0, 1, 0); var ZAXIS = /* @__PURE__ */ new Vector3(0, 0, 1); var CURSOR_RADIUS = .02; var CURSOR_MAX_DISTANCE = 1.5; var OculusHandPointerModel = class extends Object3D { constructor(hand, controller) { super(); this.hand = hand; this.controller = controller; this.motionController = null; this.envMap = null; this.mesh = null; this.pointerGeometry = null; this.pointerMesh = null; this.pointerObject = null; this.pinched = false; this.attached = false; this.cursorObject = null; this.raycaster = null; this._onConnected = this._onConnected.bind(this); this._onDisconnected = this._onDisconnected.bind(this); this.hand.addEventListener("connected", this._onConnected); this.hand.addEventListener("disconnected", this._onDisconnected); } _onConnected(event) { const xrInputSource = event.data; if (xrInputSource.hand) { this.visible = true; this.xrInputSource = xrInputSource; this.createPointer(); } } _onDisconnected() { var _a, _b; this.visible = false; this.xrInputSource = null; (_a = this.pointerGeometry) == null || _a.dispose(); (_b = this.pointerMesh) == null || _b.material.dispose(); this.clear(); } _drawVerticesRing(vertices, baseVector, ringIndex) { const segmentVector = baseVector.clone(); for (var i = 0; i < POINTER_SEGMENTS; i++) { segmentVector.applyAxisAngle(ZAXIS, Math.PI * 2 / POINTER_SEGMENTS); const vid = ringIndex * POINTER_SEGMENTS + i; vertices[3 * vid] = segmentVector.x; vertices[3 * vid + 1] = segmentVector.y; vertices[3 * vid + 2] = segmentVector.z; } } _updatePointerVertices(rearRadius) { const vertices = this.pointerGeometry.attributes.position.array; const frontFaceBase = new Vector3(POINTER_FRONT_RADIUS, 0, -1 * (POINTER_LENGTH - rearRadius)); this._drawVerticesRing(vertices, frontFaceBase, 0); const rearBase = new Vector3(Math.sin(Math.PI * POINTER_HEMISPHERE_ANGLE / 180) * rearRadius, Math.cos(Math.PI * POINTER_HEMISPHERE_ANGLE / 180) * rearRadius, 0); for (var i = 0; i < POINTER_RINGS; i++) { this._drawVerticesRing(vertices, rearBase, i + 1); rearBase.applyAxisAngle(YAXIS, Math.PI * POINTER_HEMISPHERE_ANGLE / 180 / (POINTER_RINGS * -2)); } const frontCenterIndex = POINTER_SEGMENTS * 13; const rearCenterIndex = 209; const frontCenter = new Vector3(0, 0, -1 * (POINTER_LENGTH - rearRadius)); vertices[frontCenterIndex * 3] = frontCenter.x; vertices[625] = frontCenter.y; vertices[626] = frontCenter.z; const rearCenter = new Vector3(0, 0, rearRadius); vertices[rearCenterIndex * 3] = rearCenter.x; vertices[628] = rearCenter.y; vertices[629] = rearCenter.z; this.pointerGeometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); } createPointer() { var i, j; const vertices = new Array(630).fill(0); const indices = []; this.pointerGeometry = new BufferGeometry(); this.pointerGeometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this._updatePointerVertices(POINTER_REAR_RADIUS); for (i = 0; i < POINTER_RINGS; i++) { for (j = 0; j < POINTER_SEGMENTS - 1; j++) { indices.push(i * POINTER_SEGMENTS + j, i * POINTER_SEGMENTS + j + 1, (i + 1) * POINTER_SEGMENTS + j); indices.push(i * POINTER_SEGMENTS + j + 1, (i + 1) * POINTER_SEGMENTS + j + 1, (i + 1) * POINTER_SEGMENTS + j); } indices.push((i + 1) * POINTER_SEGMENTS - 1, i * POINTER_SEGMENTS, (i + 2) * POINTER_SEGMENTS - 1); indices.push(i * POINTER_SEGMENTS, (i + 1) * POINTER_SEGMENTS, (i + 2) * POINTER_SEGMENTS - 1); } const frontCenterIndex = POINTER_SEGMENTS * 13; const rearCenterIndex = 209; for (i = 0; i < POINTER_SEGMENTS - 1; i++) { indices.push(frontCenterIndex, i + 1, i); indices.push(rearCenterIndex, i + POINTER_SEGMENTS * POINTER_RINGS, i + POINTER_SEGMENTS * POINTER_RINGS + 1); } indices.push(frontCenterIndex, 0, POINTER_SEGMENTS - 1); indices.push(rearCenterIndex, POINTER_SEGMENTS * 13 - 1, POINTER_SEGMENTS * POINTER_RINGS); const material = new MeshBasicMaterial(); material.transparent = true; material.opacity = POINTER_OPACITY_MIN; this.pointerGeometry.setIndex(indices); this.pointerMesh = new Mesh(this.pointerGeometry, material); this.pointerMesh.position.set(0, 0, -1 * POINTER_REAR_RADIUS); this.pointerObject = new Object3D(); this.pointerObject.add(this.pointerMesh); this.raycaster = new Raycaster(); const cursorGeometry = new SphereGeometry(CURSOR_RADIUS, 10, 10); const cursorMaterial = new MeshBasicMaterial(); cursorMaterial.transparent = true; cursorMaterial.opacity = POINTER_OPACITY_MIN; this.cursorObject = new Mesh(cursorGeometry, cursorMaterial); this.pointerObject.add(this.cursorObject); this.add(this.pointerObject); } _updateRaycaster() { if (this.raycaster) { const pointerMatrix = this.pointerObject.matrixWorld; const tempMatrix = new Matrix4(); tempMatrix.identity().extractRotation(pointerMatrix); this.raycaster.ray.origin.setFromMatrixPosition(pointerMatrix); this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(tempMatrix); } } _updatePointer() { this.pointerObject.visible = this.controller.visible; const indexTip = this.hand.joints["index-finger-tip"]; const thumbTip = this.hand.joints["thumb-tip"]; const distance = indexTip.position.distanceTo(thumbTip.position); const position = indexTip.position.clone().add(thumbTip.position).multiplyScalar(.5); this.pointerObject.position.copy(position); this.pointerObject.quaternion.copy(this.controller.quaternion); this.pinched = distance <= PINCH_THRESHOLD; const pinchScale = (distance - PINCH_MIN) / (PINCH_MAX - PINCH_MIN); const focusScale = (distance - PINCH_MIN) / (PINCH_THRESHOLD - PINCH_MIN); if (pinchScale > 1) { this._updatePointerVertices(POINTER_REAR_RADIUS); this.pointerMesh.position.set(0, 0, -1 * POINTER_REAR_RADIUS); this.pointerMesh.material.opacity = POINTER_OPACITY_MIN; } else if (pinchScale > 0) { const rearRadius = (POINTER_REAR_RADIUS - POINTER_REAR_RADIUS_MIN) * pinchScale + POINTER_REAR_RADIUS_MIN; this._updatePointerVertices(rearRadius); if (focusScale < 1) { this.pointerMesh.position.set(0, 0, -1 * rearRadius - (1 - focusScale) * POINTER_ADVANCE_MAX); this.pointerMesh.material.opacity = POINTER_OPACITY_MIN + (1 - focusScale) * (POINTER_OPACITY_MAX - POINTER_OPACITY_MIN); } else { this.pointerMesh.position.set(0, 0, -1 * rearRadius); this.pointerMesh.material.opacity = POINTER_OPACITY_MIN; } } else { this._updatePointerVertices(POINTER_REAR_RADIUS_MIN); this.pointerMesh.position.set(0, 0, -1 * POINTER_REAR_RADIUS_MIN - POINTER_ADVANCE_MAX); this.pointerMesh.material.opacity = POINTER_OPACITY_MAX; } this.cursorObject.material.opacity = this.pointerMesh.material.opacity; } updateMatrixWorld(force) { super.updateMatrixWorld(force); if (this.pointerGeometry) { this._updatePointer(); this._updateRaycaster(); } } isPinched() { return this.pinched; } setAttached(attached) { this.attached = attached; } isAttached() { return this.attached; } intersectObject(object, recursive = true) { if (this.raycaster) return this.raycaster.intersectObject(object, recursive); } intersectObjects(objects, recursive = true) { if (this.raycaster) return this.raycaster.intersectObjects(objects, recursive); } checkIntersections(objects, recursive = false) { if (this.raycaster && !this.attached) { const intersections = this.raycaster.intersectObjects(objects, recursive); const direction = new Vector3(0, 0, -1); if (intersections.length > 0) { const distance = intersections[0].distance; this.cursorObject.position.copy(direction.multiplyScalar(distance)); } else this.cursorObject.position.copy(direction.multiplyScalar(CURSOR_MAX_DISTANCE)); } } setCursor(distance) { const direction = new Vector3(0, 0, -1); if (this.raycaster && !this.attached) this.cursorObject.position.copy(direction.multiplyScalar(distance)); } dispose() { this._onDisconnected(); this.hand.removeEventListener("connected", this._onConnected); this.hand.removeEventListener("disconnected", this._onDisconnected); } }; //#endregion //#region node_modules/three-stdlib/webxr/Text2D.js function createText(message, height) { const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); let metrics = null; const textHeight = 100; context.font = "normal 100px Arial"; metrics = context.measureText(message); const textWidth = metrics.width; canvas.width = textWidth; canvas.height = textHeight; context.font = "normal 100px Arial"; context.textAlign = "center"; context.textBaseline = "middle"; context.fillStyle = "#ffffff"; context.fillText(message, textWidth / 2, textHeight / 2); const texture = new Texture(canvas); texture.needsUpdate = true; const material = new MeshBasicMaterial({ color: 16777215, side: 2, map: texture, transparent: true }); return new Mesh(new PlaneGeometry(height * textWidth / textHeight, height), material); } //#endregion //#region node_modules/three-stdlib/webxr/VRButton.js var __defProp$6 = Object.defineProperty; var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$6 = (obj, key, value) => { __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var VRButton = /* @__PURE__ */ (() => { 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 _a; if (currentSession === null) { const optionalFeatures = [ sessionInit.optionalFeatures, "local-floor", "bounded-floor", "hand-tracking" ].flat().filter(Boolean); (_a = navigator.xr) == null || _a.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; __publicField$6(VRButton2, "xrSessionIsGranted", false); VRButton2.registerSessionGrantedListener(); return VRButton2; })(); //#endregion //#region node_modules/three-stdlib/libs/MotionControllers.js var __defProp$5 = Object.defineProperty; var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$5 = (obj, key, value) => { __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; 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: .05, AxisTouchThreshold: .1, VisualResponseProperty: { TRANSFORM: "transform", VISIBILITY: "visibility" } }; async function fetchJsonFile(path) { const response = await fetch(path); if (!response.ok) throw new Error(response.statusText); else return response.json(); } async function fetchProfilesList(basePath) { if (!basePath) throw new Error("No basePath supplied"); return await fetchJsonFile(`${basePath}/profilesList.json`); } async function fetchProfile(xrInputSource, basePath, defaultProfile = null, getAssetPath = true) { if (!xrInputSource) throw new Error("No xrInputSource supplied"); if (!basePath) throw new Error("No basePath supplied"); const supportedProfilesList = await fetchProfilesList(basePath); let match = void 0; xrInputSource.profiles.some((profileId) => { const supportedProfile = supportedProfilesList[profileId]; if (supportedProfile) match = { profileId, profilePath: `${basePath}/${supportedProfile.path}`, deprecated: !!supportedProfile.deprecated }; return !!match; }); if (!match) { if (!defaultProfile) throw new Error("No matching profile name found"); const supportedProfile = supportedProfilesList[defaultProfile]; if (!supportedProfile) throw new Error(`No matching profile name found and default profile "${defaultProfile}" missing.`); match = { profileId: defaultProfile, profilePath: `${basePath}/${supportedProfile.path}`, deprecated: !!supportedProfile.deprecated }; } const profile = await fetchJsonFile(match.profilePath); let assetPath = void 0; if (getAssetPath) { let layout; if (xrInputSource.handedness === "any") layout = profile.layouts[Object.keys(profile.layouts)[0]]; else layout = profile.layouts[xrInputSource.handedness]; if (!layout) throw new Error(`No matching handedness, ${xrInputSource.handedness}, in profile ${match.profileId}`); if (layout.assetPath) assetPath = match.profilePath.replace("profile.json", layout.assetPath); } return { profile, assetPath }; } var defaultComponentValues = { xAxis: 0, yAxis: 0, button: 0, state: MotionControllerConstants.ComponentState.DEFAULT }; function normalizeAxes(x = 0, y = 0) { let xAxis = x; let yAxis = y; if (Math.sqrt(x * x + y * y) > 1) { const theta = Math.atan2(y, x); xAxis = Math.cos(theta); yAxis = Math.sin(theta); } return { normalizedXAxis: xAxis * .5 + .5, normalizedYAxis: yAxis * .5 + .5 }; } var VisualResponse = class { constructor(visualResponseDescription) { __publicField$5(this, "value"); __publicField$5(this, "componentProperty"); __publicField$5(this, "states"); __publicField$5(this, "valueNodeName"); __publicField$5(this, "valueNodeProperty"); __publicField$5(this, "minNodeName"); __publicField$5(this, "maxNodeName"); __publicField$5(this, "valueNode"); __publicField$5(this, "minNode"); __publicField$5(this, "maxNode"); this.componentProperty = visualResponseDescription.componentProperty; this.states = visualResponseDescription.states; this.valueNodeName = visualResponseDescription.valueNodeName; this.valueNodeProperty = visualResponseDescription.valueNodeProperty; if (this.valueNodeProperty === MotionControllerConstants.VisualResponseProperty.TRANSFORM) { this.minNodeName = visualResponseDescription.minNodeName; this.maxNodeName = visualResponseDescription.maxNodeName; } this.value = 0; this.updateFromComponent(defaultComponentValues); } /** * Computes the visual response's interpolation weight based on component state * @param {Object} componentValues - The component from which to update * @param {number | undefined} xAxis - The reported X axis value of the component * @param {number | undefined} yAxis - The reported Y axis value of the component * @param {number | undefined} button - The reported value of the component's button * @param {string} state - The component's active state */ updateFromComponent({ xAxis, yAxis, button, state }) { const { normalizedXAxis, normalizedYAxis } = normalizeAxes(xAxis, yAxis); switch (this.componentProperty) { case MotionControllerConstants.ComponentProperty.X_AXIS: this.value = this.states.includes(state) ? normalizedXAxis : .5; break; case MotionControllerConstants.ComponentProperty.Y_AXIS: this.value = this.states.includes(state) ? normalizedYAxis : .5; break; case MotionControllerConstants.ComponentProperty.BUTTON: this.value = this.states.includes(state) && button ? button : 0; break; case MotionControllerConstants.ComponentProperty.STATE: if (this.valueNodeProperty === MotionControllerConstants.VisualResponseProperty.VISIBILITY) this.value = this.states.includes(state); else this.value = this.states.includes(state) ? 1 : 0; break; default: throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`); } } }; var Component = class { /** * @param {string} componentId - Id of the component * @param {InputProfileComponent} componentDescription - Description of the component to be created */ constructor(componentId, componentDescription) { __publicField$5(this, "id"); __publicField$5(this, "values"); __publicField$5(this, "type"); __publicField$5(this, "gamepadIndices"); __publicField$5(this, "rootNodeName"); __publicField$5(this, "visualResponses"); __publicField$5(this, "touchPointNodeName"); __publicField$5(this, "touchPointNode"); if (!componentId || !componentDescription || !componentDescription.visualResponses || !componentDescription.gamepadIndices || Object.keys(componentDescription.gamepadIndices).length === 0) throw new Error("Invalid arguments supplied"); this.id = componentId; this.type = componentDescription.type; this.rootNodeName = componentDescription.rootNodeName; this.touchPointNodeName = componentDescription.touchPointNodeName; this.visualResponses = {}; Object.keys(componentDescription.visualResponses).forEach((responseName) => { const visualResponse = new VisualResponse(componentDescription.visualResponses[responseName]); this.visualResponses[responseName] = visualResponse; }); this.gamepadIndices = Object.assign({}, componentDescription.gamepadIndices); this.values = { state: MotionControllerConstants.ComponentState.DEFAULT, button: this.gamepadIndices.button !== void 0 ? 0 : void 0, xAxis: this.gamepadIndices.xAxis !== void 0 ? 0 : void 0, yAxis: this.gamepadIndices.yAxis !== void 0 ? 0 : void 0 }; } get data() { return { id: this.id, ...this.values }; } /** * @description Poll for updated data based on current gamepad state * @param {Object} gamepad - The gamepad object from which the component data should be polled */ updateFromGamepad(gamepad) { this.values.state = MotionControllerConstants.ComponentState.DEFAULT; if (this.gamepadIndices.button !== void 0 && gamepad.buttons.length > this.gamepadIndices.button) { const gamepadButton = gamepad.buttons[this.gamepadIndices.button]; this.values.button = gamepadButton.value; this.values.button = this.values.button < 0 ? 0 : this.values.button; this.values.button = this.values.button > 1 ? 1 : this.values.button; if (gamepadButton.pressed || this.values.button === 1) this.values.state = MotionControllerConstants.ComponentState.PRESSED; else if (gamepadButton.touched || this.values.button > MotionControllerConstants.ButtonTouchThreshold) this.values.state = MotionControllerConstants.ComponentState.TOUCHED; } if (this.gamepadIndices.xAxis !== void 0 && gamepad.axes.length > this.gamepadIndices.xAxis) { this.values.xAxis = gamepad.axes[this.gamepadIndices.xAxis]; this.values.xAxis = this.values.xAxis < -1 ? -1 : this.values.xAxis; this.values.xAxis = this.values.xAxis > 1 ? 1 : this.values.xAxis; if (this.values.state === MotionControllerConstants.ComponentState.DEFAULT && Math.abs(this.values.xAxis) > MotionControllerConstants.AxisTouchThreshold) this.values.state = MotionControllerConstants.ComponentState.TOUCHED; } if (this.gamepadIndices.yAxis !== void 0 && gamepad.axes.length > this.gamepadIndices.yAxis) { this.values.yAxis = gamepad.axes[this.gamepadIndices.yAxis]; this.values.yAxis = this.values.yAxis < -1 ? -1 : this.values.yAxis; this.values.yAxis = this.values.yAxis > 1 ? 1 : this.values.yAxis; if (this.values.state === MotionControllerConstants.ComponentState.DEFAULT && Math.abs(this.values.yAxis) > MotionControllerConstants.AxisTouchThreshold) this.values.state = MotionControllerConstants.ComponentState.TOUCHED; } Object.values(this.visualResponses).forEach((visualResponse) => { visualResponse.updateFromComponent(this.values); }); } }; var MotionController = class { /** * @param {XRInputSource} xrInputSource - The XRInputSource to build the MotionController around * @param {Profile} profile - The best matched profile description for the supplied xrInputSource * @param {string} assetUrl */ constructor(xrInputSource, profile, assetUrl) { __publicField$5(this, "xrInputSource"); __publicField$5(this, "assetUrl"); __publicField$5(this, "layoutDescription"); __publicField$5(this, "id"); __publicField$5(this, "components"); if (!xrInputSource) throw new Error("No xrInputSource supplied"); if (!profile) throw new Error("No profile supplied"); if (!profile.layouts[xrInputSource.handedness]) throw new Error("No layout for " + xrInputSource.handedness + " handedness"); this.xrInputSource = xrInputSource; this.assetUrl = assetUrl; this.id = profile.profileId; this.layoutDescription = profile.layouts[xrInputSource.handedness]; this.components = {}; Object.keys(this.layoutDescription.components).forEach((componentId) => { const componentDescription = this.layoutDescription.components[componentId]; this.components[componentId] = new Component(componentId, componentDescription); }); this.updateFromGamepad(); } get gripSpace() { return this.xrInputSource.gripSpace; } get targetRaySpace() { return this.xrInputSource.targetRaySpace; } /** * @description Returns a subset of component data for simplified debugging */ get data() { const data = []; Object.values(this.components).forEach((component) => { data.push(component.data); }); return data; } /** * @description Poll for updated data based on current gamepad state */ updateFromGamepad() { Object.values(this.components).forEach((component) => { component.updateFromGamepad(this.xrInputSource.gamepad); }); } }; //#endregion //#region node_modules/three-stdlib/webxr/XRControllerModelFactory.js var __defProp$4 = Object.defineProperty; var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$4 = (obj, key, value) => { __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var DEFAULT_PROFILES_PATH = "https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles"; var DEFAULT_PROFILE = "generic-trigger"; var applyEnvironmentMap = (envMap, obj) => { obj.traverse((child) => { if (child instanceof Mesh && "envMap" in child.material) { child.material.envMap = envMap; child.material.needsUpdate = true; } }); }; var XRControllerModel = class extends Object3D { constructor() { super(); __publicField$4(this, "envMap"); __publicField$4(this, "motionController"); this.motionController = null; this.envMap = null; } setEnvironmentMap(envMap) { if (this.envMap == envMap) return this; this.envMap = envMap; applyEnvironmentMap(this.envMap, this); return this; } /** * Polls data from the XRInputSource and updates the model's components to match * the real world data */ updateMatrixWorld(force) { super.updateMatrixWorld(force); if (!this.motionController) return; this.motionController.updateFromGamepad(); Object.values(this.motionController.components).forEach((component) => { Object.values(component.visualResponses).forEach((visualResponse) => { const { valueNode, minNode, maxNode, value, valueNodeProperty } = visualResponse; if (!valueNode) return; if (valueNodeProperty === MotionControllerConstants.VisualResponseProperty.VISIBILITY && typeof value === "boolean") valueNode.visible = value; else if (valueNodeProperty === MotionControllerConstants.VisualResponseProperty.TRANSFORM && minNode && maxNode && typeof value === "number") { valueNode.quaternion.slerpQuaternions(minNode.quaternion, maxNode.quaternion, value); valueNode.position.lerpVectors(minNode.position, maxNode.position, value); } }); }); } }; function findNodes(motionController, scene) { Object.values(motionController.components).forEach((component) => { const { type, touchPointNodeName, visualResponses } = component; if (type === MotionControllerConstants.ComponentType.TOUCHPAD && touchPointNodeName) { component.touchPointNode = scene.getObjectByName(touchPointNodeName); if (component.touchPointNode) { const sphere = new Mesh(new SphereGeometry(.001), new MeshBasicMaterial({ color: 255 })); component.touchPointNode.add(sphere); } else console.warn(`Could not find touch dot, ${component.touchPointNodeName}, in touchpad component ${component.id}`); } Object.values(visualResponses).forEach((visualResponse) => { const { valueNodeName, minNodeName, maxNodeName, valueNodeProperty } = visualResponse; if (valueNodeProperty === MotionControllerConstants.VisualResponseProperty.TRANSFORM && minNodeName && maxNodeName) { visualResponse.minNode = scene.getObjectByName(minNodeName); visualResponse.maxNode = scene.getObjectByName(maxNodeName); if (!visualResponse.minNode) { console.warn(`Could not find ${minNodeName} in the model`); return; } if (!visualResponse.maxNode) { console.warn(`Could not find ${maxNodeName} in the model`); return; } } visualResponse.valueNode = scene.getObjectByName(valueNodeName); if (!visualResponse.valueNode) console.warn(`Could not find ${valueNodeName} in the model`); }); }); } function addAssetSceneToControllerModel(controllerModel, scene) { findNodes(controllerModel.motionController, scene); if (controllerModel.envMap) applyEnvironmentMap(controllerModel.envMap, scene); controllerModel.add(scene); } var XRControllerModelFactory = class { constructor(gltfLoader = null) { __publicField$4(this, "gltfLoader"); __publicField$4(this, "path"); __publicField$4(this, "_assetCache"); this.gltfLoader = gltfLoader; this.path = DEFAULT_PROFILES_PATH; this._assetCache = {}; if (!this.gltfLoader) this.gltfLoader = new GLTFLoader(); } createControllerModel(controller) { const controllerModel = new XRControllerModel(); let scene = null; const onConnected = (event) => { const xrInputSource = event.data; if (xrInputSource.targetRayMode !== "tracked-pointer" || !xrInputSource.gamepad) return; fetchProfile(xrInputSource, this.path, DEFAULT_PROFILE).then(({ profile, assetPath }) => { if (!assetPath) throw new Error("no asset path"); controllerModel.motionController = new MotionController(xrInputSource, profile, assetPath); const assetUrl = controllerModel.motionController.assetUrl; const cachedAsset = this._assetCache[assetUrl]; if (cachedAsset) { scene = cachedAsset.scene.clone(); addAssetSceneToControllerModel(controllerModel, scene); } else { if (!this.gltfLoader) throw new Error("GLTFLoader not set."); this.gltfLoader.setPath(""); this.gltfLoader.load(controllerModel.motionController.assetUrl, (asset) => { if (!controllerModel.motionController) { console.warn("motionController gone while gltf load, bailing..."); return; } this._assetCache[assetUrl] = asset; scene = asset.scene.clone(); addAssetSceneToControllerModel(controllerModel, scene); }, () => {}, () => { throw new Error(`Asset ${assetUrl} missing or malformed.`); }); } }).catch((err) => { console.warn(err); }); }; controller.addEventListener("connected", onConnected); const onDisconnected = () => { controller.removeEventListener("connected", onConnected); controller.removeEventListener("disconnected", onDisconnected); controllerModel.motionController = null; if (scene) controllerModel.remove(scene); scene = null; }; controller.addEventListener("disconnected", onDisconnected); return controllerModel; } }; //#endregion //#region node_modules/three-stdlib/webxr/XREstimatedLight.js var SessionLightProbe = class { constructor(xrLight, renderer, lightProbe, environmentEstimation, estimationStartCallback) { this.xrLight = xrLight; this.renderer = renderer; this.lightProbe = lightProbe; this.xrWebGLBinding = null; this.estimationStartCallback = estimationStartCallback; this.frameCallback = this.onXRFrame.bind(this); const session = renderer.xr.getSession(); if (environmentEstimation && "XRWebGLBinding" in window) { xrLight.environment = new WebGLCubeRenderTarget(16).texture; const gl = renderer.getContext(); switch (session.preferredReflectionFormat) { case "srgba8": gl.getExtension("EXT_sRGB"); break; case "rgba16f": gl.getExtension("OES_texture_half_float"); break; } this.xrWebGLBinding = new XRWebGLBinding(session, gl); this.lightProbe.addEventListener("reflectionchange", () => { this.updateReflection(); }); } session.requestAnimationFrame(this.frameCallback); } updateReflection() { const textureProperties = this.renderer.properties.get(this.xrLight.environment); if (textureProperties) { const cubeMap = this.xrWebGLBinding.getReflectionCubeMap(this.lightProbe); if (cubeMap) { textureProperties.__webglTexture = cubeMap; this.xrLight.environment.needsPMREMUpdate = true; } } } onXRFrame(time, xrFrame) { if (!this.xrLight) return; xrFrame.session.requestAnimationFrame(this.frameCallback); const lightEstimate = xrFrame.getLightEstimate(this.lightProbe); if (lightEstimate) { this.xrLight.lightProbe.sh.fromArray(lightEstimate.sphericalHarmonicsCoefficients); this.xrLight.lightProbe.intensity = 1; const intensityScalar = Math.max(1, Math.max(lightEstimate.primaryLightIntensity.x, Math.max(lightEstimate.primaryLightIntensity.y, lightEstimate.primaryLightIntensity.z))); this.xrLight.directionalLight.color.setRGB(lightEstimate.primaryLightIntensity.x / intensityScalar, lightEstimate.primaryLightIntensity.y / intensityScalar, lightEstimate.primaryLightIntensity.z / intensityScalar); this.xrLight.directionalLight.intensity = intensityScalar; this.xrLight.directionalLight.position.copy(lightEstimate.primaryLightDirection); if (this.estimationStartCallback) { this.estimationStartCallback(); this.estimationStartCallback = null; } } } dispose() { this.xrLight = null; this.renderer = null; this.lightProbe = null; this.xrWebGLBinding = null; } }; var XREstimatedLight = class extends Group { constructor(renderer, environmentEstimation = true) { super(); this.lightProbe = new LightProbe(); this.lightProbe.intensity = 0; this.add(this.lightProbe); this.directionalLight = new DirectionalLight(); this.directionalLight.intensity = 0; this.add(this.directionalLight); this.environment = null; let sessionLightProbe = null; let estimationStarted = false; renderer.xr.addEventListener("sessionstart", () => { const session = renderer.xr.getSession(); if ("requestLightProbe" in session) session.requestLightProbe({ reflectionFormat: session.preferredReflectionFormat }).then((probe) => { sessionLightProbe = new SessionLightProbe(this, renderer, probe, environmentEstimation, () => { estimationStarted = true; this.dispatchEvent({ type: "estimationstart" }); }); }); }); renderer.xr.addEventListener("sessionend", () => { if (sessionLightProbe) { sessionLightProbe.dispose(); sessionLightProbe = null; } if (estimationStarted) this.dispatchEvent({ type: "estimationend" }); }); this.dispose = () => { if (sessionLightProbe) { sessionLightProbe.dispose(); sessionLightProbe = null; } this.remove(this.lightProbe); this.lightProbe = null; this.remove(this.directionalLight); this.directionalLight = null; this.environment = null; }; } }; //#endregion //#region node_modules/three-stdlib/webxr/XRHandPrimitiveModel.js var _matrix = /* @__PURE__ */ new Matrix4(); var _vector$1 = /* @__PURE__ */ new Vector3(); var XRHandPrimitiveModel = class { constructor(handModel, controller, path, handedness, options) { this.controller = controller; this.handModel = handModel; this.envMap = null; let geometry; if (!options || !options.primitive || options.primitive === "sphere") geometry = new SphereGeometry(1, 10, 10); else if (options.primitive === "box") geometry = new BoxGeometry(1, 1, 1); const material = new MeshStandardMaterial(); this.handMesh = new InstancedMesh(geometry, material, 30); this.handMesh.instanceMatrix.setUsage(DynamicDrawUsage); this.handMesh.castShadow = true; this.handMesh.receiveShadow = true; this.handModel.add(this.handMesh); this.joints = [ "wrist", "thumb-metacarpal", "thumb-phalanx-proximal", "thumb-phalanx-distal", "thumb-tip", "index-finger-metacarpal", "index-finger-phalanx-proximal", "index-finger-phalanx-intermediate", "index-finger-phalanx-distal", "index-finger-tip", "middle-finger-metacarpal", "middle-finger-phalanx-proximal", "middle-finger-phalanx-intermediate", "middle-finger-phalanx-distal", "middle-finger-tip", "ring-finger-metacarpal", "ring-finger-phalanx-proximal", "ring-finger-phalanx-intermediate", "ring-finger-phalanx-distal", "ring-finger-tip", "pinky-finger-metacarpal", "pinky-finger-phalanx-proximal", "pinky-finger-phalanx-intermediate", "pinky-finger-phalanx-distal", "pinky-finger-tip" ]; } updateMesh() { const defaultRadius = .008; const joints = this.controller.joints; let count = 0; for (let i = 0; i < this.joints.length; i++) { const joint = joints[this.joints[i]]; if (joint.visible) { _vector$1.setScalar(joint.jointRadius || defaultRadius); _matrix.compose(joint.position, joint.quaternion, _vector$1); this.handMesh.setMatrixAt(i, _matrix); count++; } } this.handMesh.count = count; this.handMesh.instanceMatrix.needsUpdate = true; } }; //#endregion //#region node_modules/three-stdlib/webxr/XRHandModelFactory.js var XRHandModel = class extends Object3D { constructor(controller) { super(); this.controller = controller; this.motionController = null; this.envMap = null; this.mesh = null; } updateMatrixWorld(force) { super.updateMatrixWorld(force); if (this.motionController) this.motionController.updateMesh(); } }; var XRHandModelFactory = class { constructor() { this.path = null; } setPath(path) { this.path = path; return this; } createHandModel(controller, profile) { const handModel = new XRHandModel(controller); controller.addEventListener("connected", (event) => { const xrInputSource = event.data; if (xrInputSource.hand && !handModel.motionController) { handModel.xrInputSource = xrInputSource; if (profile === void 0 || profile === "spheres") handModel.motionController = new XRHandPrimitiveModel(handModel, controller, this.path, xrInputSource.handedness, { primitive: "sphere" }); else if (profile === "boxes") handModel.motionController = new XRHandPrimitiveModel(handModel, controller, this.path, xrInputSource.handedness, { primitive: "box" }); else if (profile === "mesh") handModel.motionController = new XRHandMeshModel(handModel, controller, this.path, xrInputSource.handedness); } }); controller.addEventListener("disconnected", () => {}); return handModel; } }; //#endregion //#region node_modules/three-stdlib/geometries/ParametricGeometry.js var ParametricGeometry = class extends BufferGeometry { constructor(func = (u, v, target) => target.set(u, v, Math.cos(u) * Math.sin(v)), slices = 8, stacks = 8) { super(); this.type = "ParametricGeometry"; this.parameters = { func, slices, stacks }; const indices = []; const vertices = []; const normals = []; const uvs = []; const EPS = 1e-5; const normal = new Vector3(); const p0 = new Vector3(), p1 = new Vector3(); const pu = new Vector3(), pv = new Vector3(); const sliceCount = slices + 1; for (let i = 0; i <= stacks; i++) { const v = i / stacks; for (let j = 0; j <= slices; j++) { const u = j / slices; func(u, v, p0); vertices.push(p0.x, p0.y, p0.z); if (u - EPS >= 0) { func(u - EPS, v, p1); pu.subVectors(p0, p1); } else { func(u + EPS, v, p1); pu.subVectors(p1, p0); } if (v - EPS >= 0) { func(u, v - EPS, p1); pv.subVectors(p0, p1); } else { func(u, v + EPS, p1); pv.subVectors(p1, p0); } normal.crossVectors(pu, pv).normalize(); normals.push(normal.x, normal.y, normal.z); uvs.push(u, v); } } for (let i = 0; i < stacks; i++) for (let j = 0; j < slices; j++) { const a = i * sliceCount + j; const b = i * sliceCount + j + 1; const c = (i + 1) * sliceCount + j + 1; const d = (i + 1) * sliceCount + j; indices.push(a, b, d); indices.push(b, c, d); } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } }; //#endregion //#region node_modules/three-stdlib/geometries/ParametricGeometries.js var TubeGeometry = class extends ParametricGeometry { constructor(path, segments = 64, radius = 1, segmentsRadius = 8, closed = false) { const numpoints = segments + 1; const frames = path.computeFrenetFrames(segments, closed), tangents = frames.tangents, normals = frames.normals, binormals = frames.binormals; const position = new Vector3(); function ParametricTube(u, v, target) { v *= 2 * Math.PI; const i = Math.floor(u * (numpoints - 1)); path.getPointAt(u, position); const normal = normals[i]; const binormal = binormals[i]; const cx = -radius * Math.cos(v); const cy = radius * Math.sin(v); position.x += cx * normal.x + cy * binormal.x; position.y += cx * normal.y + cy * binormal.y; position.z += cx * normal.z + cy * binormal.z; target.copy(position); } super(ParametricTube, segments, segmentsRadius); this.tangents = tangents; this.normals = normals; this.binormals = binormals; this.path = path; this.segments = segments; this.radius = radius; this.segmentsRadius = segmentsRadius; this.closed = closed; } }; var ParametricGeometries = { klein: function(v, u, target) { u *= Math.PI; v *= 2 * Math.PI; u = u * 2; let x, z; if (u < Math.PI) { x = 3 * Math.cos(u) * (1 + Math.sin(u)) + 2 * (1 - Math.cos(u) / 2) * Math.cos(u) * Math.cos(v); z = -8 * Math.sin(u) - 2 * (1 - Math.cos(u) / 2) * Math.sin(u) * Math.cos(v); } else { x = 3 * Math.cos(u) * (1 + Math.sin(u)) + 2 * (1 - Math.cos(u) / 2) * Math.cos(v + Math.PI); z = -8 * Math.sin(u); } const y = -2 * (1 - Math.cos(u) / 2) * Math.sin(v); target.set(x, y, z); }, plane: function(width, height) { return function(u, v, target) { const x = u * width; const y = 0; const z = v * height; target.set(x, y, z); }; }, mobius: function(u, t, target) { u = u - .5; const v = 2 * Math.PI * t; const a = 2; const x = Math.cos(v) * (a + u * Math.cos(v / 2)); const y = Math.sin(v) * (a + u * Math.cos(v / 2)); const z = u * Math.sin(v / 2); target.set(x, y, z); }, mobius3d: function(u, t, target) { u *= Math.PI; t *= 2 * Math.PI; u = u * 2; const phi = u / 2; const major = 2.25, a = .125, b = .65; let x = a * Math.cos(t) * Math.cos(phi) - b * Math.sin(t) * Math.sin(phi); const z = a * Math.cos(t) * Math.sin(phi) + b * Math.sin(t) * Math.cos(phi); const y = (major + x) * Math.sin(u); x = (major + x) * Math.cos(u); target.set(x, y, z); }, TubeGeometry, TorusKnotGeometry: class TorusKnotGeometry extends TubeGeometry { constructor(radius = 200, tube = 40, segmentsT = 64, segmentsR = 8, p = 2, q = 3) { class TorusKnotCurve extends Curve { getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; t *= Math.PI * 2; const r = .5; const x = (1 + r * Math.cos(q * t)) * Math.cos(p * t); const y = (1 + r * Math.cos(q * t)) * Math.sin(p * t); const z = r * Math.sin(q * t); return point.set(x, y, z).multiplyScalar(radius); } } const segments = segmentsT; const radiusSegments = segmentsR; const extrudePath = new TorusKnotCurve(); super(extrudePath, segments, tube, radiusSegments, true, false); this.radius = radius; this.tube = tube; this.segmentsT = segmentsT; this.segmentsR = segmentsR; this.p = p; this.q = q; } }, SphereGeometry: class SphereGeometry extends ParametricGeometry { constructor(size, u, v) { function sphere(u2, v2, target) { u2 *= Math.PI; v2 *= 2 * Math.PI; const x = size * Math.sin(u2) * Math.cos(v2); const y = size * Math.sin(u2) * Math.sin(v2); const z = size * Math.cos(u2); target.set(x, y, z); } super(sphere, u, v); } }, PlaneGeometry: class PlaneGeometry extends ParametricGeometry { constructor(width, depth, segmentsWidth, segmentsDepth) { function plane(u, v, target) { const x = u * width; const y = 0; const z = v * depth; target.set(x, y, z); } super(plane, segmentsWidth, segmentsDepth); } } }; //#endregion //#region node_modules/three-stdlib/geometries/RoundedBoxGeometry.js var tempNormal = /* @__PURE__ */ new Vector3(); function getUv(faceDirVector, normal, uvAxis, projectionAxis, radius, sideLength) { const totArcLength = 2 * Math.PI * radius / 4; const centerLength = Math.max(sideLength - 2 * radius, 0); const halfArc = Math.PI / 4; tempNormal.copy(normal); tempNormal[projectionAxis] = 0; tempNormal.normalize(); const arcUvRatio = .5 * totArcLength / (totArcLength + centerLength); const arcAngleRatio = 1 - tempNormal.angleTo(faceDirVector) / halfArc; if (Math.sign(tempNormal[uvAxis]) === 1) return arcAngleRatio * arcUvRatio; else return centerLength / (totArcLength + centerLength) + arcUvRatio + arcUvRatio * (1 - arcAngleRatio); } var RoundedBoxGeometry = class extends BoxGeometry { constructor(width = 1, height = 1, depth = 1, segments = 2, radius = .1) { segments = segments * 2 + 1; radius = Math.min(width / 2, height / 2, depth / 2, radius); super(1, 1, 1, segments, segments, segments); if (segments === 1) return; const geometry2 = this.toNonIndexed(); this.index = null; this.attributes.position = geometry2.attributes.position; this.attributes.normal = geometry2.attributes.normal; this.attributes.uv = geometry2.attributes.uv; const position = new Vector3(); const normal = new Vector3(); const box = new Vector3(width, height, depth).divideScalar(2).subScalar(radius); const positions = this.attributes.position.array; const normals = this.attributes.normal.array; const uvs = this.attributes.uv.array; const faceTris = positions.length / 6; const faceDirVector = new Vector3(); const halfSegmentSize = .5 / segments; for (let i = 0, j = 0; i < positions.length; i += 3, j += 2) { position.fromArray(positions, i); normal.copy(position); normal.x -= Math.sign(normal.x) * halfSegmentSize; normal.y -= Math.sign(normal.y) * halfSegmentSize; normal.z -= Math.sign(normal.z) * halfSegmentSize; normal.normalize(); positions[i + 0] = box.x * Math.sign(position.x) + normal.x * radius; positions[i + 1] = box.y * Math.sign(position.y) + normal.y * radius; positions[i + 2] = box.z * Math.sign(position.z) + normal.z * radius; normals[i + 0] = normal.x; normals[i + 1] = normal.y; normals[i + 2] = normal.z; switch (Math.floor(i / faceTris)) { case 0: faceDirVector.set(1, 0, 0); uvs[j + 0] = getUv(faceDirVector, normal, "z", "y", radius, depth); uvs[j + 1] = 1 - getUv(faceDirVector, normal, "y", "z", radius, height); break; case 1: faceDirVector.set(-1, 0, 0); uvs[j + 0] = 1 - getUv(faceDirVector, normal, "z", "y", radius, depth); uvs[j + 1] = 1 - getUv(faceDirVector, normal, "y", "z", radius, height); break; case 2: faceDirVector.set(0, 1, 0); uvs[j + 0] = 1 - getUv(faceDirVector, normal, "x", "z", radius, width); uvs[j + 1] = getUv(faceDirVector, normal, "z", "x", radius, depth); break; case 3: faceDirVector.set(0, -1, 0); uvs[j + 0] = 1 - getUv(faceDirVector, normal, "x", "z", radius, width); uvs[j + 1] = 1 - getUv(faceDirVector, normal, "z", "x", radius, depth); break; case 4: faceDirVector.set(0, 0, 1); uvs[j + 0] = 1 - getUv(faceDirVector, normal, "x", "y", radius, width); uvs[j + 1] = 1 - getUv(faceDirVector, normal, "y", "x", radius, height); break; case 5: faceDirVector.set(0, 0, -1); uvs[j + 0] = getUv(faceDirVector, normal, "x", "y", radius, width); uvs[j + 1] = 1 - getUv(faceDirVector, normal, "y", "x", radius, height); break; } } } }; //#endregion //#region node_modules/three-stdlib/geometries/BoxLineGeometry.js var BoxLineGeometry = class extends BufferGeometry { constructor(width, height, depth, widthSegments, heightSegments, depthSegments) { super(); width = width || 1; height = height || 1; depth = depth || 1; widthSegments = Math.floor(widthSegments) || 1; heightSegments = Math.floor(heightSegments) || 1; depthSegments = Math.floor(depthSegments) || 1; const widthHalf = width / 2; const heightHalf = height / 2; const depthHalf = depth / 2; const segmentWidth = width / widthSegments; const segmentHeight = height / heightSegments; const segmentDepth = depth / depthSegments; const vertices = []; let x = -widthHalf, y = -heightHalf, z = -depthHalf; for (let i = 0; i <= widthSegments; i++) { vertices.push(x, -heightHalf, -depthHalf, x, heightHalf, -depthHalf); vertices.push(x, heightHalf, -depthHalf, x, heightHalf, depthHalf); vertices.push(x, heightHalf, depthHalf, x, -heightHalf, depthHalf); vertices.push(x, -heightHalf, depthHalf, x, -heightHalf, -depthHalf); x += segmentWidth; } for (let i = 0; i <= heightSegments; i++) { vertices.push(-widthHalf, y, -depthHalf, widthHalf, y, -depthHalf); vertices.push(widthHalf, y, -depthHalf, widthHalf, y, depthHalf); vertices.push(widthHalf, y, depthHalf, -widthHalf, y, depthHalf); vertices.push(-widthHalf, y, depthHalf, -widthHalf, y, -depthHalf); y += segmentHeight; } for (let i = 0; i <= depthSegments; i++) { vertices.push(-widthHalf, -heightHalf, z, -widthHalf, heightHalf, z); vertices.push(-widthHalf, heightHalf, z, widthHalf, heightHalf, z); vertices.push(widthHalf, heightHalf, z, widthHalf, -heightHalf, z); vertices.push(widthHalf, -heightHalf, z, -widthHalf, -heightHalf, z); z += segmentDepth; } this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); } }; //#endregion //#region node_modules/three-stdlib/geometries/DecalGeometry.js var DecalGeometry = class extends BufferGeometry { constructor(mesh, position, orientation, size) { super(); const vertices = []; const normals = []; const uvs = []; const plane = new Vector3(); const projectorMatrix = new Matrix4(); projectorMatrix.makeRotationFromEuler(orientation); projectorMatrix.setPosition(position); 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 i; let decalVertices = []; const vertex = new Vector3(); const normal = new Vector3(); if (mesh.geometry.isGeometry === true) { console.error("THREE.DecalGeometry no longer supports THREE.Geometry. Use BufferGeometry instead."); return; } const geometry = mesh.geometry; const positionAttribute = geometry.attributes.position; const normalAttribute = geometry.attributes.normal; if (geometry.index !== null) { const index = geometry.index; for (i = 0; i < index.count; i++) { vertex.fromBufferAttribute(positionAttribute, index.getX(i)); normal.fromBufferAttribute(normalAttribute, index.getX(i)); pushDecalVertex(decalVertices, vertex, normal); } } else for (i = 0; i < positionAttribute.count; i++) { vertex.fromBufferAttribute(positionAttribute, i); normal.fromBufferAttribute(normalAttribute, i); pushDecalVertex(decalVertices, vertex, normal); } 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 (i = 0; i < decalVertices.length; i++) { const decalVertex = decalVertices[i]; uvs.push(.5 + decalVertex.position.x / size.x, .5 + decalVertex.position.y / size.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, normal) { vertex.applyMatrix4(mesh.matrixWorld); vertex.applyMatrix4(projectorMatrixInverse); normal.transformDirection(mesh.matrixWorld); decalVertices.push(new DecalVertex(vertex.clone(), normal.clone())); } function clipGeometry(inVertices, plane2) { const outVertices = []; const s = .5 * Math.abs(size.dot(plane2)); for (let i = 0; i < inVertices.length; i += 3) { let v1Out, v2Out, v3Out, total = 0; let nV1, nV2, nV3, nV4; const d1 = inVertices[i + 0].position.dot(plane2) - s; const d2 = inVertices[i + 1].position.dot(plane2) - s; const d3 = inVertices[i + 2].position.dot(plane2) - s; 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[i]); outVertices.push(inVertices[i + 1]); outVertices.push(inVertices[i + 2]); break; case 1: if (v1Out) { nV1 = inVertices[i + 1]; nV2 = inVertices[i + 2]; nV3 = clip(inVertices[i], nV1, plane2, s); nV4 = clip(inVertices[i], nV2, plane2, s); } if (v2Out) { nV1 = inVertices[i]; nV2 = inVertices[i + 2]; nV3 = clip(inVertices[i + 1], nV1, plane2, s); nV4 = clip(inVertices[i + 1], nV2, plane2, s); outVertices.push(nV3); outVertices.push(nV2.clone()); outVertices.push(nV1.clone()); outVertices.push(nV2.clone()); outVertices.push(nV3.clone()); outVertices.push(nV4); break; } if (v3Out) { nV1 = inVertices[i]; nV2 = inVertices[i + 1]; nV3 = clip(inVertices[i + 2], nV1, plane2, s); nV4 = clip(inVertices[i + 2], nV2, plane2, s); } outVertices.push(nV1.clone()); outVertices.push(nV2.clone()); outVertices.push(nV3); outVertices.push(nV4); outVertices.push(nV3.clone()); outVertices.push(nV2.clone()); break; case 2: if (!v1Out) { nV1 = inVertices[i].clone(); nV2 = clip(nV1, inVertices[i + 1], plane2, s); nV3 = clip(nV1, inVertices[i + 2], plane2, s); outVertices.push(nV1); outVertices.push(nV2); outVertices.push(nV3); } if (!v2Out) { nV1 = inVertices[i + 1].clone(); nV2 = clip(nV1, inVertices[i + 2], plane2, s); nV3 = clip(nV1, inVertices[i], plane2, s); outVertices.push(nV1); outVertices.push(nV2); outVertices.push(nV3); } if (!v3Out) { nV1 = inVertices[i + 2].clone(); nV2 = clip(nV1, inVertices[i], plane2, s); nV3 = clip(nV1, inVertices[i + 1], plane2, s); outVertices.push(nV1); outVertices.push(nV2); outVertices.push(nV3); } break; } } return outVertices; } function clip(v0, v1, p, s) { const d0 = v0.position.dot(p) - s; const s0 = d0 / (d0 - (v1.position.dot(p) - s)); return new DecalVertex(new Vector3(v0.position.x + s0 * (v1.position.x - v0.position.x), v0.position.y + s0 * (v1.position.y - v0.position.y), v0.position.z + s0 * (v1.position.z - v0.position.z)), new Vector3(v0.normal.x + s0 * (v1.normal.x - v0.normal.x), v0.normal.y + s0 * (v1.normal.y - v0.normal.y), v0.normal.z + s0 * (v1.normal.z - v0.normal.z))); } } }; var DecalVertex = class { constructor(position, normal) { this.position = position; this.normal = normal; } clone() { return new this.constructor(this.position.clone(), this.normal.clone()); } }; //#endregion //#region node_modules/three-stdlib/geometries/TeapotGeometry.js var TeapotGeometry = class extends BufferGeometry { constructor(size, segments, bottom, lid, body, fitLid, blinn) { const teapotPatches = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 3, 16, 17, 18, 7, 19, 20, 21, 11, 22, 23, 24, 15, 25, 26, 27, 18, 28, 29, 30, 21, 31, 32, 33, 24, 34, 35, 36, 27, 37, 38, 39, 30, 40, 41, 0, 33, 42, 43, 4, 36, 44, 45, 8, 39, 46, 47, 12, 12, 13, 14, 15, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 15, 25, 26, 27, 51, 60, 61, 62, 55, 63, 64, 65, 59, 66, 67, 68, 27, 37, 38, 39, 62, 69, 70, 71, 65, 72, 73, 74, 68, 75, 76, 77, 39, 46, 47, 12, 71, 78, 79, 48, 74, 80, 81, 52, 77, 82, 83, 56, 56, 57, 58, 59, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 59, 66, 67, 68, 87, 96, 97, 98, 91, 99, 100, 101, 95, 102, 103, 104, 68, 75, 76, 77, 98, 105, 106, 107, 101, 108, 109, 110, 104, 111, 112, 113, 77, 82, 83, 56, 107, 114, 115, 84, 110, 116, 117, 88, 113, 118, 119, 92, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 123, 136, 137, 120, 127, 138, 139, 124, 131, 140, 141, 128, 135, 142, 143, 132, 132, 133, 134, 135, 144, 145, 146, 147, 148, 149, 150, 151, 68, 152, 153, 154, 135, 142, 143, 132, 147, 155, 156, 144, 151, 157, 158, 148, 154, 159, 160, 68, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 164, 177, 178, 161, 168, 179, 180, 165, 172, 181, 182, 169, 176, 183, 184, 173, 173, 174, 175, 176, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 176, 183, 184, 173, 188, 197, 198, 185, 192, 199, 200, 189, 196, 201, 202, 193, 203, 203, 203, 203, 204, 205, 206, 207, 208, 208, 208, 208, 209, 210, 211, 212, 203, 203, 203, 203, 207, 213, 214, 215, 208, 208, 208, 208, 212, 216, 217, 218, 203, 203, 203, 203, 215, 219, 220, 221, 208, 208, 208, 208, 218, 222, 223, 224, 203, 203, 203, 203, 221, 225, 226, 204, 208, 208, 208, 208, 224, 227, 228, 209, 209, 210, 211, 212, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 212, 216, 217, 218, 232, 241, 242, 243, 236, 244, 245, 246, 240, 247, 248, 249, 218, 222, 223, 224, 243, 250, 251, 252, 246, 253, 254, 255, 249, 256, 257, 258, 224, 227, 228, 209, 252, 259, 260, 229, 255, 261, 262, 233, 258, 263, 264, 237, 265, 265, 265, 265, 266, 267, 268, 269, 270, 271, 272, 273, 92, 119, 118, 113, 265, 265, 265, 265, 269, 274, 275, 276, 273, 277, 278, 279, 113, 112, 111, 104, 265, 265, 265, 265, 276, 280, 281, 282, 279, 283, 284, 285, 104, 103, 102, 95, 265, 265, 265, 265, 282, 286, 287, 266, 285, 288, 289, 270, 95, 94, 93, 92 ]; const teapotVertices = [ 1.4, 0, 2.4, 1.4, -.784, 2.4, .784, -1.4, 2.4, 0, -1.4, 2.4, 1.3375, 0, 2.53125, 1.3375, -.749, 2.53125, .749, -1.3375, 2.53125, 0, -1.3375, 2.53125, 1.4375, 0, 2.53125, 1.4375, -.805, 2.53125, .805, -1.4375, 2.53125, 0, -1.4375, 2.53125, 1.5, 0, 2.4, 1.5, -.84, 2.4, .84, -1.5, 2.4, 0, -1.5, 2.4, -.784, -1.4, 2.4, -1.4, -.784, 2.4, -1.4, 0, 2.4, -.749, -1.3375, 2.53125, -1.3375, -.749, 2.53125, -1.3375, 0, 2.53125, -.805, -1.4375, 2.53125, -1.4375, -.805, 2.53125, -1.4375, 0, 2.53125, -.84, -1.5, 2.4, -1.5, -.84, 2.4, -1.5, 0, 2.4, -1.4, .784, 2.4, -.784, 1.4, 2.4, 0, 1.4, 2.4, -1.3375, .749, 2.53125, -.749, 1.3375, 2.53125, 0, 1.3375, 2.53125, -1.4375, .805, 2.53125, -.805, 1.4375, 2.53125, 0, 1.4375, 2.53125, -1.5, .84, 2.4, -.84, 1.5, 2.4, 0, 1.5, 2.4, .784, 1.4, 2.4, 1.4, .784, 2.4, .749, 1.3375, 2.53125, 1.3375, .749, 2.53125, .805, 1.4375, 2.53125, 1.4375, .805, 2.53125, .84, 1.5, 2.4, 1.5, .84, 2.4, 1.75, 0, 1.875, 1.75, -.98, 1.875, .98, -1.75, 1.875, 0, -1.75, 1.875, 2, 0, 1.35, 2, -1.12, 1.35, 1.12, -2, 1.35, 0, -2, 1.35, 2, 0, .9, 2, -1.12, .9, 1.12, -2, .9, 0, -2, .9, -.98, -1.75, 1.875, -1.75, -.98, 1.875, -1.75, 0, 1.875, -1.12, -2, 1.35, -2, -1.12, 1.35, -2, 0, 1.35, -1.12, -2, .9, -2, -1.12, .9, -2, 0, .9, -1.75, .98, 1.875, -.98, 1.75, 1.875, 0, 1.75, 1.875, -2, 1.12, 1.35, -1.12, 2, 1.35, 0, 2, 1.35, -2, 1.12, .9, -1.12, 2, .9, 0, 2, .9, .98, 1.75, 1.875, 1.75, .98, 1.875, 1.12, 2, 1.35, 2, 1.12, 1.35, 1.12, 2, .9, 2, 1.12, .9, 2, 0, .45, 2, -1.12, .45, 1.12, -2, .45, 0, -2, .45, 1.5, 0, .225, 1.5, -.84, .225, .84, -1.5, .225, 0, -1.5, .225, 1.5, 0, .15, 1.5, -.84, .15, .84, -1.5, .15, 0, -1.5, .15, -1.12, -2, .45, -2, -1.12, .45, -2, 0, .45, -.84, -1.5, .225, -1.5, -.84, .225, -1.5, 0, .225, -.84, -1.5, .15, -1.5, -.84, .15, -1.5, 0, .15, -2, 1.12, .45, -1.12, 2, .45, 0, 2, .45, -1.5, .84, .225, -.84, 1.5, .225, 0, 1.5, .225, -1.5, .84, .15, -.84, 1.5, .15, 0, 1.5, .15, 1.12, 2, .45, 2, 1.12, .45, .84, 1.5, .225, 1.5, .84, .225, .84, 1.5, .15, 1.5, .84, .15, -1.6, 0, 2.025, -1.6, -.3, 2.025, -1.5, -.3, 2.25, -1.5, 0, 2.25, -2.3, 0, 2.025, -2.3, -.3, 2.025, -2.5, -.3, 2.25, -2.5, 0, 2.25, -2.7, 0, 2.025, -2.7, -.3, 2.025, -3, -.3, 2.25, -3, 0, 2.25, -2.7, 0, 1.8, -2.7, -.3, 1.8, -3, -.3, 1.8, -3, 0, 1.8, -1.5, .3, 2.25, -1.6, .3, 2.025, -2.5, .3, 2.25, -2.3, .3, 2.025, -3, .3, 2.25, -2.7, .3, 2.025, -3, .3, 1.8, -2.7, .3, 1.8, -2.7, 0, 1.575, -2.7, -.3, 1.575, -3, -.3, 1.35, -3, 0, 1.35, -2.5, 0, 1.125, -2.5, -.3, 1.125, -2.65, -.3, .9375, -2.65, 0, .9375, -2, -.3, .9, -1.9, -.3, .6, -1.9, 0, .6, -3, .3, 1.35, -2.7, .3, 1.575, -2.65, .3, .9375, -2.5, .3, 1.125, -1.9, .3, .6, -2, .3, .9, 1.7, 0, 1.425, 1.7, -.66, 1.425, 1.7, -.66, .6, 1.7, 0, .6, 2.6, 0, 1.425, 2.6, -.66, 1.425, 3.1, -.66, .825, 3.1, 0, .825, 2.3, 0, 2.1, 2.3, -.25, 2.1, 2.4, -.25, 2.025, 2.4, 0, 2.025, 2.7, 0, 2.4, 2.7, -.25, 2.4, 3.3, -.25, 2.4, 3.3, 0, 2.4, 1.7, .66, .6, 1.7, .66, 1.425, 3.1, .66, .825, 2.6, .66, 1.425, 2.4, .25, 2.025, 2.3, .25, 2.1, 3.3, .25, 2.4, 2.7, .25, 2.4, 2.8, 0, 2.475, 2.8, -.25, 2.475, 3.525, -.25, 2.49375, 3.525, 0, 2.49375, 2.9, 0, 2.475, 2.9, -.15, 2.475, 3.45, -.15, 2.5125, 3.45, 0, 2.5125, 2.8, 0, 2.4, 2.8, -.15, 2.4, 3.2, -.15, 2.4, 3.2, 0, 2.4, 3.525, .25, 2.49375, 2.8, .25, 2.475, 3.45, .15, 2.5125, 2.9, .15, 2.475, 3.2, .15, 2.4, 2.8, .15, 2.4, 0, 0, 3.15, .8, 0, 3.15, .8, -.45, 3.15, .45, -.8, 3.15, 0, -.8, 3.15, 0, 0, 2.85, .2, 0, 2.7, .2, -.112, 2.7, .112, -.2, 2.7, 0, -.2, 2.7, -.45, -.8, 3.15, -.8, -.45, 3.15, -.8, 0, 3.15, -.112, -.2, 2.7, -.2, -.112, 2.7, -.2, 0, 2.7, -.8, .45, 3.15, -.45, .8, 3.15, 0, .8, 3.15, -.2, .112, 2.7, -.112, .2, 2.7, 0, .2, 2.7, .45, .8, 3.15, .8, .45, 3.15, .112, .2, 2.7, .2, .112, 2.7, .4, 0, 2.55, .4, -.224, 2.55, .224, -.4, 2.55, 0, -.4, 2.55, 1.3, 0, 2.55, 1.3, -.728, 2.55, .728, -1.3, 2.55, 0, -1.3, 2.55, 1.3, 0, 2.4, 1.3, -.728, 2.4, .728, -1.3, 2.4, 0, -1.3, 2.4, -.224, -.4, 2.55, -.4, -.224, 2.55, -.4, 0, 2.55, -.728, -1.3, 2.55, -1.3, -.728, 2.55, -1.3, 0, 2.55, -.728, -1.3, 2.4, -1.3, -.728, 2.4, -1.3, 0, 2.4, -.4, .224, 2.55, -.224, .4, 2.55, 0, .4, 2.55, -1.3, .728, 2.55, -.728, 1.3, 2.55, 0, 1.3, 2.55, -1.3, .728, 2.4, -.728, 1.3, 2.4, 0, 1.3, 2.4, .224, .4, 2.55, .4, .224, 2.55, .728, 1.3, 2.55, 1.3, .728, 2.55, .728, 1.3, 2.4, 1.3, .728, 2.4, 0, 0, 0, 1.425, 0, 0, 1.425, .798, 0, .798, 1.425, 0, 0, 1.425, 0, 1.5, 0, .075, 1.5, .84, .075, .84, 1.5, .075, 0, 1.5, .075, -.798, 1.425, 0, -1.425, .798, 0, -1.425, 0, 0, -.84, 1.5, .075, -1.5, .84, .075, -1.5, 0, .075, -1.425, -.798, 0, -.798, -1.425, 0, 0, -1.425, 0, -1.5, -.84, .075, -.84, -1.5, .075, 0, -1.5, .075, .798, -1.425, 0, 1.425, -.798, 0, .84, -1.5, .075, 1.5, -.84, .075 ]; super(); size = size || 50; segments = segments !== void 0 ? Math.max(2, Math.floor(segments) || 10) : 10; bottom = bottom === void 0 ? true : bottom; lid = lid === void 0 ? true : lid; body = body === void 0 ? true : body; fitLid = fitLid === void 0 ? true : fitLid; const blinnScale = 1.3; blinn = blinn === void 0 ? true : blinn; const maxHeight2 = 3.15 * (blinn ? 1 : blinnScale) / 2; const trueSize = size / maxHeight2; let numTriangles = bottom ? (8 * segments - 4) * segments : 0; numTriangles += lid ? (16 * segments - 4) * segments : 0; numTriangles += body ? 40 * segments * segments : 0; const indices = new Uint32Array(numTriangles * 3); let numVertices = bottom ? 4 : 0; numVertices += lid ? 8 : 0; numVertices += body ? 20 : 0; numVertices *= (segments + 1) * (segments + 1); const vertices = new Float32Array(numVertices * 3); const normals = new Float32Array(numVertices * 3); const uvs = new Float32Array(numVertices * 2); const ms = new Matrix4(); ms.set(-1, 3, -3, 1, 3, -6, 3, 0, -3, 3, 0, 0, 1, 0, 0, 0); const g = []; let i, r, c; const sp = []; const tp = []; const dsp = []; const dtp = []; const mgm = []; const vert = []; const sdir = []; const tdir = []; const norm = new Vector3(); let tcoord; let sstep, tstep; let vertPerRow; let s, t, sval, tval, p; let dsval = 0; let dtval = 0; const normOut = new Vector3(); let v1, v2, v3, v4; const gmx = new Matrix4(); const tmtx = new Matrix4(); const vsp = new Vector4(); const vtp = new Vector4(); const vdsp = new Vector4(); const vdtp = new Vector4(); const vsdir = new Vector3(); const vtdir = new Vector3(); const mst = ms.clone(); mst.transpose(); const notDegenerate = (vtx1, vtx2, vtx3) => !(vertices[vtx1 * 3] === vertices[vtx2 * 3] && vertices[vtx1 * 3 + 1] === vertices[vtx2 * 3 + 1] && vertices[vtx1 * 3 + 2] === vertices[vtx2 * 3 + 2] || vertices[vtx1 * 3] === vertices[vtx3 * 3] && vertices[vtx1 * 3 + 1] === vertices[vtx3 * 3 + 1] && vertices[vtx1 * 3 + 2] === vertices[vtx3 * 3 + 2] || vertices[vtx2 * 3] === vertices[vtx3 * 3] && vertices[vtx2 * 3 + 1] === vertices[vtx3 * 3 + 1] && vertices[vtx2 * 3 + 2] === vertices[vtx3 * 3 + 2]); for (i = 0; i < 3; i++) mgm[i] = new Matrix4(); const minPatches = body ? 0 : 20; const maxPatches = bottom ? 32 : 28; vertPerRow = segments + 1; let surfCount = 0; let vertCount = 0; let normCount = 0; let uvCount = 0; let indexCount = 0; for (let surf = minPatches; surf < maxPatches; surf++) if (lid || surf < 20 || surf >= 28) { for (i = 0; i < 3; i++) { for (r = 0; r < 4; r++) for (c = 0; c < 4; c++) { g[c * 4 + r] = teapotVertices[teapotPatches[surf * 16 + r * 4 + c] * 3 + i]; if (fitLid && surf >= 20 && surf < 28 && i !== 2) g[c * 4 + r] *= 1.077; if (!blinn && i === 2) g[c * 4 + r] *= blinnScale; } gmx.set(g[0], g[1], g[2], g[3], g[4], g[5], g[6], g[7], g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]); tmtx.multiplyMatrices(gmx, ms); mgm[i].multiplyMatrices(mst, tmtx); } for (sstep = 0; sstep <= segments; sstep++) { s = sstep / segments; for (tstep = 0; tstep <= segments; tstep++) { t = tstep / segments; for (p = 4, sval = tval = 1; p--;) { sp[p] = sval; tp[p] = tval; sval *= s; tval *= t; if (p === 3) { dsp[p] = dtp[p] = 0; dsval = dtval = 1; } else { dsp[p] = dsval * (3 - p); dtp[p] = dtval * (3 - p); dsval *= s; dtval *= t; } } vsp.fromArray(sp); vtp.fromArray(tp); vdsp.fromArray(dsp); vdtp.fromArray(dtp); for (i = 0; i < 3; i++) { tcoord = vsp.clone(); tcoord.applyMatrix4(mgm[i]); vert[i] = tcoord.dot(vtp); tcoord = vdsp.clone(); tcoord.applyMatrix4(mgm[i]); sdir[i] = tcoord.dot(vtp); tcoord = vsp.clone(); tcoord.applyMatrix4(mgm[i]); tdir[i] = tcoord.dot(vdtp); } vsdir.fromArray(sdir); vtdir.fromArray(tdir); norm.crossVectors(vtdir, vsdir); norm.normalize(); if (vert[0] === 0 && vert[1] === 0) normOut.set(0, vert[2] > maxHeight2 ? 1 : -1, 0); else normOut.set(norm.x, norm.z, -norm.y); vertices[vertCount++] = trueSize * vert[0]; vertices[vertCount++] = trueSize * (vert[2] - maxHeight2); vertices[vertCount++] = -trueSize * vert[1]; normals[normCount++] = normOut.x; normals[normCount++] = normOut.y; normals[normCount++] = normOut.z; uvs[uvCount++] = 1 - t; uvs[uvCount++] = 1 - s; } } for (sstep = 0; sstep < segments; sstep++) for (tstep = 0; tstep < segments; tstep++) { v1 = surfCount * vertPerRow * vertPerRow + sstep * vertPerRow + tstep; v2 = v1 + 1; v3 = v2 + vertPerRow; v4 = v1 + vertPerRow; if (notDegenerate(v1, v2, v3)) { indices[indexCount++] = v1; indices[indexCount++] = v2; indices[indexCount++] = v3; } if (notDegenerate(v1, v3, v4)) { indices[indexCount++] = v1; indices[indexCount++] = v3; indices[indexCount++] = v4; } } surfCount++; } this.setIndex(new BufferAttribute(indices, 1)); this.setAttribute("position", new BufferAttribute(vertices, 3)); this.setAttribute("normal", new BufferAttribute(normals, 3)); this.setAttribute("uv", new BufferAttribute(uvs, 2)); this.computeBoundingSphere(); } }; //#endregion //#region 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 = 100, lineHeight = 1, letterSpacing = 0, ...rest } = parameters; if (font === void 0) super(); else { const shapes = font.generateShapes(text, size, { lineHeight, letterSpacing }); super(shapes, { ...rest, bevelEnabled, bevelSize, bevelThickness, depth: height }); } this.type = "TextGeometry"; } }; //#endregion //#region node_modules/three-stdlib/csm/CSMFrustum.js var inverseProjectionMatrix = /* @__PURE__ */ 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 isOrthographic = projectionMatrix.elements[11] === 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(v) { v.applyMatrix4(inverseProjectionMatrix); }); this.vertices.far[0].set(1, 1, 1); this.vertices.far[1].set(1, -1, 1); this.vertices.far[2].set(-1, -1, 1); this.vertices.far[3].set(-1, 1, 1); this.vertices.far.forEach(function(v) { v.applyMatrix4(inverseProjectionMatrix); const absZ = Math.abs(v.z); if (isOrthographic) v.z *= Math.min(maxFar / absZ, 1); else v.multiplyScalar(Math.min(maxFar / absZ, 1)); }); return this.vertices; } split(breaks, target) { while (breaks.length > target.length) target.push(new CSMFrustum()); target.length = breaks.length; for (let i = 0; i < breaks.length; i++) { const cascade = target[i]; if (i === 0) for (let 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[i - 1]); if (i === 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[i]); } } toSpace(cameraMatrix, target) { for (let i = 0; i < 4; i++) { target.vertices.near[i].copy(this.vertices.near[i]).applyMatrix4(cameraMatrix); target.vertices.far[i].copy(this.vertices.far[i]).applyMatrix4(cameraMatrix); } } }; //#endregion //#region node_modules/three-stdlib/csm/CSMShader.js var CSMShader = { lights_fragment_begin: ` GeometricContext geometry; geometry.position = - vViewPosition; geometry.normal = normal; geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); #ifdef CLEARCOAT geometry.clearcoatNormal = clearcoatNormal; #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometry, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometry, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometry, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometry, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES ) DirectionalLight directionalLight; float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear); #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #if defined( USE_SHADOWMAP ) && defined( CSM_FADE ) vec2 cascade; float cascadeCenter; float closestEdge; float margin; float csmx; float csmy; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, geometry, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) // NOTE: Depth gets larger away from the camera. // cascade.x is closer, cascade.y is further cascade = CSM_cascades[ i ]; cascadeCenter = ( cascade.x + cascade.y ) / 2.0; closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; margin = 0.25 * pow( closestEdge, 2.0 ); csmx = cascade.x - margin / 2.0; csmy = cascade.y + margin / 2.0; if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) { float dist = min( linearDepth - csmx, csmy - linearDepth ); float ratio = clamp( dist / margin, 0.0, 1.0 ); vec3 prevColor = directLight.color; directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter; directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); ReflectedLight prevLight = reflectedLight; RE_Direct( directLight, geometry, material, reflectedLight ); bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter; float blendRatio = shouldBlend ? ratio : 1.0; reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio ); reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio ); reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio ); } #endif } #pragma unroll_loop_end #else #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, geometry, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometry, material, reflectedLight ); #endif } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS) // compute the lights not casting shadows (if any) #pragma unroll_loop_start for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, geometry, directLight ); RE_Direct( directLight, geometry, material, reflectedLight ); } #pragma unroll_loop_end #endif #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, geometry, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometry, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); irradiance += getLightProbeIrradiance( lightProbe, geometry.normal ); #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); } #pragma unroll_loop_end #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif `, getlights_pars_begin() { return ` #if defined( USE_CSM ) && defined( CSM_CASCADES ) uniform vec2 CSM_cascades[CSM_CASCADES]; uniform float cameraNear; uniform float shadowFar; #endif ${ShaderChunk.lights_pars_begin} `; } }; //#endregion //#region node_modules/three-stdlib/csm/CSM.js var _cameraToLightMatrix = /* @__PURE__ */ new Matrix4(); var _lightSpaceFrustum = /* @__PURE__ */ new CSMFrustum(); var _center = /* @__PURE__ */ new Vector3(); var _bbox = /* @__PURE__ */ new Box3(); var _uniformArray = []; var _logArray = []; var CSM = class { constructor(data) { data = data || {}; this.camera = data.camera; this.parent = data.parent; this.cascades = data.cascades || 3; this.maxFar = data.maxFar || 1e5; this.mode = data.mode || "practical"; this.shadowMapSize = data.shadowMapSize || 2048; this.shadowBias = data.shadowBias || 1e-6; this.lightDirection = data.lightDirection || new Vector3(1, -1, 1).normalize(); this.lightIntensity = data.lightIntensity || 1; this.lightNear = data.lightNear || 1; this.lightFar = data.lightFar || 2e3; this.lightMargin = data.lightMargin || 200; this.customSplitsCallback = data.customSplitsCallback; this.fade = false; this.mainFrustum = new CSMFrustum(); this.frustums = []; this.breaks = []; this.lights = []; this.shaders = /* @__PURE__ */ new Map(); this.createLights(); this.updateFrustums(); this.injectInclude(); } createLights() { for (let i = 0; i < this.cascades; i++) { const light = new DirectionalLight(16777215, this.lightIntensity); light.castShadow = true; light.shadow.mapSize.width = this.shadowMapSize; light.shadow.mapSize.height = this.shadowMapSize; light.shadow.camera.near = this.lightNear; light.shadow.camera.far = this.lightFar; light.shadow.bias = this.shadowBias; this.parent.add(light); this.parent.add(light.target); this.lights.push(light); } } initCascades() { const camera = this.camera; camera.updateProjectionMatrix(); this.mainFrustum.setFromProjectionMatrix(camera.projectionMatrix, this.maxFar); this.mainFrustum.split(this.breaks, this.frustums); } updateShadowBounds() { const frustums = this.frustums; for (let i = 0; i < frustums.length; i++) { const shadowCam = this.lights[i].shadow.camera; const frustum = this.frustums[i]; const nearVerts = frustum.vertices.near; const farVerts = frustum.vertices.far; const point1 = farVerts[0]; let point2; if (point1.distanceTo(farVerts[2]) > point1.distanceTo(nearVerts[2])) point2 = farVerts[2]; else point2 = nearVerts[2]; let squaredBBWidth = point1.distanceTo(point2); if (this.fade) { const camera = this.camera; const far = Math.max(camera.far, this.maxFar); const linearDepth = frustum.vertices.far[0].z / (far - camera.near); const margin = .25 * Math.pow(linearDepth, 2) * (far - camera.near); squaredBBWidth += margin; } shadowCam.left = -squaredBBWidth / 2; shadowCam.right = squaredBBWidth / 2; shadowCam.top = squaredBBWidth / 2; shadowCam.bottom = -squaredBBWidth / 2; shadowCam.updateProjectionMatrix(); } } getBreaks() { const camera = this.camera; const far = Math.min(camera.far, this.maxFar); this.breaks.length = 0; switch (this.mode) { case "uniform": uniformSplit(this.cascades, camera.near, far, this.breaks); break; case "logarithmic": logarithmicSplit(this.cascades, camera.near, far, this.breaks); break; case "practical": practicalSplit(this.cascades, camera.near, far, .5, this.breaks); break; case "custom": if (this.customSplitsCallback === void 0) console.error("CSM: Custom split scheme callback not defined."); this.customSplitsCallback(this.cascades, camera.near, far, this.breaks); break; } function uniformSplit(amount, near, far2, target) { for (let i = 1; i < amount; i++) target.push((near + (far2 - near) * i / amount) / far2); target.push(1); } function logarithmicSplit(amount, near, far2, target) { for (let i = 1; i < amount; i++) target.push(near * (far2 / near) ** (i / amount) / far2); target.push(1); } function practicalSplit(amount, near, far2, lambda, target) { _uniformArray.length = 0; _logArray.length = 0; logarithmicSplit(amount, near, far2, _logArray); uniformSplit(amount, near, far2, _uniformArray); for (let i = 1; i < amount; i++) target.push(MathUtils.lerp(_uniformArray[i - 1], _logArray[i - 1], lambda)); target.push(1); } } update() { const camera = this.camera; const frustums = this.frustums; for (let i = 0; i < frustums.length; i++) { const light = this.lights[i]; const shadowCam = light.shadow.camera; const texelWidth = (shadowCam.right - shadowCam.left) / this.shadowMapSize; const texelHeight = (shadowCam.top - shadowCam.bottom) / this.shadowMapSize; light.shadow.camera.updateMatrixWorld(true); _cameraToLightMatrix.multiplyMatrices(light.shadow.camera.matrixWorldInverse, camera.matrixWorld); frustums[i].toSpace(_cameraToLightMatrix, _lightSpaceFrustum); const nearVerts = _lightSpaceFrustum.vertices.near; const farVerts = _lightSpaceFrustum.vertices.far; _bbox.makeEmpty(); for (let j = 0; j < 4; j++) { _bbox.expandByPoint(nearVerts[j]); _bbox.expandByPoint(farVerts[j]); } _bbox.getCenter(_center); _center.z = _bbox.max.z + this.lightMargin; _center.x = Math.floor(_center.x / texelWidth) * texelWidth; _center.y = Math.floor(_center.y / texelHeight) * texelHeight; _center.applyMatrix4(light.shadow.camera.matrixWorld); light.position.copy(_center); light.target.position.copy(_center); light.target.position.x += this.lightDirection.x; light.target.position.y += this.lightDirection.y; light.target.position.z += this.lightDirection.z; } } injectInclude() { ShaderChunk.lights_fragment_begin = CSMShader.lights_fragment_begin; ShaderChunk.lights_pars_begin = CSMShader.lights_pars_begin; } setupMaterial(material) { material.defines = material.defines || {}; material.defines.USE_CSM = 1; material.defines.CSM_CASCADES = this.cascades; if (this.fade) material.defines.CSM_FADE = ""; const breaksVec2 = []; const scope = this; const shaders = this.shaders; material.onBeforeCompile = function(shader) { const far = Math.min(scope.camera.far, scope.maxFar); scope.getExtendedBreaks(breaksVec2); shader.uniforms.CSM_cascades = { value: breaksVec2 }; shader.uniforms.cameraNear = { value: scope.camera.near }; shader.uniforms.shadowFar = { value: far }; shaders.set(material, shader); }; shaders.set(material, null); } updateUniforms() { const far = Math.min(this.camera.far, this.maxFar); this.shaders.forEach(function(shader, material) { if (shader !== null) { const uniforms = shader.uniforms; this.getExtendedBreaks(uniforms.CSM_cascades.value); uniforms.cameraNear.value = this.camera.near; uniforms.shadowFar.value = far; } if (!this.fade && "CSM_FADE" in material.defines) { delete material.defines.CSM_FADE; material.needsUpdate = true; } else if (this.fade && !("CSM_FADE" in material.defines)) { material.defines.CSM_FADE = ""; material.needsUpdate = true; } }, this); } getExtendedBreaks(target) { while (target.length < this.breaks.length) target.push(new Vector2()); target.length = this.breaks.length; for (let i = 0; i < this.cascades; i++) { const amount = this.breaks[i]; const prev = this.breaks[i - 1] || 0; target[i].x = prev; target[i].y = amount; } } updateFrustums() { this.getBreaks(); this.initCascades(); this.updateShadowBounds(); this.updateUniforms(); } remove() { for (let i = 0; i < this.lights.length; i++) this.parent.remove(this.lights[i]); } dispose() { const shaders = this.shaders; shaders.forEach(function(shader, material) { delete material.onBeforeCompile; delete material.defines.USE_CSM; delete material.defines.CSM_CASCADES; delete material.defines.CSM_FADE; if (shader !== null) { delete shader.uniforms.CSM_cascades; delete shader.uniforms.cameraNear; delete shader.uniforms.shadowFar; } material.needsUpdate = true; }); shaders.clear(); } }; //#endregion //#region node_modules/three-stdlib/csm/CSMHelper.js var CSMHelper = class extends Group { constructor(csm) { super(); this.csm = csm; this.displayFrustum = true; this.displayPlanes = true; this.displayShadowBounds = true; const indices = new Uint16Array([ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ]); const positions = new Float32Array(24); const frustumGeometry = new BufferGeometry(); frustumGeometry.setIndex(new BufferAttribute(indices, 1)); frustumGeometry.setAttribute("position", new BufferAttribute(positions, 3, false)); const frustumLines = new LineSegments(frustumGeometry, new LineBasicMaterial()); this.add(frustumLines); this.frustumLines = frustumLines; this.cascadeLines = []; this.cascadePlanes = []; this.shadowLines = []; } updateVisibility() { const displayFrustum = this.displayFrustum; const displayPlanes = this.displayPlanes; const displayShadowBounds = this.displayShadowBounds; const frustumLines = this.frustumLines; const cascadeLines = this.cascadeLines; const cascadePlanes = this.cascadePlanes; const shadowLines = this.shadowLines; for (let i = 0, l = cascadeLines.length; i < l; i++) { const cascadeLine = cascadeLines[i]; const cascadePlane = cascadePlanes[i]; const shadowLineGroup = shadowLines[i]; cascadeLine.visible = displayFrustum; cascadePlane.visible = displayFrustum && displayPlanes; shadowLineGroup.visible = displayShadowBounds; } frustumLines.visible = displayFrustum; } update() { const csm = this.csm; const camera = csm.camera; const cascades = csm.cascades; const mainFrustum = csm.mainFrustum; const frustums = csm.frustums; const lights = csm.lights; const frustumLinePositions = this.frustumLines.geometry.getAttribute("position"); const cascadeLines = this.cascadeLines; const cascadePlanes = this.cascadePlanes; const shadowLines = this.shadowLines; this.position.copy(camera.position); this.quaternion.copy(camera.quaternion); this.scale.copy(camera.scale); this.updateMatrixWorld(true); while (cascadeLines.length > cascades) { this.remove(cascadeLines.pop()); this.remove(cascadePlanes.pop()); this.remove(shadowLines.pop()); } while (cascadeLines.length < cascades) { const cascadeLine = new Box3Helper(new Box3(), 16777215); const planeMat = new MeshBasicMaterial({ transparent: true, opacity: .1, depthWrite: false, side: 2 }); const cascadePlane = new Mesh(new PlaneGeometry(), planeMat); const shadowLineGroup = new Group(); const shadowLine = new Box3Helper(new Box3(), 16776960); shadowLineGroup.add(shadowLine); this.add(cascadeLine); this.add(cascadePlane); this.add(shadowLineGroup); cascadeLines.push(cascadeLine); cascadePlanes.push(cascadePlane); shadowLines.push(shadowLineGroup); } for (let i = 0; i < cascades; i++) { const frustum = frustums[i]; const shadowCam = lights[i].shadow.camera; const farVerts2 = frustum.vertices.far; const cascadeLine = cascadeLines[i]; const cascadePlane = cascadePlanes[i]; const shadowLineGroup = shadowLines[i]; const shadowLine = shadowLineGroup.children[0]; cascadeLine.box.min.copy(farVerts2[2]); cascadeLine.box.max.copy(farVerts2[0]); cascadeLine.box.max.z += 1e-4; cascadePlane.position.addVectors(farVerts2[0], farVerts2[2]); cascadePlane.position.multiplyScalar(.5); cascadePlane.scale.subVectors(farVerts2[0], farVerts2[2]); cascadePlane.scale.z = 1e-4; this.remove(shadowLineGroup); shadowLineGroup.position.copy(shadowCam.position); shadowLineGroup.quaternion.copy(shadowCam.quaternion); shadowLineGroup.scale.copy(shadowCam.scale); shadowLineGroup.updateMatrixWorld(true); this.attach(shadowLineGroup); shadowLine.box.min.set(shadowCam.bottom, shadowCam.left, -shadowCam.far); shadowLine.box.max.set(shadowCam.top, shadowCam.right, -shadowCam.near); } const nearVerts = mainFrustum.vertices.near; const farVerts = mainFrustum.vertices.far; frustumLinePositions.setXYZ(0, farVerts[0].x, farVerts[0].y, farVerts[0].z); frustumLinePositions.setXYZ(1, farVerts[3].x, farVerts[3].y, farVerts[3].z); frustumLinePositions.setXYZ(2, farVerts[2].x, farVerts[2].y, farVerts[2].z); frustumLinePositions.setXYZ(3, farVerts[1].x, farVerts[1].y, farVerts[1].z); frustumLinePositions.setXYZ(4, nearVerts[0].x, nearVerts[0].y, nearVerts[0].z); frustumLinePositions.setXYZ(5, nearVerts[3].x, nearVerts[3].y, nearVerts[3].z); frustumLinePositions.setXYZ(6, nearVerts[2].x, nearVerts[2].y, nearVerts[2].z); frustumLinePositions.setXYZ(7, nearVerts[1].x, nearVerts[1].y, nearVerts[1].z); frustumLinePositions.needsUpdate = true; } }; //#endregion //#region node_modules/three-stdlib/shaders/ACESFilmicToneMappingShader.js var ACESFilmicToneMappingShader = { uniforms: { tDiffuse: { value: null }, exposure: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` #define saturate(a) clamp( a, 0.0, 1.0 ) uniform sampler2D tDiffuse; uniform float exposure; varying vec2 vUv; vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); // ODT_SAT => XYZ => D60_2_D65 => sRGB const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color = ACESInputMat * color; // Apply RRT and ODT color = RRTAndODTFit( color ); color = ACESOutputMat * color; // Clamp to [0, 1] return saturate( color ); } void main() { vec4 tex = texture2D( tDiffuse, vUv ); tex.rgb *= exposure / 0.6; // pre-exposed, outside of the tone mapping function gl_FragColor = vec4( ACESFilmicToneMapping( tex.rgb ), tex.a ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/BasicShader.js var BasicShader = { uniforms: {}, vertexShader: ` void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` void main() { gl_FragColor = vec4( 1.0, 0.0, 0.0, 0.5 ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/BleachBypassShader.js var BleachBypassShader = { uniforms: { tDiffuse: { value: null }, opacity: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform float opacity; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 base = texture2D( tDiffuse, vUv ); vec3 lumCoeff = vec3( 0.25, 0.65, 0.1 ); float lum = dot( lumCoeff, base.rgb ); vec3 blend = vec3( lum ); float L = min( 1.0, max( 0.0, 10.0 * ( lum - 0.45 ) ) ); vec3 result1 = 2.0 * base.rgb * blend; vec3 result2 = 1.0 - 2.0 * ( 1.0 - blend ) * ( 1.0 - base.rgb ); vec3 newColor = mix( result1, result2, L ); float A2 = opacity * base.a; vec3 mixRGB = A2 * newColor.rgb; mixRGB += ( ( 1.0 - A2 ) * base.rgb ); gl_FragColor = vec4( mixRGB, base.a ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/BlendShader.js var BlendShader = { uniforms: { tDiffuse1: { value: null }, tDiffuse2: { value: null }, mixRatio: { value: .5 }, opacity: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform float opacity; uniform float mixRatio; uniform sampler2D tDiffuse1; uniform sampler2D tDiffuse2; varying vec2 vUv; void main() { vec4 texel1 = texture2D( tDiffuse1, vUv ); vec4 texel2 = texture2D( tDiffuse2, vUv ); gl_FragColor = opacity * mix( texel1, texel2, mixRatio ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/BrightnessContrastShader.js var BrightnessContrastShader = { uniforms: { tDiffuse: { value: null }, brightness: { value: 0 }, contrast: { value: 0 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform float brightness; uniform float contrast; varying vec2 vUv; void main() { gl_FragColor = texture2D( tDiffuse, vUv ); gl_FragColor.rgb += brightness; if (contrast > 0.0) { gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - contrast) + 0.5; } else { gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + contrast) + 0.5; } } ` }; //#endregion //#region node_modules/three-stdlib/shaders/ColorCorrectionShader.js var ColorCorrectionShader = { uniforms: { tDiffuse: { value: null }, powRGB: { value: /* @__PURE__ */ new Vector3(2, 2, 2) }, mulRGB: { value: /* @__PURE__ */ new Vector3(1, 1, 1) }, addRGB: { value: /* @__PURE__ */ new Vector3(0, 0, 0) } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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 ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/ColorifyShader.js var ColorifyShader = { uniforms: { tDiffuse: { value: null }, color: { value: /* @__PURE__ */ new Color(16777215) } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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 ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/DOFMipMapShader.js var DOFMipMapShader = { uniforms: { tColor: { value: null }, tDepth: { value: null }, focus: { value: 1 }, maxblur: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform float focus; uniform float maxblur; uniform sampler2D tColor; uniform sampler2D tDepth; varying vec2 vUv; void main() { vec4 depth = texture2D( tDepth, vUv ); float factor = depth.x - focus; vec4 col = texture2D( tColor, vUv, 2.0 * maxblur * abs( focus - depth.x ) ); gl_FragColor = col; gl_FragColor.a = 1.0; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/FXAAShader.js var FXAAShader = { uniforms: { tDiffuse: { value: null }, resolution: { value: /* @__PURE__ */ new Vector2(1 / 1024, 1 / 512) } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/FocusShader.js var FocusShader = { uniforms: { tDiffuse: { value: null }, screenWidth: { value: 1024 }, screenHeight: { value: 1024 }, sampleDistance: { value: .94 }, waveFactor: { value: .00125 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform float screenWidth; uniform float screenHeight; uniform float sampleDistance; uniform float waveFactor; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 color, org, tmp, add; float sample_dist, f; vec2 vin; vec2 uv = vUv; add = color = org = texture2D( tDiffuse, uv ); vin = ( uv - vec2( 0.5 ) ) * vec2( 1.4 ); sample_dist = dot( vin, vin ) * 2.0; f = ( waveFactor * 100.0 + sample_dist ) * sampleDistance * 4.0; vec2 sampleSize = vec2( 1.0 / screenWidth, 1.0 / screenHeight ) * vec2( f ); add += tmp = texture2D( tDiffuse, uv + vec2( 0.111964, 0.993712 ) * sampleSize ); if( tmp.b < color.b ) color = tmp; add += tmp = texture2D( tDiffuse, uv + vec2( 0.846724, 0.532032 ) * sampleSize ); if( tmp.b < color.b ) color = tmp; add += tmp = texture2D( tDiffuse, uv + vec2( 0.943883, -0.330279 ) * sampleSize ); if( tmp.b < color.b ) color = tmp; add += tmp = texture2D( tDiffuse, uv + vec2( 0.330279, -0.943883 ) * sampleSize ); if( tmp.b < color.b ) color = tmp; add += tmp = texture2D( tDiffuse, uv + vec2( -0.532032, -0.846724 ) * sampleSize ); if( tmp.b < color.b ) color = tmp; add += tmp = texture2D( tDiffuse, uv + vec2( -0.993712, -0.111964 ) * sampleSize ); if( tmp.b < color.b ) color = tmp; add += tmp = texture2D( tDiffuse, uv + vec2( -0.707107, 0.707107 ) * sampleSize ); if( tmp.b < color.b ) color = tmp; color = color * vec4( 2.0 ) - ( add / vec4( 8.0 ) ); color = color + ( add / vec4( 8.0 ) - color ) * ( vec4( 1.0 ) - vec4( sample_dist * 0.5 ) ); gl_FragColor = vec4( color.rgb * color.rgb * vec3( 0.95 ) + color.rgb, 1.0 ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/FreiChenShader.js var FreiChenShader = { uniforms: { tDiffuse: { value: null }, aspect: { value: /* @__PURE__ */ new Vector2(512, 512) } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/FresnelShader.js var FresnelShader = { uniforms: { mRefractionRatio: { value: 1.02 }, mFresnelBias: { value: .1 }, mFresnelPower: { value: 2 }, mFresnelScale: { value: 1 }, tCube: { value: null } }, vertexShader: ` uniform float mRefractionRatio; uniform float mFresnelBias; uniform float mFresnelScale; uniform float mFresnelPower; varying vec3 vReflect; varying vec3 vRefract[3]; varying float vReflectionFactor; void main() { vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal ); vec3 I = worldPosition.xyz - cameraPosition; vReflect = reflect( I, worldNormal ); vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio ); vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 ); vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 ); vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower ); gl_Position = projectionMatrix * mvPosition; } `, fragmentShader: ` uniform samplerCube tCube; varying vec3 vReflect; varying vec3 vRefract[3]; varying float vReflectionFactor; void main() { vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) ); vec4 refractedColor = vec4( 1.0 ); refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r; refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g; refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b; gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/GammaCorrectionShader.js var GammaCorrectionShader = { uniforms: { tDiffuse: { value: null } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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 } ` }; //#endregion //#region node_modules/three-stdlib/shaders/GodRaysShader.js var GodRaysDepthMaskShader = { uniforms: { tInput: { value: null } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` varying vec2 vUv; uniform sampler2D tInput; void main() { gl_FragColor = vec4( 1.0 ) - texture2D( tInput, vUv ); } ` }; var GodRaysGenerateShader = { uniforms: { tInput: { value: null }, fStepSize: { value: 1 }, vSunPositionScreenSpace: { value: /* @__PURE__ */ new Vector3() } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` #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 GodRaysCombineShader = { uniforms: { tColors: { value: null }, tGodRays: { value: null }, fGodRayIntensity: { value: .69 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` varying vec2 vUv; uniform sampler2D tColors; uniform sampler2D tGodRays; uniform float fGodRayIntensity; void main() { // Since THREE.MeshDepthMaterial renders foreground objects white and background // objects black, the god-rays will be white streaks. Therefore value is inverted // before being combined with tColors gl_FragColor = texture2D( tColors, vUv ) + fGodRayIntensity * vec4( 1.0 - texture2D( tGodRays, vUv ).r ); gl_FragColor.a = 1.0; } ` }; var GodRaysFakeSunShader = { uniforms: { vSunPositionScreenSpace: { value: /* @__PURE__ */ new Vector3() }, fAspect: { value: 1 }, sunColor: { value: /* @__PURE__ */ new Color(16772608) }, bgColor: { value: /* @__PURE__ */ new Color(0) } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/HorizontalBlurShader.js var HorizontalBlurShader = { uniforms: { tDiffuse: { value: null }, h: { value: 1 / 512 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/HorizontalTiltShiftShader.js var HorizontalTiltShiftShader = { uniforms: { tDiffuse: { value: null }, h: { value: 1 / 512 }, r: { value: .35 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/HueSaturationShader.js var HueSaturationShader = { uniforms: { tDiffuse: { value: null }, hue: { value: 0 }, saturation: { value: 0 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform float hue; uniform float saturation; varying vec2 vUv; void main() { gl_FragColor = texture2D( tDiffuse, vUv ); // hue float angle = hue * 3.14159265; float s = sin(angle), c = cos(angle); vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0; float len = length(gl_FragColor.rgb); gl_FragColor.rgb = vec3( dot(gl_FragColor.rgb, weights.xyz), dot(gl_FragColor.rgb, weights.zxy), dot(gl_FragColor.rgb, weights.yzx) ); // saturation float average = (gl_FragColor.r + gl_FragColor.g + gl_FragColor.b) / 3.0; if (saturation > 0.0) { gl_FragColor.rgb += (average - gl_FragColor.rgb) * (1.0 - 1.0 / (1.001 - saturation)); } else { gl_FragColor.rgb += (average - gl_FragColor.rgb) * (-saturation); } } ` }; //#endregion //#region node_modules/three-stdlib/shaders/KaleidoShader.js var KaleidoShader = { uniforms: { tDiffuse: { value: null }, sides: { value: 6 }, angle: { value: 0 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform float sides; uniform float angle; varying vec2 vUv; void main() { vec2 p = vUv - 0.5; float r = length(p); float a = atan(p.y, p.x) + angle; float tau = 2. * 3.1416 ; a = mod(a, tau/sides); a = abs(a - tau/sides/2.) ; p = r * vec2(cos(a), sin(a)); vec4 color = texture2D(tDiffuse, p + 0.5); gl_FragColor = color; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/MirrorShader.js var MirrorShader = { uniforms: { tDiffuse: { value: null }, side: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform int side; varying vec2 vUv; void main() { vec2 p = vUv; if (side == 0){ if (p.x > 0.5) p.x = 1.0 - p.x; }else if (side == 1){ if (p.x < 0.5) p.x = 1.0 - p.x; }else if (side == 2){ if (p.y < 0.5) p.y = 1.0 - p.y; }else if (side == 3){ if (p.y > 0.5) p.y = 1.0 - p.y; } vec4 color = texture2D(tDiffuse, p); gl_FragColor = color; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/NormalMapShader.js var NormalMapShader = { uniforms: { heightMap: { value: null }, resolution: { value: /* @__PURE__ */ new Vector2(512, 512) }, scale: { value: /* @__PURE__ */ new Vector2(1, 1) }, height: { value: .05 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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 ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/ParallaxShader.js var ParallaxShader = { modes: { none: "NO_PARALLAX", basic: "USE_BASIC_PARALLAX", steep: "USE_STEEP_PARALLAX", occlusion: "USE_OCLUSION_PARALLAX", relief: "USE_RELIEF_PARALLAX" }, uniforms: { bumpMap: { value: null }, map: { value: null }, parallaxScale: { value: null }, parallaxMinLayers: { value: null }, parallaxMaxLayers: { value: null } }, vertexShader: ` varying vec2 vUv; varying vec3 vViewPosition; varying vec3 vNormal; void main() { vUv = uv; vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); vViewPosition = -mvPosition.xyz; vNormal = normalize( normalMatrix * normal ); gl_Position = projectionMatrix * mvPosition; } `, fragmentShader: ` uniform sampler2D bumpMap; uniform sampler2D map; uniform float parallaxScale; uniform float parallaxMinLayers; uniform float parallaxMaxLayers; varying vec2 vUv; varying vec3 vViewPosition; varying vec3 vNormal; #ifdef USE_BASIC_PARALLAX vec2 parallaxMap( in vec3 V ) { float initialHeight = texture2D( bumpMap, vUv ).r; // No Offset Limitting: messy, floating output at grazing angles. //vec2 texCoordOffset = parallaxScale * V.xy / V.z * initialHeight; // Offset Limiting vec2 texCoordOffset = parallaxScale * V.xy * initialHeight; return vUv - texCoordOffset; } #else vec2 parallaxMap( in vec3 V ) { // Determine number of layers from angle between V and N float numLayers = mix( parallaxMaxLayers, parallaxMinLayers, abs( dot( vec3( 0.0, 0.0, 1.0 ), V ) ) ); float layerHeight = 1.0 / numLayers; float currentLayerHeight = 0.0; // Shift of texture coordinates for each iteration vec2 dtex = parallaxScale * V.xy / V.z / numLayers; vec2 currentTextureCoords = vUv; float heightFromTexture = texture2D( bumpMap, currentTextureCoords ).r; // while ( heightFromTexture > currentLayerHeight ) // Infinite loops are not well supported. Do a "large" finite // loop, but not too large, as it slows down some compilers. for ( int i = 0; i < 30; i += 1 ) { if ( heightFromTexture <= currentLayerHeight ) { break; } currentLayerHeight += layerHeight; // Shift texture coordinates along vector V currentTextureCoords -= dtex; heightFromTexture = texture2D( bumpMap, currentTextureCoords ).r; } #ifdef USE_STEEP_PARALLAX return currentTextureCoords; #elif defined( USE_RELIEF_PARALLAX ) vec2 deltaTexCoord = dtex / 2.0; float deltaHeight = layerHeight / 2.0; // Return to the mid point of previous layer currentTextureCoords += deltaTexCoord; currentLayerHeight -= deltaHeight; // Binary search to increase precision of Steep Parallax Mapping const int numSearches = 5; for ( int i = 0; i < numSearches; i += 1 ) { deltaTexCoord /= 2.0; deltaHeight /= 2.0; heightFromTexture = texture2D( bumpMap, currentTextureCoords ).r; // Shift along or against vector V if( heightFromTexture > currentLayerHeight ) { // Below the surface currentTextureCoords -= deltaTexCoord; currentLayerHeight += deltaHeight; } else { // above the surface currentTextureCoords += deltaTexCoord; currentLayerHeight -= deltaHeight; } } return currentTextureCoords; #elif defined( USE_OCLUSION_PARALLAX ) vec2 prevTCoords = currentTextureCoords + dtex; // Heights for linear interpolation float nextH = heightFromTexture - currentLayerHeight; float prevH = texture2D( bumpMap, prevTCoords ).r - currentLayerHeight + layerHeight; // Proportions for linear interpolation float weight = nextH / ( nextH - prevH ); // Interpolation of texture coordinates return prevTCoords * weight + currentTextureCoords * ( 1.0 - weight ); #else // NO_PARALLAX return vUv; #endif } #endif vec2 perturbUv( vec3 surfPosition, vec3 surfNormal, vec3 viewPosition ) { vec2 texDx = dFdx( vUv ); vec2 texDy = dFdy( vUv ); vec3 vSigmaX = dFdx( surfPosition ); vec3 vSigmaY = dFdy( surfPosition ); vec3 vR1 = cross( vSigmaY, surfNormal ); vec3 vR2 = cross( surfNormal, vSigmaX ); float fDet = dot( vSigmaX, vR1 ); vec2 vProjVscr = ( 1.0 / fDet ) * vec2( dot( vR1, viewPosition ), dot( vR2, viewPosition ) ); vec3 vProjVtex; vProjVtex.xy = texDx * vProjVscr.x + texDy * vProjVscr.y; vProjVtex.z = dot( surfNormal, viewPosition ); return parallaxMap( vProjVtex ); } void main() { vec2 mapUv = perturbUv( -vViewPosition, normalize( vNormal ), normalize( vViewPosition ) ); gl_FragColor = texture2D( map, mapUv ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/PixelShader.js var PixelShader = { uniforms: { tDiffuse: { value: null }, resolution: { value: null }, pixelSize: { value: 1 } }, vertexShader: ` varying highp vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform float pixelSize; uniform vec2 resolution; varying highp vec2 vUv; void main(){ vec2 dxy = pixelSize / resolution; vec2 coord = dxy * floor( vUv / dxy ); gl_FragColor = texture2D(tDiffuse, coord); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/RGBShiftShader.js var RGBShiftShader = { uniforms: { tDiffuse: { value: null }, amount: { value: .005 }, angle: { value: 0 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform float amount; uniform float angle; varying vec2 vUv; void main() { vec2 offset = amount * vec2( cos(angle), sin(angle)); vec4 cr = texture2D(tDiffuse, vUv + offset); vec4 cga = texture2D(tDiffuse, vUv); vec4 cb = texture2D(tDiffuse, vUv - offset); gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/SepiaShader.js var SepiaShader = { uniforms: { tDiffuse: { value: null }, amount: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform float amount; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 color = texture2D( tDiffuse, vUv ); vec3 c = color.rgb; color.r = dot( c, vec3( 1.0 - 0.607 * amount, 0.769 * amount, 0.189 * amount ) ); color.g = dot( c, vec3( 0.349 * amount, 1.0 - 0.314 * amount, 0.168 * amount ) ); color.b = dot( c, vec3( 0.272 * amount, 0.534 * amount, 1.0 - 0.869 * amount ) ); gl_FragColor = vec4( min( vec3( 1.0 ), color.rgb ), color.a ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/SobelOperatorShader.js var SobelOperatorShader = { uniforms: { tDiffuse: { value: null }, resolution: { value: /* @__PURE__ */ new Vector2() } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; uniform vec2 resolution; varying vec2 vUv; void main() { vec2 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 ); } ` }; //#endregion //#region node_modules/three-stdlib/shaders/SubsurfaceScatteringShader.js var _SubsurfaceScatteringShader; function get() { if (_SubsurfaceScatteringShader) return _SubsurfaceScatteringShader; const meshphong_frag_head = ShaderChunk["meshphong_frag"].slice(0, ShaderChunk["meshphong_frag"].indexOf("void main() {")); const meshphong_frag_body = ShaderChunk["meshphong_frag"].slice(ShaderChunk["meshphong_frag"].indexOf("void main() {")); _SubsurfaceScatteringShader = { uniforms: UniformsUtils.merge([ShaderLib["phong"].uniforms, { thicknessMap: { value: null }, thicknessColor: { value: new Color(16777215) }, thicknessDistortion: { value: .1 }, thicknessAmbient: { value: 0 }, thicknessAttenuation: { value: .1 }, thicknessPower: { value: 2 }, thicknessScale: { value: 10 } }]), vertexShader: ` #define USE_UV ${ShaderChunk["meshphong_vert"]} `, fragmentShader: ` #define USE_UV', #define SUBSURFACE', ${meshphong_frag_head} uniform sampler2D thicknessMap; uniform float thicknessPower; uniform float thicknessScale; uniform float thicknessDistortion; uniform float thicknessAmbient; uniform float thicknessAttenuation; uniform vec3 thicknessColor; void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in GeometricContext geometry, inout ReflectedLight reflectedLight) { vec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r; vec3 scatteringHalf = normalize(directLight.direction + (geometry.normal * thicknessDistortion)); float scatteringDot = pow(saturate(dot(geometry.viewDir, -scatteringHalf)), thicknessPower) * thicknessScale; vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness; reflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color; } ${meshphong_frag_body.replace("#include ", ShaderChunk["lights_fragment_begin"].replace(/RE_Direct\( directLight, geometry, material, reflectedLight \);/g, ` RE_Direct( directLight, geometry, material, reflectedLight ); #if defined( SUBSURFACE ) && defined( USE_UV ) RE_Direct_Scattering(directLight, vUv, geometry, reflectedLight); #endif `))} ` }; return _SubsurfaceScatteringShader; } var SubsurfaceScatteringShader = { get uniforms() { return get().uniforms; }, set uniforms(value) { get().uniforms = value; }, get vertexShader() { return get().vertexShader; }, set vertexShader(value) { get().vertexShader = value; }, get fragmentShader() { return get().vertexShader; }, set fragmentShader(value) { get().vertexShader = value; } }; //#endregion //#region node_modules/three-stdlib/shaders/TechnicolorShader.js var TechnicolorShader = { uniforms: { tDiffuse: { value: null } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 tex = texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ); vec4 newTex = vec4(tex.r, (tex.g + tex.b) * .5, (tex.g + tex.b) * .5, 1.0); gl_FragColor = newTex; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/ToonShader.js var ToonShader1 = { uniforms: { uDirLightPos: { value: /* @__PURE__ */ new Vector3() }, uDirLightColor: { value: /* @__PURE__ */ new Color(15658734) }, uAmbientLightColor: { value: /* @__PURE__ */ new Color(328965) }, uBaseColor: { value: /* @__PURE__ */ new Color(16777215) } }, vertexShader: ` 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: ` 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: /* @__PURE__ */ new Vector3() }, uDirLightColor: { value: /* @__PURE__ */ new Color(15658734) }, uAmbientLightColor: { value: /* @__PURE__ */ new Color(328965) }, uBaseColor: { value: /* @__PURE__ */ new Color(15658734) }, uLineColor1: { value: /* @__PURE__ */ new Color(8421504) }, uLineColor2: { value: /* @__PURE__ */ new Color(0) }, uLineColor3: { value: /* @__PURE__ */ new Color(0) }, uLineColor4: { value: /* @__PURE__ */ new Color(0) } }, vertexShader: ` varying vec3 vNormal; void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); vNormal = normalize( normalMatrix * normal ); } `, fragmentShader: ` 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: /* @__PURE__ */ new Vector3() }, uDirLightColor: { value: /* @__PURE__ */ new Color(15658734) }, uAmbientLightColor: { value: /* @__PURE__ */ new Color(328965) }, uBaseColor: { value: /* @__PURE__ */ new Color(16777215) }, uLineColor1: { value: /* @__PURE__ */ new Color(0) }, uLineColor2: { value: /* @__PURE__ */ new Color(0) }, uLineColor3: { value: /* @__PURE__ */ new Color(0) }, uLineColor4: { value: /* @__PURE__ */ new Color(0) } }, vertexShader: ` varying vec3 vNormal; void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); vNormal = normalize( normalMatrix * normal ); } `, fragmentShader: ` 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: /* @__PURE__ */ new Vector3() }, uDirLightColor: { value: /* @__PURE__ */ new Color(15658734) }, uAmbientLightColor: { value: /* @__PURE__ */ new Color(328965) }, uBaseColor: { value: /* @__PURE__ */ new Color(16777215) }, uLineColor1: { value: /* @__PURE__ */ new Color(0) } }, vertexShader: ` varying vec3 vNormal; void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); vNormal = normalize( normalMatrix * normal ); } `, fragmentShader: ` 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 ); } } } ` }; //#endregion //#region node_modules/three-stdlib/shaders/TriangleBlurShader.js var TriangleBlurShader = { uniforms: { texture: { value: null }, delta: { value: /* @__PURE__ */ new Vector2(1, 1) } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` #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; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/VerticalBlurShader.js var VerticalBlurShader = { uniforms: { tDiffuse: { value: null }, v: { value: 1 / 512 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/VerticalTiltShiftShader.js var VerticalTiltShiftShader = { uniforms: { tDiffuse: { value: null }, v: { value: 1 / 512 }, r: { value: .35 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` 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; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/VignetteShader.js var VignetteShader = { uniforms: { tDiffuse: { value: null }, offset: { value: 1 }, darkness: { value: 1 } }, vertexShader: ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform float offset; uniform float darkness; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { // Eskils vignette vec4 texel = texture2D( tDiffuse, vUv ); vec2 uv = ( vUv - vec2( 0.5 ) ) * vec2( offset ); gl_FragColor = vec4( mix( texel.rgb, vec3( 1.0 - darkness ), dot( uv, uv ) ), texel.a ); /* // alternative version from glfx.js // this one makes more "dusty" look (as opposed to "burned") vec4 color = texture2D( tDiffuse, vUv ); float dist = distance( vUv, vec2( 0.5 ) ); color.rgb *= smoothstep( 0.8, offset * 0.799, dist *( darkness + offset ) ); gl_FragColor = color; */ } ` }; //#endregion //#region node_modules/three-stdlib/shaders/VolumeShader.js var VolumeRenderShader1 = { uniforms: { u_size: { value: /* @__PURE__ */ new Vector3(1, 1, 1) }, u_renderstyle: { value: 0 }, u_renderthreshold: { value: .5 }, u_clim: { value: /* @__PURE__ */ new Vector2(1, 1) }, u_data: { value: null }, u_cmdata: { value: null } }, vertexShader: ` 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: ` 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; } ` }; //#endregion //#region node_modules/three-stdlib/shaders/WaterRefractionShader.js var WaterRefractionShader = { uniforms: { color: { value: null }, time: { value: 0 }, tDiffuse: { value: null }, tDudv: { value: null }, textureMatrix: { value: null } }, vertexShader: ` uniform mat4 textureMatrix; varying vec2 vUv; varying vec4 vUvRefraction; void main() { vUv = uv; vUvRefraction = textureMatrix * vec4( position, 1.0 ); gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } `, fragmentShader: ` uniform vec3 color; uniform float time; uniform sampler2D tDiffuse; uniform sampler2D tDudv; varying vec2 vUv; varying vec4 vUvRefraction; float blendOverlay( float base, float blend ) { return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); } vec3 blendOverlay( vec3 base, vec3 blend ) { return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) ); } void main() { float waveStrength = 0.1; float waveSpeed = 0.03; // simple distortion (ripple) via dudv map (see https://www.youtube.com/watch?v=6B7IF6GOu7s) vec2 distortedUv = texture2D( tDudv, vec2( vUv.x + time * waveSpeed, vUv.y ) ).rg * waveStrength; distortedUv = vUv.xy + vec2( distortedUv.x, distortedUv.y + time * waveSpeed ); vec2 distortion = ( texture2D( tDudv, distortedUv ).rg * 2.0 - 1.0 ) * waveStrength; // new uv coords vec4 uv = vec4( vUvRefraction ); uv.xy += distortion; vec4 base = texture2DProj( tDiffuse, uv ); gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); } ` }; //#endregion //#region node_modules/three-stdlib/interactive/HTMLMesh.js var HTMLMesh = class extends Mesh { constructor(dom) { const texture = new HTMLTexture(dom); const geometry = new PlaneGeometry(texture.image.width * .001, texture.image.height * .001); const material = new MeshBasicMaterial({ map: texture, toneMapped: false, transparent: true }); super(geometry, material); function onEvent(event) { material.map.dispatchDOMEvent(event); } this.addEventListener("mousedown", onEvent); this.addEventListener("mousemove", onEvent); this.addEventListener("mouseup", onEvent); this.addEventListener("click", onEvent); this.dispose = function() { geometry.dispose(); material.dispose(); material.map.dispose(); canvases.delete(dom); this.removeEventListener("mousedown", onEvent); this.removeEventListener("mousemove", onEvent); this.removeEventListener("mouseup", onEvent); this.removeEventListener("click", onEvent); }; } }; var HTMLTexture = class extends CanvasTexture { constructor(dom) { super(html2canvas(dom)); this.dom = dom; this.anisotropy = 16; if ("colorSpace" in this) this.colorSpace = "srgb"; else this.encoding = 3001; this.minFilter = LinearFilter; this.magFilter = LinearFilter; const observer = new MutationObserver(() => { if (!this.scheduleUpdate) this.scheduleUpdate = setTimeout(() => this.update(), 16); }); observer.observe(dom, { attributes: true, childList: true, subtree: true, characterData: true }); this.observer = observer; } dispatchDOMEvent(event) { if (event.data) htmlevent(this.dom, event.type, event.data.x, event.data.y); } update() { this.image = html2canvas(this.dom); this.needsUpdate = true; this.scheduleUpdate = null; } dispose() { if (this.observer) this.observer.disconnect(); this.scheduleUpdate = clearTimeout(this.scheduleUpdate); super.dispose(); } }; var canvases = /* @__PURE__ */ new WeakMap(); function html2canvas(element) { const range = document.createRange(); const color = new Color(); function Clipper(context2) { const clips = []; let isClipping = false; function doClip() { if (isClipping) { isClipping = false; context2.restore(); } if (clips.length === 0) return; let minX = -Infinity, minY = -Infinity; let maxX = Infinity, maxY = Infinity; for (let i = 0; i < clips.length; i++) { const clip = clips[i]; minX = Math.max(minX, clip.x); minY = Math.max(minY, clip.y); maxX = Math.min(maxX, clip.x + clip.width); maxY = Math.min(maxY, clip.y + clip.height); } context2.save(); context2.beginPath(); context2.rect(minX, minY, maxX - minX, maxY - minY); context2.clip(); isClipping = true; } return { add: function(clip) { clips.push(clip); doClip(); }, remove: function() { clips.pop(); doClip(); } }; } function drawText(style, x, y, string) { if (string !== "") { if (style.textTransform === "uppercase") string = string.toUpperCase(); context.font = style.fontWeight + " " + style.fontSize + " " + style.fontFamily; context.textBaseline = "top"; context.fillStyle = style.color; context.fillText(string, x, y + parseFloat(style.fontSize) * .1); } } function buildRectPath(x, y, w, h, r) { if (w < 2 * r) r = w / 2; if (h < 2 * r) r = h / 2; context.beginPath(); context.moveTo(x + r, y); context.arcTo(x + w, y, x + w, y + h, r); context.arcTo(x + w, y + h, x, y + h, r); context.arcTo(x, y + h, x, y, r); context.arcTo(x, y, x + w, y, r); context.closePath(); } function drawBorder(style, which, x, y, width, height) { const borderWidth = style[which + "Width"]; const borderStyle = style[which + "Style"]; const borderColor = style[which + "Color"]; if (borderWidth !== "0px" && borderStyle !== "none" && borderColor !== "transparent" && borderColor !== "rgba(0, 0, 0, 0)") { context.strokeStyle = borderColor; context.lineWidth = parseFloat(borderWidth); context.beginPath(); context.moveTo(x, y); context.lineTo(x + width, y + height); context.stroke(); } } function drawElement(element2, style) { let x = 0, y = 0, width = 0, height = 0; if (element2.nodeType === Node.TEXT_NODE) { range.selectNode(element2); const rect = range.getBoundingClientRect(); x = rect.left - offset.left - .5; y = rect.top - offset.top - .5; width = rect.width; height = rect.height; drawText(style, x, y, element2.nodeValue.trim()); } else if (element2.nodeType === Node.COMMENT_NODE) return; else if (element2 instanceof HTMLCanvasElement) { if (element2.style.display === "none") return; context.save(); const dpr = window.devicePixelRatio; context.scale(1 / dpr, 1 / dpr); context.drawImage(element2, 0, 0); context.restore(); } else { if (element2.style.display === "none") return; const rect = element2.getBoundingClientRect(); x = rect.left - offset.left - .5; y = rect.top - offset.top - .5; width = rect.width; height = rect.height; style = window.getComputedStyle(element2); buildRectPath(x, y, width, height, parseFloat(style.borderRadius)); const backgroundColor = style.backgroundColor; if (backgroundColor !== "transparent" && backgroundColor !== "rgba(0, 0, 0, 0)") { context.fillStyle = backgroundColor; context.fill(); } const borders = [ "borderTop", "borderLeft", "borderBottom", "borderRight" ]; let match = true; let prevBorder = null; for (const border of borders) { if (prevBorder !== null) match = style[border + "Width"] === style[prevBorder + "Width"] && style[border + "Color"] === style[prevBorder + "Color"] && style[border + "Style"] === style[prevBorder + "Style"]; if (match === false) break; prevBorder = border; } if (match === true) { const width2 = parseFloat(style.borderTopWidth); if (style.borderTopWidth !== "0px" && style.borderTopStyle !== "none" && style.borderTopColor !== "transparent" && style.borderTopColor !== "rgba(0, 0, 0, 0)") { context.strokeStyle = style.borderTopColor; context.lineWidth = width2; context.stroke(); } } else { drawBorder(style, "borderTop", x, y, width, 0); drawBorder(style, "borderLeft", x, y, 0, height); drawBorder(style, "borderBottom", x, y + height, width, 0); drawBorder(style, "borderRight", x + width, y, 0, height); } if (element2 instanceof HTMLInputElement) { let accentColor = style.accentColor; if (accentColor === void 0 || accentColor === "auto") accentColor = style.color; color.set(accentColor); const accentTextColor = Math.sqrt(.299 * color.r ** 2 + .587 * color.g ** 2 + .114 * color.b ** 2) < .5 ? "white" : "#111111"; if (element2.type === "radio") { buildRectPath(x, y, width, height, height); context.fillStyle = "white"; context.strokeStyle = accentColor; context.lineWidth = 1; context.fill(); context.stroke(); if (element2.checked) { buildRectPath(x + 2, y + 2, width - 4, height - 4, height); context.fillStyle = accentColor; context.strokeStyle = accentTextColor; context.lineWidth = 2; context.fill(); context.stroke(); } } if (element2.type === "checkbox") { buildRectPath(x, y, width, height, 2); context.fillStyle = element2.checked ? accentColor : "white"; context.strokeStyle = element2.checked ? accentTextColor : accentColor; context.lineWidth = 1; context.stroke(); context.fill(); if (element2.checked) { const currentTextAlign = context.textAlign; context.textAlign = "center"; drawText({ color: accentTextColor, fontFamily: style.fontFamily, fontSize: height + "px", fontWeight: "bold" }, x + width / 2, y, "✔"); context.textAlign = currentTextAlign; } } if (element2.type === "range") { const [min, max, value] = [ "min", "max", "value" ].map((property) => parseFloat(element2[property])); const position = (value - min) / (max - min) * (width - height); buildRectPath(x, y + height / 4, width, height / 2, height / 4); context.fillStyle = accentTextColor; context.strokeStyle = accentColor; context.lineWidth = 1; context.fill(); context.stroke(); buildRectPath(x, y + height / 4, position + height / 2, height / 2, height / 4); context.fillStyle = accentColor; context.fill(); buildRectPath(x + position, y, height, height, height / 2); context.fillStyle = accentColor; context.fill(); } if (element2.type === "color" || element2.type === "text" || element2.type === "number") { clipper.add({ x, y, width, height }); drawText(style, x + parseInt(style.paddingLeft), y + parseInt(style.paddingTop), element2.value); clipper.remove(); } } } const isClipping = style.overflow === "auto" || style.overflow === "hidden"; if (isClipping) clipper.add({ x, y, width, height }); for (let i = 0; i < element2.childNodes.length; i++) drawElement(element2.childNodes[i], style); if (isClipping) clipper.remove(); } const offset = element.getBoundingClientRect(); let canvas = canvases.get(element); if (canvas === void 0) { canvas = document.createElement("canvas"); canvas.width = offset.width; canvas.height = offset.height; canvases.set(element, canvas); } const context = canvas.getContext("2d"); const clipper = new Clipper(context); drawElement(element); return canvas; } function htmlevent(element, event, x, y) { const mouseEventInit = { clientX: x * element.offsetWidth + element.offsetLeft, clientY: y * element.offsetHeight + element.offsetTop, view: element.ownerDocument.defaultView }; window.dispatchEvent(new MouseEvent(event, mouseEventInit)); const rect = element.getBoundingClientRect(); x = x * rect.width + rect.left; y = y * rect.height + rect.top; function traverse(element2) { if (element2.nodeType !== Node.TEXT_NODE && element2.nodeType !== Node.COMMENT_NODE) { const rect2 = element2.getBoundingClientRect(); if (x > rect2.left && x < rect2.right && y > rect2.top && y < rect2.bottom) { element2.dispatchEvent(new MouseEvent(event, mouseEventInit)); if (element2 instanceof HTMLInputElement && element2.type === "range" && (event === "mousedown" || event === "click")) { const [min, max] = ["min", "max"].map((property) => parseFloat(element2[property])); const width = rect2.width; const proportion = (x - rect2.x) / width; element2.value = min + (max - min) * proportion; element2.dispatchEvent(new InputEvent("input", { bubbles: true })); } } for (let i = 0; i < element2.childNodes.length; i++) traverse(element2.childNodes[i]); } } traverse(element); } //#endregion //#region node_modules/three-stdlib/interactive/InteractiveGroup.js var _pointer = /* @__PURE__ */ new Vector2(); var _event = { type: "", data: _pointer }; var InteractiveGroup = class extends Group { constructor(renderer, camera) { super(); const scope = this; const raycaster = new Raycaster(); const tempMatrix = new Matrix4(); const element = renderer.domElement; function onPointerEvent(event) { event.stopPropagation(); _pointer.x = event.clientX / element.clientWidth * 2 - 1; _pointer.y = -(event.clientY / element.clientHeight) * 2 + 1; raycaster.setFromCamera(_pointer, camera); const intersects = raycaster.intersectObjects(scope.children, false); if (intersects.length > 0) { const intersection = intersects[0]; const object = intersection.object; const uv = intersection.uv; _event.type = event.type; _event.data.set(uv.x, 1 - uv.y); object.dispatchEvent(_event); } } element.addEventListener("pointerdown", onPointerEvent); element.addEventListener("pointerup", onPointerEvent); element.addEventListener("pointermove", onPointerEvent); element.addEventListener("mousedown", onPointerEvent); element.addEventListener("mouseup", onPointerEvent); element.addEventListener("mousemove", onPointerEvent); element.addEventListener("click", onPointerEvent); const events = { move: "mousemove", select: "click", selectstart: "mousedown", selectend: "mouseup" }; function onXRControllerEvent(event) { const controller = event.target; tempMatrix.identity().extractRotation(controller.matrixWorld); raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld); raycaster.ray.direction.set(0, 0, -1).applyMatrix4(tempMatrix); const intersections = raycaster.intersectObjects(scope.children, false); if (intersections.length > 0) { const intersection = intersections[0]; const object = intersection.object; const uv = intersection.uv; _event.type = events[event.type]; _event.data.set(uv.x, 1 - uv.y); object.dispatchEvent(_event); } } const controller1 = renderer.xr.getController(0); controller1.addEventListener("move", onXRControllerEvent); controller1.addEventListener("select", onXRControllerEvent); controller1.addEventListener("selectstart", onXRControllerEvent); controller1.addEventListener("selectend", onXRControllerEvent); const controller2 = renderer.xr.getController(1); controller2.addEventListener("move", onXRControllerEvent); controller2.addEventListener("select", onXRControllerEvent); controller2.addEventListener("selectstart", onXRControllerEvent); controller2.addEventListener("selectend", onXRControllerEvent); } }; //#endregion //#region node_modules/three-stdlib/interactive/SelectionHelper.js var SelectionHelper = class { constructor(selectionBox, renderer, cssClassName) { this.element = document.createElement("div"); this.element.classList.add(cssClassName); this.element.style.pointerEvents = "none"; this.renderer = renderer; this.startPoint = new Vector2(); this.pointTopLeft = new Vector2(); this.pointBottomRight = new Vector2(); this.isDown = false; this.renderer.domElement.addEventListener("pointerdown", (event) => { this.isDown = true; this.onSelectStart(event); }); this.renderer.domElement.addEventListener("pointermove", (event) => { if (this.isDown) this.onSelectMove(event); }); this.renderer.domElement.addEventListener("pointerup", (event) => { this.isDown = false; this.onSelectOver(event); }); } onSelectStart(event) { this.renderer.domElement.parentElement.appendChild(this.element); this.element.style.left = `${event.clientX}px`; this.element.style.top = `${event.clientY}px`; this.element.style.width = "0px"; this.element.style.height = "0px"; this.startPoint.x = event.clientX; this.startPoint.y = event.clientY; } onSelectMove(event) { this.pointBottomRight.x = Math.max(this.startPoint.x, event.clientX); this.pointBottomRight.y = Math.max(this.startPoint.y, event.clientY); this.pointTopLeft.x = Math.min(this.startPoint.x, event.clientX); this.pointTopLeft.y = Math.min(this.startPoint.y, event.clientY); this.element.style.left = `${this.pointTopLeft.x}px`; this.element.style.top = `${this.pointTopLeft.y}px`; this.element.style.width = `${this.pointBottomRight.x - this.pointTopLeft.x}px`; this.element.style.height = `${this.pointBottomRight.y - this.pointTopLeft.y}px`; } onSelectOver() { this.element.parentElement.removeChild(this.element); } }; //#endregion //#region node_modules/three-stdlib/interactive/SelectionBox.js var frustum = /* @__PURE__ */ new Frustum(); var center = /* @__PURE__ */ new Vector3(); var tmpPoint = /* @__PURE__ */ new Vector3(); var vecNear = /* @__PURE__ */ new Vector3(); var vecTopLeft = /* @__PURE__ */ new Vector3(); var vecTopRight = /* @__PURE__ */ new Vector3(); var vecDownRight = /* @__PURE__ */ new Vector3(); var vecDownLeft = /* @__PURE__ */ new Vector3(); var vecFarTopLeft = /* @__PURE__ */ new Vector3(); var vecFarTopRight = /* @__PURE__ */ new Vector3(); var vecFarDownRight = /* @__PURE__ */ new Vector3(); var vecFarDownLeft = /* @__PURE__ */ new Vector3(); var vectemp1 = /* @__PURE__ */ new Vector3(); var vectemp2 = /* @__PURE__ */ new Vector3(); var vectemp3 = /* @__PURE__ */ 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(); center.copy(object.geometry.boundingSphere.center); center.applyMatrix4(object.matrixWorld); if (frustum2.containsPoint(center)) this.collection.push(object); } } if (object.children.length > 0) for (let x = 0; x < object.children.length; x++) this.searchChildInFrustum(frustum2, object.children[x]); } }; //#endregion //#region node_modules/three-stdlib/physics/AmmoPhysics.js async function AmmoPhysics() { if ("Ammo" in window === false) { console.error("AmmoPhysics: Couldn't find Ammo.js"); return; } const AmmoLib = await Ammo(); const frameRate = 60; const collisionConfiguration = new AmmoLib.btDefaultCollisionConfiguration(); const dispatcher = new AmmoLib.btCollisionDispatcher(collisionConfiguration); const broadphase = new AmmoLib.btDbvtBroadphase(); const solver = new AmmoLib.btSequentialImpulseConstraintSolver(); const world = new AmmoLib.btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); world.setGravity(new AmmoLib.btVector3(0, -9.8, 0)); const worldTransform = new AmmoLib.btTransform(); function getShape(geometry) { const parameters = geometry.parameters; if (geometry.type === "BoxGeometry") { const sx = parameters.width !== void 0 ? parameters.width / 2 : .5; const sy = parameters.height !== void 0 ? parameters.height / 2 : .5; const sz = parameters.depth !== void 0 ? parameters.depth / 2 : .5; const shape = new AmmoLib.btBoxShape(new AmmoLib.btVector3(sx, sy, sz)); shape.setMargin(.05); return shape; } else if (geometry.type === "SphereGeometry" || geometry.type === "IcosahedronGeometry") { const radius = parameters.radius !== void 0 ? parameters.radius : 1; const shape = new AmmoLib.btSphereShape(radius); shape.setMargin(.05); return shape; } return null; } const meshes = []; const meshMap = /* @__PURE__ */ new WeakMap(); function addMesh(mesh, mass = 0) { const shape = getShape(mesh.geometry); if (shape !== null) { if (mesh.isInstancedMesh) handleInstancedMesh(mesh, mass, shape); else if (mesh.isMesh) handleMesh(mesh, mass, shape); } } function handleMesh(mesh, mass, shape) { const position = mesh.position; const quaternion = mesh.quaternion; const transform = new AmmoLib.btTransform(); transform.setIdentity(); transform.setOrigin(new AmmoLib.btVector3(position.x, position.y, position.z)); transform.setRotation(new AmmoLib.btQuaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w)); const motionState = new AmmoLib.btDefaultMotionState(transform); const localInertia = new AmmoLib.btVector3(0, 0, 0); shape.calculateLocalInertia(mass, localInertia); const rbInfo = new AmmoLib.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia); const body = new AmmoLib.btRigidBody(rbInfo); world.addRigidBody(body); if (mass > 0) { meshes.push(mesh); meshMap.set(mesh, body); } } function handleInstancedMesh(mesh, mass, shape) { const array = mesh.instanceMatrix.array; const bodies = []; for (let i = 0; i < mesh.count; i++) { const index = i * 16; const transform = new AmmoLib.btTransform(); transform.setFromOpenGLMatrix(array.slice(index, index + 16)); const motionState = new AmmoLib.btDefaultMotionState(transform); const localInertia = new AmmoLib.btVector3(0, 0, 0); shape.calculateLocalInertia(mass, localInertia); const rbInfo = new AmmoLib.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia); const body = new AmmoLib.btRigidBody(rbInfo); world.addRigidBody(body); bodies.push(body); } if (mass > 0) { mesh.instanceMatrix.setUsage(35048); meshes.push(mesh); meshMap.set(mesh, bodies); } } function setMeshPosition(mesh, position, index = 0) { if (mesh.isInstancedMesh) { const body = meshMap.get(mesh)[index]; body.setAngularVelocity(new AmmoLib.btVector3(0, 0, 0)); body.setLinearVelocity(new AmmoLib.btVector3(0, 0, 0)); worldTransform.setIdentity(); worldTransform.setOrigin(new AmmoLib.btVector3(position.x, position.y, position.z)); body.setWorldTransform(worldTransform); } else if (mesh.isMesh) { const body = meshMap.get(mesh); body.setAngularVelocity(new AmmoLib.btVector3(0, 0, 0)); body.setLinearVelocity(new AmmoLib.btVector3(0, 0, 0)); worldTransform.setIdentity(); worldTransform.setOrigin(new AmmoLib.btVector3(position.x, position.y, position.z)); body.setWorldTransform(worldTransform); } } let lastTime = 0; function step() { const time = performance.now(); if (lastTime > 0) { const delta = (time - lastTime) / 1e3; world.stepSimulation(delta, 10); } lastTime = time; for (let i = 0, l = meshes.length; i < l; i++) { const mesh = meshes[i]; if (mesh.isInstancedMesh) { const array = mesh.instanceMatrix.array; const bodies = meshMap.get(mesh); for (let j = 0; j < bodies.length; j++) { bodies[j].getMotionState().getWorldTransform(worldTransform); compose(worldTransform.getOrigin(), worldTransform.getRotation(), array, j * 16); } mesh.instanceMatrix.needsUpdate = true; } else if (mesh.isMesh) { meshMap.get(mesh).getMotionState().getWorldTransform(worldTransform); const position = worldTransform.getOrigin(); const quaternion = worldTransform.getRotation(); mesh.position.set(position.x(), position.y(), position.z()); mesh.quaternion.set(quaternion.x(), quaternion.y(), quaternion.z(), quaternion.w()); } } } setInterval(step, 1e3 / frameRate); return { addMesh, setMeshPosition }; } function compose(position, quaternion, array, index) { const x = quaternion.x(), y = quaternion.y(), z = quaternion.z(), w = quaternion.w(); const x2 = x + x, y2 = y + y, z2 = z + z; const xx = x * x2, xy = x * y2, xz = x * z2; const yy = y * y2, yz = y * z2, zz = z * z2; const wx = w * x2, wy = w * y2, wz = w * z2; array[index + 0] = 1 - (yy + zz); array[index + 1] = xy + wz; array[index + 2] = xz - wy; array[index + 3] = 0; array[index + 4] = xy - wz; array[index + 5] = 1 - (xx + zz); array[index + 6] = yz + wx; array[index + 7] = 0; array[index + 8] = xz + wy; array[index + 9] = yz - wx; array[index + 10] = 1 - (xx + yy); array[index + 11] = 0; array[index + 12] = position.x(); array[index + 13] = position.y(); array[index + 14] = position.z(); array[index + 15] = 1; } //#endregion //#region node_modules/three-stdlib/effects/ParallaxBarrierEffect.js var ParallaxBarrierEffect = class { constructor(renderer) { const _camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1); const _scene = new Scene(); const _stereo = new StereoCamera(); const _params = { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }; const _renderTargetL = new WebGLRenderTarget(512, 512, _params); const _renderTargetR = new WebGLRenderTarget(512, 512, _params); const _material = new ShaderMaterial({ uniforms: { mapLeft: { value: _renderTargetL.texture }, mapRight: { value: _renderTargetR.texture } }, vertexShader: [ "varying vec2 vUv;", "void main() {", " vUv = vec2( uv.x, uv.y );", " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}" ].join("\n"), fragmentShader: [ "uniform sampler2D mapLeft;", "uniform sampler2D mapRight;", "varying vec2 vUv;", "void main() {", " vec2 uv = vUv;", " if ( ( mod( gl_FragCoord.y, 2.0 ) ) > 1.00 ) {", " gl_FragColor = texture2D( mapLeft, uv );", " } else {", " gl_FragColor = texture2D( mapRight, uv );", " }", " #include ", ` #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}>`, "}" ].join("\n") }); const mesh = new Mesh(new PlaneGeometry(2, 2), _material); _scene.add(mesh); this.setSize = function(width, height) { renderer.setSize(width, height); const pixelRatio = renderer.getPixelRatio(); _renderTargetL.setSize(width * pixelRatio, height * pixelRatio); _renderTargetR.setSize(width * pixelRatio, height * pixelRatio); }; this.render = function(scene, camera) { if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); _stereo.update(camera); renderer.setRenderTarget(_renderTargetL); renderer.clear(); renderer.render(scene, _stereo.cameraL); renderer.setRenderTarget(_renderTargetR); renderer.clear(); renderer.render(scene, _stereo.cameraR); renderer.setRenderTarget(null); renderer.render(_scene, _camera); }; } }; //#endregion //#region node_modules/three-stdlib/effects/PeppersGhostEffect.js var PeppersGhostEffect = class { constructor(renderer) { const scope = this; scope.cameraDistance = 15; scope.reflectFromAbove = false; let _halfWidth, _width, _height; const _cameraF = new PerspectiveCamera(); const _cameraB = new PerspectiveCamera(); const _cameraL = new PerspectiveCamera(); const _cameraR = new PerspectiveCamera(); const _position = new Vector3(); const _quaternion = new Quaternion(); const _scale = new Vector3(); renderer.autoClear = false; this.setSize = function(width, height) { _halfWidth = width / 2; if (width < height) { _width = width / 3; _height = width / 3; } else { _width = height / 3; _height = height / 3; } renderer.setSize(width, height); }; this.render = function(scene, camera) { if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); camera.matrixWorld.decompose(_position, _quaternion, _scale); _cameraF.position.copy(_position); _cameraF.quaternion.copy(_quaternion); _cameraF.translateZ(scope.cameraDistance); _cameraF.lookAt(scene.position); _cameraB.position.copy(_position); _cameraB.quaternion.copy(_quaternion); _cameraB.translateZ(-scope.cameraDistance); _cameraB.lookAt(scene.position); _cameraB.rotation.z += 180 * (Math.PI / 180); _cameraL.position.copy(_position); _cameraL.quaternion.copy(_quaternion); _cameraL.translateX(-scope.cameraDistance); _cameraL.lookAt(scene.position); _cameraL.rotation.x += 90 * (Math.PI / 180); _cameraR.position.copy(_position); _cameraR.quaternion.copy(_quaternion); _cameraR.translateX(scope.cameraDistance); _cameraR.lookAt(scene.position); _cameraR.rotation.x += 90 * (Math.PI / 180); renderer.clear(); renderer.setScissorTest(true); renderer.setScissor(_halfWidth - _width / 2, _height * 2, _width, _height); renderer.setViewport(_halfWidth - _width / 2, _height * 2, _width, _height); if (scope.reflectFromAbove) renderer.render(scene, _cameraB); else renderer.render(scene, _cameraF); renderer.setScissor(_halfWidth - _width / 2, 0, _width, _height); renderer.setViewport(_halfWidth - _width / 2, 0, _width, _height); if (scope.reflectFromAbove) renderer.render(scene, _cameraF); else renderer.render(scene, _cameraB); renderer.setScissor(_halfWidth - _width / 2 - _width, _height, _width, _height); renderer.setViewport(_halfWidth - _width / 2 - _width, _height, _width, _height); if (scope.reflectFromAbove) renderer.render(scene, _cameraR); else renderer.render(scene, _cameraL); renderer.setScissor(_halfWidth + _width / 2, _height, _width, _height); renderer.setViewport(_halfWidth + _width / 2, _height, _width, _height); if (scope.reflectFromAbove) renderer.render(scene, _cameraL); else renderer.render(scene, _cameraR); renderer.setScissorTest(false); }; } }; //#endregion //#region node_modules/three-stdlib/effects/OutlineEffect.js var OutlineEffect = class { constructor(renderer, parameters = {}) { this.enabled = true; const defaultThickness = parameters.defaultThickness !== void 0 ? parameters.defaultThickness : .003; const defaultColor = new Color().fromArray(parameters.defaultColor !== void 0 ? parameters.defaultColor : [ 0, 0, 0 ]); const defaultAlpha = parameters.defaultAlpha !== void 0 ? parameters.defaultAlpha : 1; const defaultKeepAlive = parameters.defaultKeepAlive !== void 0 ? parameters.defaultKeepAlive : false; const cache = {}; const removeThresholdCount = 60; const originalMaterials = {}; const originalOnBeforeRenders = {}; const uniformsOutline = { outlineThickness: { value: defaultThickness }, outlineColor: { value: defaultColor }, outlineAlpha: { value: defaultAlpha } }; const vertexShader = [ "#include ", "#include ", "#include ", "#include ", "#include ", "#include ", "#include ", "#include ", "uniform float outlineThickness;", "vec4 calculateOutline( vec4 pos, vec3 normal, vec4 skinned ) {", " float thickness = outlineThickness;", " const float ratio = 1.0;", " vec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );", " vec4 norm = normalize( pos - pos2 );", " return pos + norm * thickness * pos.w * ratio;", "}", "void main() {", " #include ", " #include ", " #include ", " #include ", " #include ", " #include ", " #include ", " #include ", " #include ", " #include ", " vec3 outlineNormal = - objectNormal;", " gl_Position = calculateOutline( gl_Position, outlineNormal, vec4( transformed, 1.0 ) );", " #include ", " #include ", " #include ", "}" ].join("\n"); const fragmentShader = [ "#include ", "#include ", "#include ", "#include ", "uniform vec3 outlineColor;", "uniform float outlineAlpha;", "void main() {", " #include ", " #include ", " gl_FragColor = vec4( outlineColor, outlineAlpha );", " #include ", ` #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}>`, " #include ", " #include ", "}" ].join("\n"); function createMaterial() { return new ShaderMaterial({ type: "OutlineEffect", uniforms: UniformsUtils.merge([ UniformsLib["fog"], UniformsLib["displacementmap"], uniformsOutline ]), vertexShader, fragmentShader, side: 1 }); } function getOutlineMaterialFromCache(originalMaterial) { let data = cache[originalMaterial.uuid]; if (data === void 0) { data = { material: createMaterial(), used: true, keepAlive: defaultKeepAlive, count: 0 }; cache[originalMaterial.uuid] = data; } data.used = true; return data.material; } function getOutlineMaterial(originalMaterial) { const outlineMaterial = getOutlineMaterialFromCache(originalMaterial); originalMaterials[outlineMaterial.uuid] = originalMaterial; updateOutlineMaterial(outlineMaterial, originalMaterial); return outlineMaterial; } function isCompatible(object) { const geometry = object.geometry; const hasNormals = geometry !== void 0 && geometry.attributes.normal !== void 0; return object.isMesh === true && object.material !== void 0 && hasNormals === true; } function setOutlineMaterial(object) { if (isCompatible(object) === false) return; if (Array.isArray(object.material)) for (let i = 0, il = object.material.length; i < il; i++) object.material[i] = getOutlineMaterial(object.material[i]); else object.material = getOutlineMaterial(object.material); originalOnBeforeRenders[object.uuid] = object.onBeforeRender; object.onBeforeRender = onBeforeRender; } function restoreOriginalMaterial(object) { if (isCompatible(object) === false) return; if (Array.isArray(object.material)) for (let i = 0, il = object.material.length; i < il; i++) object.material[i] = originalMaterials[object.material[i].uuid]; else object.material = originalMaterials[object.material.uuid]; object.onBeforeRender = originalOnBeforeRenders[object.uuid]; } function onBeforeRender(renderer2, scene, camera, geometry, material) { const originalMaterial = originalMaterials[material.uuid]; if (originalMaterial === void 0) return; updateUniforms(material, originalMaterial); } function updateUniforms(material, originalMaterial) { const outlineParameters = originalMaterial.userData.outlineParameters; material.uniforms.outlineAlpha.value = originalMaterial.opacity; if (outlineParameters !== void 0) { if (outlineParameters.thickness !== void 0) material.uniforms.outlineThickness.value = outlineParameters.thickness; if (outlineParameters.color !== void 0) material.uniforms.outlineColor.value.fromArray(outlineParameters.color); if (outlineParameters.alpha !== void 0) material.uniforms.outlineAlpha.value = outlineParameters.alpha; } if (originalMaterial.displacementMap) { material.uniforms.displacementMap.value = originalMaterial.displacementMap; material.uniforms.displacementScale.value = originalMaterial.displacementScale; material.uniforms.displacementBias.value = originalMaterial.displacementBias; } } function updateOutlineMaterial(material, originalMaterial) { if (material.name === "invisible") return; const outlineParameters = originalMaterial.userData.outlineParameters; material.fog = originalMaterial.fog; material.toneMapped = originalMaterial.toneMapped; material.premultipliedAlpha = originalMaterial.premultipliedAlpha; material.displacementMap = originalMaterial.displacementMap; if (outlineParameters !== void 0) { if (originalMaterial.visible === false) material.visible = false; else material.visible = outlineParameters.visible !== void 0 ? outlineParameters.visible : true; material.transparent = outlineParameters.alpha !== void 0 && outlineParameters.alpha < 1 ? true : originalMaterial.transparent; if (outlineParameters.keepAlive !== void 0) cache[originalMaterial.uuid].keepAlive = outlineParameters.keepAlive; } else { material.transparent = originalMaterial.transparent; material.visible = originalMaterial.visible; } if (originalMaterial.wireframe === true || originalMaterial.depthTest === false) material.visible = false; if (originalMaterial.clippingPlanes) { material.clipping = true; material.clippingPlanes = originalMaterial.clippingPlanes; material.clipIntersection = originalMaterial.clipIntersection; material.clipShadows = originalMaterial.clipShadows; } material.version = originalMaterial.version; } function cleanupCache() { let keys; keys = Object.keys(originalMaterials); for (let i = 0, il = keys.length; i < il; i++) originalMaterials[keys[i]] = void 0; keys = Object.keys(originalOnBeforeRenders); for (let i = 0, il = keys.length; i < il; i++) originalOnBeforeRenders[keys[i]] = void 0; keys = Object.keys(cache); for (let i = 0, il = keys.length; i < il; i++) { const key = keys[i]; if (cache[key].used === false) { cache[key].count++; if (cache[key].keepAlive === false && cache[key].count > removeThresholdCount) delete cache[key]; } else { cache[key].used = false; cache[key].count = 0; } } } this.render = function(scene, camera) { if (this.enabled === false) { renderer.render(scene, camera); return; } const currentAutoClear = renderer.autoClear; renderer.autoClear = this.autoClear; renderer.render(scene, camera); renderer.autoClear = currentAutoClear; this.renderOutline(scene, camera); }; this.renderOutline = function(scene, camera) { const currentAutoClear = renderer.autoClear; const currentSceneAutoUpdate = scene.matrixWorldAutoUpdate; const currentSceneBackground = scene.background; const currentShadowMapEnabled = renderer.shadowMap.enabled; scene.matrixWorldAutoUpdate = false; scene.background = null; renderer.autoClear = false; renderer.shadowMap.enabled = false; scene.traverse(setOutlineMaterial); renderer.render(scene, camera); scene.traverse(restoreOriginalMaterial); cleanupCache(); scene.matrixWorldAutoUpdate = currentSceneAutoUpdate; scene.background = currentSceneBackground; renderer.autoClear = currentAutoClear; renderer.shadowMap.enabled = currentShadowMapEnabled; }; this.autoClear = renderer.autoClear; this.domElement = renderer.domElement; this.shadowMap = renderer.shadowMap; this.clear = function(color, depth, stencil) { renderer.clear(color, depth, stencil); }; this.getPixelRatio = function() { return renderer.getPixelRatio(); }; this.setPixelRatio = function(value) { renderer.setPixelRatio(value); }; this.getSize = function(target) { return renderer.getSize(target); }; this.setSize = function(width, height, updateStyle) { renderer.setSize(width, height, updateStyle); }; this.setViewport = function(x, y, width, height) { renderer.setViewport(x, y, width, height); }; this.setScissor = function(x, y, width, height) { renderer.setScissor(x, y, width, height); }; this.setScissorTest = function(boolean) { renderer.setScissorTest(boolean); }; this.setRenderTarget = function(renderTarget) { renderer.setRenderTarget(renderTarget); }; } }; //#endregion //#region node_modules/three-stdlib/effects/AnaglyphEffect.js var AnaglyphEffect = class { constructor(renderer, width = 512, height = 512) { this.colorMatrixLeft = new Matrix3().fromArray([ .4561, -.0400822, -.0152161, .500484, -.0378246, -.0205971, .176381, -.0157589, -.00546856 ]); this.colorMatrixRight = new Matrix3().fromArray([ -.0434706, .378476, -.0721527, -.0879388, .73364, -.112961, -.00155529, -.0184503, 1.2264 ]); const _camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1); const _scene = new Scene(); const _stereo = new StereoCamera(); const _params = { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat }; const _renderTargetL = new WebGLRenderTarget(width, height, _params); const _renderTargetR = new WebGLRenderTarget(width, height, _params); const _material = new ShaderMaterial({ uniforms: { mapLeft: { value: _renderTargetL.texture }, mapRight: { value: _renderTargetR.texture }, colorMatrixLeft: { value: this.colorMatrixLeft }, colorMatrixRight: { value: this.colorMatrixRight } }, vertexShader: [ "varying vec2 vUv;", "void main() {", " vUv = vec2( uv.x, uv.y );", " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}" ].join("\n"), fragmentShader: [ "uniform sampler2D mapLeft;", "uniform sampler2D mapRight;", "varying vec2 vUv;", "uniform mat3 colorMatrixLeft;", "uniform mat3 colorMatrixRight;", "void main() {", " vec2 uv = vUv;", " vec4 colorL = texture2D( mapLeft, uv );", " vec4 colorR = texture2D( mapRight, uv );", " vec3 color = clamp(", " colorMatrixLeft * colorL.rgb +", " colorMatrixRight * colorR.rgb, 0., 1. );", " gl_FragColor = vec4(", " color.r, color.g, color.b,", " max( colorL.a, colorR.a ) );", " #include ", ` #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}>`, "}" ].join("\n") }); const _mesh = new Mesh(new PlaneGeometry(2, 2), _material); _scene.add(_mesh); this.setSize = function(width2, height2) { renderer.setSize(width2, height2); const pixelRatio = renderer.getPixelRatio(); _renderTargetL.setSize(width2 * pixelRatio, height2 * pixelRatio); _renderTargetR.setSize(width2 * pixelRatio, height2 * pixelRatio); }; this.render = function(scene, camera) { const currentRenderTarget = renderer.getRenderTarget(); if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); _stereo.update(camera); renderer.setRenderTarget(_renderTargetL); renderer.clear(); renderer.render(scene, _stereo.cameraL); renderer.setRenderTarget(_renderTargetR); renderer.clear(); renderer.render(scene, _stereo.cameraR); renderer.setRenderTarget(null); renderer.render(_scene, _camera); renderer.setRenderTarget(currentRenderTarget); }; this.dispose = function() { _renderTargetL.dispose(); _renderTargetR.dispose(); _mesh.geometry.dispose(); _mesh.material.dispose(); }; } }; //#endregion //#region node_modules/three-stdlib/effects/AsciiEffect.js var AsciiEffect = class { constructor(renderer, charSet = " .:-=+*#%@", options = {}) { const fResolution = options["resolution"] || .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 = (.3 * iRed + .59 * iGreen + .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}`; } } }; //#endregion //#region node_modules/three-stdlib/effects/StereoEffect.js var StereoEffect = class { constructor(renderer) { const _stereo = new StereoCamera(); _stereo.aspect = .5; const size = new Vector2(); this.setEyeSeparation = function(eyeSep) { _stereo.eyeSep = eyeSep; }; this.setSize = function(width, height) { renderer.setSize(width, height); }; this.render = function(scene, camera) { if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); _stereo.update(camera); renderer.getSize(size); if (renderer.autoClear) renderer.clear(); renderer.setScissorTest(true); renderer.setScissor(0, 0, size.width / 2, size.height); renderer.setViewport(0, 0, size.width / 2, size.height); renderer.render(scene, _stereo.cameraL); renderer.setScissor(size.width / 2, 0, size.width / 2, size.height); renderer.setViewport(size.width / 2, 0, size.width / 2, size.height); renderer.render(scene, _stereo.cameraR); renderer.setScissorTest(false); }; } }; //#endregion //#region node_modules/three-stdlib/curves/NURBSUtils.js function findSpan(p, u, U) { const n = U.length - p - 1; if (u >= U[n]) return n - 1; if (u <= U[p]) return p; let low = p; let high = n; 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, p, U) { const N = []; const left = []; const right = []; N[0] = 1; for (let j = 1; j <= p; ++j) { left[j] = u - U[span + 1 - j]; right[j] = U[span + j] - u; let saved = 0; for (let r = 0; r < j; ++r) { const rv = right[r + 1]; const lv = left[j - r]; const temp = N[r] / (rv + lv); N[r] = saved + rv * temp; saved = lv * temp; } N[j] = saved; } return N; } function calcBSplinePoint(p, U, P, u) { const span = findSpan(p, u, U); const N = calcBasisFunctions(span, u, p, U); const C = new Vector4(0, 0, 0, 0); for (let j = 0; j <= p; ++j) { const point = P[span - p + 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, p, n, U) { const zeroArr = []; for (let i = 0; i <= p; ++i) zeroArr[i] = 0; const ders = []; for (let i = 0; i <= n; ++i) ders[i] = zeroArr.slice(0); const ndu = []; for (let i = 0; i <= p; ++i) ndu[i] = zeroArr.slice(0); ndu[0][0] = 1; const left = zeroArr.slice(0); const right = zeroArr.slice(0); for (let j = 1; j <= p; ++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]; ndu[j][r2] = rv + lv; const temp = ndu[r2][j - 1] / ndu[j][r2]; ndu[r2][j] = saved + rv * temp; saved = lv * temp; } ndu[j][j] = saved; } for (let j = 0; j <= p; ++j) ders[0][j] = ndu[j][p]; for (let r2 = 0; r2 <= p; ++r2) { let s1 = 0; let s2 = 1; const a = []; for (let i = 0; i <= p; ++i) a[i] = zeroArr.slice(0); a[0][0] = 1; for (let k = 1; k <= n; ++k) { let d = 0; const rk = r2 - k; const pk = p - k; if (r2 >= k) { a[s2][0] = a[s1][0] / ndu[pk + 1][rk]; d = a[s2][0] * ndu[rk][pk]; } const j1 = rk >= -1 ? 1 : -rk; const j2 = r2 - 1 <= pk ? k - 1 : p - r2; for (let j3 = j1; j3 <= j2; ++j3) { a[s2][j3] = (a[s1][j3] - a[s1][j3 - 1]) / ndu[pk + 1][rk + j3]; d += a[s2][j3] * ndu[rk + j3][pk]; } if (r2 <= pk) { a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r2]; d += a[s2][k] * ndu[r2][pk]; } ders[k][r2] = d; const j = s1; s1 = s2; s2 = j; } } let r = p; for (let k = 1; k <= n; ++k) { for (let j = 0; j <= p; ++j) ders[k][j] *= r; r *= p - k; } return ders; } function calcBSplineDerivatives(p, U, P, u, nd) { const du = nd < p ? nd : p; const CK = []; const span = findSpan(p, u, U); const nders = calcBasisFunctionDerivatives(span, u, p, du, U); const Pw = []; for (let i = 0; i < P.length; ++i) { const point = P[i].clone(); const w = point.w; point.x *= w; point.y *= w; point.z *= w; Pw[i] = point; } for (let k = 0; k <= du; ++k) { const point = Pw[span - p].clone().multiplyScalar(nders[k][0]); for (let j = 1; j <= p; ++j) point.add(Pw[span - p + 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, i) { let nom = 1; for (let j = 2; j <= k; ++j) nom *= j; let denom = 1; for (let j = 2; j <= i; ++j) denom *= j; for (let j = 2; j <= k - i; ++j) denom *= j; return nom / denom; } function calcRationalCurveDerivatives(Pders) { const nd = Pders.length; const Aders = []; const wders = []; for (let i = 0; i < nd; ++i) { const point = Pders[i]; Aders[i] = new Vector3(point.x, point.y, point.z); wders[i] = point.w; } const CK = []; for (let k = 0; k < nd; ++k) { const v = Aders[k].clone(); for (let i = 1; i <= k; ++i) v.sub(CK[k - i].clone().multiplyScalar(calcKoverI(k, i) * wders[i])); CK[k] = v.divideScalar(wders[0]); } return CK; } function calcNURBSDerivatives(p, U, P, u, nd) { return calcRationalCurveDerivatives(calcBSplineDerivatives(p, U, P, u, nd)); } function calcSurfacePoint(p, q, U, V, P, u, v, target) { const uspan = findSpan(p, u, U); const vspan = findSpan(q, v, V); const Nu = calcBasisFunctions(uspan, u, p, U); const Nv = calcBasisFunctions(vspan, v, q, V); const temp = []; for (let l = 0; l <= q; ++l) { temp[l] = new Vector4(0, 0, 0, 0); for (let k = 0; k <= p; ++k) { const point = P[uspan - p + k][vspan - q + l].clone(); const w = point.w; point.x *= w; point.y *= w; point.z *= w; temp[l].add(point.multiplyScalar(Nu[k])); } } const Sw = new Vector4(0, 0, 0, 0); for (let l = 0; l <= q; ++l) Sw.add(temp[l].multiplyScalar(Nv[l])); Sw.divideScalar(Sw.w); target.set(Sw.x, Sw.y, Sw.z); } //#endregion //#region 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 i = 0; i < controlPoints.length; ++i) { const point = controlPoints[i]; this.controlPoints[i] = new Vector4(point.x, point.y, point.z, point.w); } } getPoint(t, optionalTarget) { const point = optionalTarget || new Vector3(); const u = this.knots[this.startKnot] + t * (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(t, optionalTarget) { const tangent = optionalTarget || new Vector3(); const u = this.knots[0] + t * (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; } }; //#endregion //#region 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 loader = new FileLoader(this.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(buffer) { try { onLoad(scope.parse(buffer, path)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } 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); } return new FBXTreeParser(new TextureLoader(this.manager).setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin), 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$1().parse(deformers); this.parseScene(deformers, geometryMap, materials); return sceneGraph; } parseConnections() { const connectionMap = /* @__PURE__ */ new Map(); if ("Connections" in fbxTree) fbxTree.Connections.connections.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; } 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; } 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 })); } } 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; } 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; } 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 loader = this.manager.getHandler(".tga"); if (loader === null) { console.warn("FBXLoader: TGA loader not found, creating placeholder texture for", textureNode.RelativeFilename); texture = new Texture(); } else { loader.setPath(this.textureLoader.path); texture = loader.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; } 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; } 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; } 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 = 303; 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; default: console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.", type); break; } }); return parameters; } 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); } 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 }; } 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) }; if ("Indexes" in boneNode) { rawBone.indices = boneNode.Indexes.a; rawBone.weights = boneNode.Weights.a; } rawBones.push(rawBone); }); return { rawBones, bones: [] }; } parseMorphTargets(relationships, deformerNodes) { const rawMorphTargets = []; for (let i = 0; i < relationships.children.length; i++) { const child = relationships.children[i]; const morphTargetNode = deformerNodes[child.ID]; const rawMorphTarget = { name: morphTargetNode.attrName, initialWeight: morphTargetNode.DeformPercent, id: morphTargetNode.id, fullWeights: morphTargetNode.FullWeights.a }; if (morphTargetNode.attrType !== "BlendShapeChannel") return; rawMorphTarget.geoID = connections.get(parseInt(child.ID)).children.filter(function(child2) { return child2.relationship === void 0; })[0].ID; rawMorphTargets.push(rawMorphTarget); } return rawMorphTargets; } 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); connections.get(model.ID).parents.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; } 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; 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, i) { 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[i] = bone; if (subBone !== null) bone.add(subBone); } }); } }); return bone; } 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; } 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 distance = 0; if (lightAttribute.FarAttenuationEnd !== void 0) if (lightAttribute.EnableFarAttenuation !== void 0 && lightAttribute.EnableFarAttenuation.value === 0) distance = 0; else distance = lightAttribute.FarAttenuationEnd.value; const decay = 1; switch (type) { case 0: model = new PointLight(color, intensity, distance, decay); break; case 1: model = new DirectionalLight(color, intensity); break; case 2: let angle = Math.PI / 3; if (lightAttribute.InnerAngle !== void 0) angle = MathUtils.degToRad(lightAttribute.InnerAngle.value); let penumbra = 0; if (lightAttribute.OuterAngle !== void 0) { penumbra = MathUtils.degToRad(lightAttribute.OuterAngle.value); penumbra = Math.max(penumbra, 1); } model = new SpotLight(color, intensity, distance, angle, penumbra, decay); break; default: console.warn("THREE.FBXLoader: Unknown light type " + lightAttribute.LightType.value + ", defaulting to a PointLight."); model = new PointLight(color, intensity); break; } if (lightAttribute.CastShadows !== void 0 && lightAttribute.CastShadows.value === 1) model.castShadow = true; } return model; } createMesh(relationships, geometryMap, materialMap) { let model; let geometry = null; let material = null; const materials = []; relationships.children.forEach(function(child) { if (geometryMap.has(child.ID)) geometry = geometryMap.get(child.ID); if (materialMap.has(child.ID)) materials.push(materialMap.get(child.ID)); }); if (materials.length > 1) material = materials; else if (materials.length > 0) material = materials[0]; else { material = new MeshPhongMaterial({ color: 13421772 }); materials.push(material); } if ("color" in geometry.attributes) materials.forEach(function(material2) { material2.vertexColors = true; }); if (geometry.FBX_Deformer) { model = new SkinnedMesh(geometry, material); model.normalizeSkinWeights(); } else model = new Mesh(geometry, material); return model; } createCurve(relationships, geometryMap) { return new Line(relationships.children.reduce(function(geo, child) { if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID); return geo; }, null), new LineBasicMaterial({ color: 3342591, linewidth: 1 })); } 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) connections.get(model.ID).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]; connections.get(parseInt(skeleton.ID)).parents.forEach(function(parent) { if (geometryMap.has(parent.ID)) { const geoID = parent.ID; connections.get(geoID).parents.forEach(function(geoConnParent) { if (modelMap.has(geoConnParent.ID)) modelMap.get(geoConnParent.ID).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; } createAmbientLight() { if ("GlobalSettings" in fbxTree && "AmbientColor" in fbxTree.GlobalSettings) { const ambientColor = fbxTree.GlobalSettings.AmbientColor.value; const r = ambientColor[0]; const g = ambientColor[1]; const b = ambientColor[2]; if (r !== 0 || g !== 0 || b !== 0) { const color = new Color(r, g, b); sceneGraph.add(new AmbientLight(color, 1)); } } } }; var GeometryParser$1 = class { 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; } parseGeometry(relationships, geoNode, deformers) { switch (geoNode.attrType) { case "Mesh": return this.parseMeshGeometry(relationships, geoNode, deformers); case "NurbsCurve": return this.parseNurbsGeometry(geoNode); } } 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); } genGeometry(geoNode, skeleton, morphTargets, preTransform) { const geo = new BufferGeometry(); if (geoNode.attrName) geo.name = geoNode.attrName; const geoInfo = this.parseGeoNode(geoNode, skeleton); const buffers = this.genBuffers(geoInfo); const positionAttribute = new Float32BufferAttribute(buffers.vertex, 3); positionAttribute.applyMatrix4(preTransform); geo.setAttribute("position", positionAttribute); if (buffers.colors.length > 0) geo.setAttribute("color", new Float32BufferAttribute(buffers.colors, 3)); if (skeleton) { geo.setAttribute("skinIndex", new Uint16BufferAttribute(buffers.weightsIndices, 4)); geo.setAttribute("skinWeight", new Float32BufferAttribute(buffers.vertexWeights, 4)); geo.FBX_Deformer = skeleton; } if (buffers.normal.length > 0) { const normalMatrix = new Matrix3().getNormalMatrix(preTransform); const normalAttribute = new Float32BufferAttribute(buffers.normal, 3); normalAttribute.applyNormalMatrix(normalMatrix); geo.setAttribute("normal", normalAttribute); } buffers.uvs.forEach(function(uvBuffer, i) { if (UV1 === "uv2") i++; const name = i === 0 ? "uv" : `uv${i}`; geo.setAttribute(name, new Float32BufferAttribute(buffers.uvs[i], 2)); }); if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") { let prevMaterialIndex = buffers.materialIndex[0]; let startIndex = 0; buffers.materialIndex.forEach(function(currentIndex, i) { if (currentIndex !== prevMaterialIndex) { geo.addGroup(startIndex, i - startIndex, prevMaterialIndex); prevMaterialIndex = currentIndex; startIndex = i; } }); if (geo.groups.length > 0) { const lastGroup = geo.groups[geo.groups.length - 1]; const lastIndex = lastGroup.start + lastGroup.count; if (lastIndex !== buffers.materialIndex.length) geo.addGroup(lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex); } if (geo.groups.length === 0) geo.addGroup(0, buffers.materialIndex.length, buffers.materialIndex[0]); } this.addMorphTargets(geo, geoNode, morphTargets, preTransform); return geo; } parseGeoNode(geoNode, skeleton) { const geoInfo = {}; geoInfo.vertexPositions = geoNode.Vertices !== void 0 ? geoNode.Vertices.a : []; geoInfo.vertexIndices = geoNode.PolygonVertexIndex !== void 0 ? geoNode.PolygonVertexIndex.a : []; if (geoNode.LayerElementColor) geoInfo.color = this.parseVertexColors(geoNode.LayerElementColor[0]); if (geoNode.LayerElementMaterial) geoInfo.material = this.parseMaterialIndices(geoNode.LayerElementMaterial[0]); if (geoNode.LayerElementNormal) geoInfo.normal = this.parseNormals(geoNode.LayerElementNormal[0]); if (geoNode.LayerElementUV) { geoInfo.uv = []; let i = 0; while (geoNode.LayerElementUV[i]) { if (geoNode.LayerElementUV[i].UV) geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i])); i++; } } geoInfo.weightTable = {}; if (skeleton !== null) { geoInfo.skeleton = skeleton; skeleton.rawBones.forEach(function(rawBone, i) { rawBone.indices.forEach(function(index, j) { if (geoInfo.weightTable[index] === void 0) geoInfo.weightTable[index] = []; geoInfo.weightTable[index].push({ id: i, 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 i = 0; i < 4; ++i) { faceWeights.push(weights[i]); faceWeightIndices.push(weightIndices[i]); } } 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, i) { const data = getData(polygonVertexIndex, polygonIndex, vertexIndex, uv); if (faceUVs[i] === void 0) faceUVs[i] = []; faceUVs[i].push(data[0]); faceUVs[i].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; } genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength) { for (let i = 2; i < faceLength; i++) { 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[(i - 1) * 3]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 1]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 2]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 1]]); buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 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[(i - 1) * 4]); buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 1]); buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 2]); buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 3]); buffers.vertexWeights.push(faceWeights[i * 4]); buffers.vertexWeights.push(faceWeights[i * 4 + 1]); buffers.vertexWeights.push(faceWeights[i * 4 + 2]); buffers.vertexWeights.push(faceWeights[i * 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[(i - 1) * 4]); buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 1]); buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 2]); buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 3]); buffers.weightsIndices.push(faceWeightIndices[i * 4]); buffers.weightsIndices.push(faceWeightIndices[i * 4 + 1]); buffers.weightsIndices.push(faceWeightIndices[i * 4 + 2]); buffers.weightsIndices.push(faceWeightIndices[i * 4 + 3]); } if (geoInfo.color) { buffers.colors.push(faceColors[0]); buffers.colors.push(faceColors[1]); buffers.colors.push(faceColors[2]); buffers.colors.push(faceColors[(i - 1) * 3]); buffers.colors.push(faceColors[(i - 1) * 3 + 1]); buffers.colors.push(faceColors[(i - 1) * 3 + 2]); buffers.colors.push(faceColors[i * 3]); buffers.colors.push(faceColors[i * 3 + 1]); buffers.colors.push(faceColors[i * 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[(i - 1) * 3]); buffers.normal.push(faceNormals[(i - 1) * 3 + 1]); buffers.normal.push(faceNormals[(i - 1) * 3 + 2]); buffers.normal.push(faceNormals[i * 3]); buffers.normal.push(faceNormals[i * 3 + 1]); buffers.normal.push(faceNormals[i * 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][(i - 1) * 2]); buffers.uvs[j].push(faceUVs[j][(i - 1) * 2 + 1]); buffers.uvs[j].push(faceUVs[j][i * 2]); buffers.uvs[j].push(faceUVs[j][i * 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); }); }); } 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 length = parentGeo.attributes.position.count * 3; const morphPositions = new Float32Array(length); for (let i = 0; i < indices.length; i++) { const morphIndex = indices[i] * 3; morphPositions[morphIndex] = morphPositionsSparse[i * 3]; morphPositions[morphIndex + 1] = morphPositionsSparse[i * 3 + 1]; morphPositions[morphIndex + 2] = morphPositionsSparse[i * 3 + 2]; } const morphGeoInfo = { vertexIndices, vertexPositions: morphPositions }; const positionAttribute = new Float32BufferAttribute(this.genBuffers(morphGeoInfo).vertex, 3); positionAttribute.name = name || morphGeoNode.attrName; positionAttribute.applyMatrix4(preTransform); parentGeo.morphAttributes.position.push(positionAttribute); } parseNormals(NormalNode) { const mappingType = NormalNode.MappingInformationType; const referenceType = NormalNode.ReferenceInformationType; const buffer = NormalNode.Normals.a; let indexBuffer = []; if (referenceType === "IndexToDirect") { if ("NormalIndex" in NormalNode) indexBuffer = NormalNode.NormalIndex.a; else if ("NormalsIndex" in NormalNode) indexBuffer = NormalNode.NormalsIndex.a; } return { dataSize: 3, buffer, indices: indexBuffer, mappingType, referenceType }; } parseUVs(UVNode) { const mappingType = UVNode.MappingInformationType; const referenceType = UVNode.ReferenceInformationType; const buffer = UVNode.UV.a; let indexBuffer = []; if (referenceType === "IndexToDirect") indexBuffer = UVNode.UVIndex.a; return { dataSize: 2, buffer, indices: indexBuffer, mappingType, referenceType }; } parseVertexColors(ColorNode) { const mappingType = ColorNode.MappingInformationType; const referenceType = ColorNode.ReferenceInformationType; const buffer = ColorNode.Colors.a; let indexBuffer = []; if (referenceType === "IndexToDirect") indexBuffer = ColorNode.ColorIndex.a; return { dataSize: 4, buffer, indices: indexBuffer, mappingType, referenceType }; } parseMaterialIndices(MaterialNode) { const mappingType = MaterialNode.MappingInformationType; const referenceType = MaterialNode.ReferenceInformationType; if (mappingType === "NoMappingInformation") return { dataSize: 1, buffer: [0], indices: [0], mappingType: "AllSame", referenceType }; const materialIndexBuffer = MaterialNode.Materials.a; const materialIndices = []; for (let i = 0; i < materialIndexBuffer.length; ++i) materialIndices.push(i); return { dataSize: 1, buffer: materialIndexBuffer, indices: materialIndices, mappingType, referenceType }; } 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 i = 0, l = pointsValues.length; i < l; i += 4) controlPoints.push(new Vector4().fromArray(pointsValues, i)); let startKnot, endKnot; if (geoNode.Form === "Closed") controlPoints.push(controlPoints[0]); else if (geoNode.Form === "Periodic") { startKnot = degree; endKnot = knots.length - 1 - startKnot; for (let i = 0; i < degree; ++i) controlPoints.push(controlPoints[i]); } const points = new NURBSCurve(degree, knots, controlPoints, startKnot, endKnot).getPoints(controlPoints.length * 12); return new BufferGeometry().setFromPoints(points); } }; var AnimationParser = class { 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); return this.parseAnimStacks(layersMap); } 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; } 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; } } } 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) { connection.children.forEach(function(child, i) { if (curveNodesMap.has(child.ID)) { const curveNode = curveNodesMap.get(child.ID); if (curveNode.curves.x !== void 0 || curveNode.curves.y !== void 0 || curveNode.curves.z !== void 0) { if (layerCurveNodes[i] === void 0) { const modelID = connections.get(child.ID).parents.filter(function(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[i] = node; } } if (layerCurveNodes[i]) layerCurveNodes[i][curveNode.attr] = curveNode; } else if (curveNode.curves.morph !== void 0) { if (layerCurveNodes[i] === void 0) { const deformerID = connections.get(child.ID).parents.filter(function(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]; layerCurveNodes[i] = { modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName(rawModel.attrName) : "", morphName: fbxTree.Objects.Deformer[deformerID].attrName }; } layerCurveNodes[i][curveNode.attr] = curveNode; } } }); layersMap.set(parseInt(nodeID), layerCurveNodes); } } return layersMap; } 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 i = 0; i < values.length; i += 3) { euler.set(values[i], values[i + 1], values[i + 2], eulerOrder); quaternion.setFromEuler(euler); if (preRotation !== void 0) quaternion.premultiply(preRotation); if (postRotation !== void 0) quaternion.multiply(postRotation); quaternion.toArray(quaternionValues, i / 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); } 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(a, b) { return a - b; }); if (times.length > 1) { let targetIndex = 1; let lastValue = times[0]; for (let i = 1; i < times.length; i++) { const currentValue = times[i]; if (currentValue !== lastValue) { times[targetIndex] = currentValue; lastValue = currentValue; targetIndex++; } } times = times.slice(0, targetIndex); } return times; } getKeyframeTrackValues(times, curves, initialValue) { const prevValue = initialValue; const 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; } interpolateRotations(curve) { for (let i = 1; i < curve.values.length; i++) { const initialValue = curve.values[i - 1]; const valuesSpan = curve.values[i] - 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[i - 1]; const interval = (curve.times[i] - initialTime) / numSubIntervals; let nextTime = initialTime + interval; const interpolatedTimes = []; const interpolatedValues = []; while (nextTime < curve.times[i]) { interpolatedTimes.push(nextTime); nextTime += interval; interpolatedValues.push(nextValue); nextValue += step; } curve.times = inject(curve.times, i, interpolatedTimes); curve.values = inject(curve.values, i, 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, i) { 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[++i]); 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(); if (currentNode.name === "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); } 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(buffer) { const reader = new BinaryReader(buffer); reader.skip(23); const version = reader.getUint32(); if (version < 6400) throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: " + version); const allNodes = new FBXTree(); while (!this.endOfContent(reader)) { const node = this.parseNode(reader, version); if (node !== null) allNodes.add(node.name, node); } return allNodes; } endOfContent(reader) { if (reader.size() % 16 === 0) return (reader.getOffset() + 160 + 16 & -16) >= reader.size(); else return reader.getOffset() + 160 + 16 >= reader.size(); } parseNode(reader, version) { const node = {}; const endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32(); const numProperties = version >= 7500 ? reader.getUint64() : reader.getUint32(); version >= 7500 ? reader.getUint64() : reader.getUint32(); const nameLen = reader.getUint8(); const name = reader.getString(nameLen); if (endOffset === 0) return null; const propertyList = []; for (let i = 0; i < numProperties; i++) propertyList.push(this.parseProperty(reader)); const id = propertyList.length > 0 ? propertyList[0] : ""; const attrName = propertyList.length > 1 ? propertyList[1] : ""; const attrType = propertyList.length > 2 ? propertyList[2] : ""; node.singleProperty = numProperties === 1 && reader.getOffset() === endOffset ? true : false; while (endOffset > reader.getOffset()) { const subNode = this.parseNode(reader, version); if (subNode !== null) this.parseSubNode(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, i) { if (i !== 0) array.push(property); }); if (node.connections === void 0) node.connections = []; node.connections.push(array); } else if (subNode.name === "Properties70") Object.keys(subNode).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 length; 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": length = reader.getUint32(); return reader.getArrayBuffer(length); case "S": length = reader.getUint32(); return reader.getString(length); 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 reader2 = new BinaryReader(unzlibSync(new Uint8Array(reader.getArrayBuffer(compressedLength))).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(buffer, littleEndian) { this.dv = new DataView(buffer); this.offset = 0; this.littleEndian = littleEndian !== void 0 ? littleEndian : true; } getOffset() { return this.offset; } size() { return this.dv.buffer.byteLength; } skip(length) { this.offset += length; } getBoolean() { return (this.getUint8() & 1) === 1; } getBooleanArray(size) { const a = []; for (let i = 0; i < size; i++) a.push(this.getBoolean()); return a; } 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(size) { const a = []; for (let i = 0; i < size; i++) a.push(this.getInt32()); return a; } getUint32() { const value = this.dv.getUint32(this.offset, this.littleEndian); this.offset += 4; return value; } 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(size) { const a = []; for (let i = 0; i < size; i++) a.push(this.getInt64()); return a; } 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(size) { const a = []; for (let i = 0; i < size; i++) a.push(this.getFloat32()); return a; } getFloat64() { const value = this.dv.getFloat64(this.offset, this.littleEndian); this.offset += 8; return value; } getFloat64Array(size) { const a = []; for (let i = 0; i < size; i++) a.push(this.getFloat64()); return a; } getArrayBuffer(size) { const value = this.dv.buffer.slice(this.offset, this.offset + size); this.offset += size; return value; } getString(size) { let a = []; for (let i = 0; i < size; i++) a[i] = this.getUint8(); const nullByte = a.indexOf(0); if (nullByte >= 0) a = a.slice(0, nullByte); return decodeText$1(new Uint8Array(a)); } }; var FBXTree = class { add(key, val) { this[key] = val; } }; function isFbxFormatBinary(buffer) { return buffer.byteLength >= 21 && "Kaydara FBX Binary \0" === convertArrayBufferToString(buffer, 0, 21); } 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 read(offset) { const result = text[offset - 1]; text = text.slice(cursor + offset); cursor++; return result; } for (let i = 0; i < CORRECT.length; ++i) if (read(1) === CORRECT[i]) return false; return true; } function getFbxVersion(text) { const match = text.match(/FBXVersion: (\d+)/); if (match) return parseInt(match[1]); 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 index; switch (infoObject.mappingType) { case "ByPolygonVertex": index = polygonVertexIndex; break; case "ByPolygon": index = polygonIndex; break; case "ByVertice": index = vertexIndex; break; case "AllSame": index = infoObject.indices[0]; break; default: console.warn("THREE.FBXLoader: unknown attribute mapping type " + infoObject.mappingType); } if (infoObject.referenceType === "IndexToDirect") index = infoObject.indices[index]; const from = index * infoObject.dataSize; const to = from + infoObject.dataSize; return slice(dataArray, infoObject.buffer, from, to); } var tempEuler = /* @__PURE__ */ new Euler(); var tempVec = /* @__PURE__ */ 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_inv = new Matrix4().scale(new Vector3().setFromMatrixScale(lParentLX)).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", "YZX", "XZY", "ZXY", "YXZ", "XYZ" ]; 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) { return value.split(",").map(function(val) { return parseFloat(val); }); } function convertArrayBufferToString(buffer, from, to) { if (from === void 0) from = 0; if (to === void 0) to = buffer.byteLength; return decodeText$1(new Uint8Array(buffer, from, to)); } function append(a, b) { for (let i = 0, j = a.length, l = b.length; i < l; i++, j++) a[j] = b[i]; } function slice(a, b, from, to) { for (let i = from, j = 0; i < to; i++, j++) a[j] = b[i]; return a; } function inject(a1, index, a2) { return a1.slice(0, index).concat(a2).concat(a1.slice(index)); } //#endregion //#region node_modules/three-stdlib/loaders/FontLoader.js var __defProp$3 = Object.defineProperty; var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$3 = (obj, key, value) => { __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var FontLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.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) { __publicField$3(this, "data"); __publicField$3(this, "isFont", true); __publicField$3(this, "type", "Font"); this.data = data; } generateShapes(text, size = 100, _options) { const shapes = []; const options = { letterSpacing: 0, lineHeight: 1, ..._options }; const paths = createPaths(text, size, this.data, options); for (let p = 0, pl = paths.length; p < pl; p++) Array.prototype.push.apply(shapes, paths[p].toShapes(false)); return shapes; } }; function createPaths(text, size, data, options) { const chars = Array.from(text); const scale = size / data.resolution; const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale; const paths = []; let offsetX = 0, offsetY = 0; for (let i = 0; i < chars.length; i++) { const char = chars[i]; if (char === "\n") { offsetX = 0; offsetY -= line_height * options.lineHeight; } else { const ret = createPath(char, scale, offsetX, offsetY, data); if (ret) { offsetX += ret.offsetX + options.letterSpacing; paths.push(ret.path); } } } return paths; } function createPath(char, scale, 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 i = 0, l = outline.length; i < l;) switch (outline[i++]) { case "m": x = parseInt(outline[i++]) * scale + offsetX; y = parseInt(outline[i++]) * scale + offsetY; path.moveTo(x, y); break; case "l": x = parseInt(outline[i++]) * scale + offsetX; y = parseInt(outline[i++]) * scale + offsetY; path.lineTo(x, y); break; case "q": cpx = parseInt(outline[i++]) * scale + offsetX; cpy = parseInt(outline[i++]) * scale + offsetY; cpx1 = parseInt(outline[i++]) * scale + offsetX; cpy1 = parseInt(outline[i++]) * scale + offsetY; path.quadraticCurveTo(cpx1, cpy1, cpx, cpy); break; case "b": cpx = parseInt(outline[i++]) * scale + offsetX; cpy = parseInt(outline[i++]) * scale + offsetY; cpx1 = parseInt(outline[i++]) * scale + offsetX; cpy1 = parseInt(outline[i++]) * scale + offsetY; cpx2 = parseInt(outline[i++]) * scale + offsetX; cpy2 = parseInt(outline[i++]) * scale + offsetY; path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy); break; } } return { offsetX: glyph.ha * scale, path }; } //#endregion //#region node_modules/three-stdlib/loaders/TGALoader.js var TGALoader = class extends DataTextureLoader { constructor(manager) { super(manager); } parse(buffer) { function tgaCheckHeader(header2) { switch (header2.image_type) { case TGA_TYPE_INDEXED: case TGA_TYPE_RLE_INDEXED: if (header2.colormap_length > 256 || header2.colormap_size !== 24 || header2.colormap_type !== 1) console.error("THREE.TGALoader: Invalid type colormap data for indexed type."); break; case TGA_TYPE_RGB: case TGA_TYPE_GREY: case TGA_TYPE_RLE_RGB: case TGA_TYPE_RLE_GREY: if (header2.colormap_type) console.error("THREE.TGALoader: Invalid type colormap data for colormap type."); break; case TGA_TYPE_NO_DATA: console.error("THREE.TGALoader: No data."); default: console.error("THREE.TGALoader: Invalid type \"%s\".", header2.image_type); } if (header2.width <= 0 || header2.height <= 0) console.error("THREE.TGALoader: Invalid image size."); if (header2.pixel_size !== 8 && header2.pixel_size !== 16 && header2.pixel_size !== 24 && header2.pixel_size !== 32) console.error("THREE.TGALoader: Invalid pixel size \"%s\".", header2.pixel_size); } function tgaParse(use_rle2, use_pal2, header2, offset2, data) { let pixel_data, palettes; const pixel_size = header2.pixel_size >> 3; const pixel_total = header2.width * header2.height * pixel_size; if (use_pal2) palettes = data.subarray(offset2, offset2 += header2.colormap_length * (header2.colormap_size >> 3)); if (use_rle2) { pixel_data = new Uint8Array(pixel_total); let c, count, i; let shift = 0; const pixels = new Uint8Array(pixel_size); while (shift < pixel_total) { c = data[offset2++]; count = (c & 127) + 1; if (c & 128) { for (i = 0; i < pixel_size; ++i) pixels[i] = data[offset2++]; for (i = 0; i < count; ++i) pixel_data.set(pixels, shift + i * pixel_size); shift += pixel_size * count; } else { count *= pixel_size; for (i = 0; i < count; ++i) pixel_data[shift + i] = data[offset2++]; shift += count; } } } else pixel_data = data.subarray(offset2, offset2 += use_pal2 ? header2.width * header2.height : pixel_total); return { pixel_data, palettes }; } function tgaGetImageData8bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image, palettes) { const colormap = palettes; let color, i = 0, x, y; const width = header.width; for (y = y_start; y !== y_end; y += y_step) for (x = x_start; x !== x_end; x += x_step, i++) { color = image[i]; imageData2[(x + width * y) * 4 + 3] = 255; imageData2[(x + width * y) * 4 + 2] = colormap[color * 3 + 0]; imageData2[(x + width * y) * 4 + 1] = colormap[color * 3 + 1]; imageData2[(x + width * y) * 4 + 0] = colormap[color * 3 + 2]; } return imageData2; } function tgaGetImageData16bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) { let color, i = 0, x, y; const width = header.width; for (y = y_start; y !== y_end; y += y_step) for (x = x_start; x !== x_end; x += x_step, i += 2) { color = image[i + 0] + (image[i + 1] << 8); imageData2[(x + width * y) * 4 + 0] = (color & 31744) >> 7; imageData2[(x + width * y) * 4 + 1] = (color & 992) >> 2; imageData2[(x + width * y) * 4 + 2] = (color & 31) >> 3; imageData2[(x + width * y) * 4 + 3] = color & 32768 ? 0 : 255; } return imageData2; } function tgaGetImageData24bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) { let i = 0, x, y; const width = header.width; for (y = y_start; y !== y_end; y += y_step) for (x = x_start; x !== x_end; x += x_step, i += 3) { imageData2[(x + width * y) * 4 + 3] = 255; imageData2[(x + width * y) * 4 + 2] = image[i + 0]; imageData2[(x + width * y) * 4 + 1] = image[i + 1]; imageData2[(x + width * y) * 4 + 0] = image[i + 2]; } return imageData2; } function tgaGetImageData32bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) { let i = 0, x, y; const width = header.width; for (y = y_start; y !== y_end; y += y_step) for (x = x_start; x !== x_end; x += x_step, i += 4) { imageData2[(x + width * y) * 4 + 2] = image[i + 0]; imageData2[(x + width * y) * 4 + 1] = image[i + 1]; imageData2[(x + width * y) * 4 + 0] = image[i + 2]; imageData2[(x + width * y) * 4 + 3] = image[i + 3]; } return imageData2; } function tgaGetImageDataGrey8bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) { let color, i = 0, x, y; const width = header.width; for (y = y_start; y !== y_end; y += y_step) for (x = x_start; x !== x_end; x += x_step, i++) { color = image[i]; imageData2[(x + width * y) * 4 + 0] = color; imageData2[(x + width * y) * 4 + 1] = color; imageData2[(x + width * y) * 4 + 2] = color; imageData2[(x + width * y) * 4 + 3] = 255; } return imageData2; } function tgaGetImageDataGrey16bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) { let i = 0, x, y; const width = header.width; for (y = y_start; y !== y_end; y += y_step) for (x = x_start; x !== x_end; x += x_step, i += 2) { imageData2[(x + width * y) * 4 + 0] = image[i + 0]; imageData2[(x + width * y) * 4 + 1] = image[i + 0]; imageData2[(x + width * y) * 4 + 2] = image[i + 0]; imageData2[(x + width * y) * 4 + 3] = image[i + 1]; } return imageData2; } function getTgaRGBA(data, width, height, image, palette) { let x_start, y_start, x_step, y_step, x_end, y_end; switch ((header.flags & TGA_ORIGIN_MASK) >> TGA_ORIGIN_SHIFT) { default: case TGA_ORIGIN_UL: x_start = 0; x_step = 1; x_end = width; y_start = 0; y_step = 1; y_end = height; break; case TGA_ORIGIN_BL: x_start = 0; x_step = 1; x_end = width; y_start = height - 1; y_step = -1; y_end = -1; break; case TGA_ORIGIN_UR: x_start = width - 1; x_step = -1; x_end = -1; y_start = 0; y_step = 1; y_end = height; break; case TGA_ORIGIN_BR: x_start = width - 1; x_step = -1; x_end = -1; y_start = height - 1; y_step = -1; y_end = -1; break; } if (use_grey) switch (header.pixel_size) { case 8: tgaGetImageDataGrey8bits(data, y_start, y_step, y_end, x_start, x_step, x_end, image); break; case 16: tgaGetImageDataGrey16bits(data, y_start, y_step, y_end, x_start, x_step, x_end, image); break; default: console.error("THREE.TGALoader: Format not supported."); break; } else switch (header.pixel_size) { case 8: tgaGetImageData8bits(data, y_start, y_step, y_end, x_start, x_step, x_end, image, palette); break; case 16: tgaGetImageData16bits(data, y_start, y_step, y_end, x_start, x_step, x_end, image); break; case 24: tgaGetImageData24bits(data, y_start, y_step, y_end, x_start, x_step, x_end, image); break; case 32: tgaGetImageData32bits(data, y_start, y_step, y_end, x_start, x_step, x_end, image); break; default: console.error("THREE.TGALoader: Format not supported."); break; } return data; } const TGA_TYPE_NO_DATA = 0, TGA_TYPE_INDEXED = 1, TGA_TYPE_RGB = 2, TGA_TYPE_GREY = 3, TGA_TYPE_RLE_INDEXED = 9, TGA_TYPE_RLE_RGB = 10, TGA_TYPE_RLE_GREY = 11, TGA_ORIGIN_MASK = 48, TGA_ORIGIN_SHIFT = 4, TGA_ORIGIN_BL = 0, TGA_ORIGIN_BR = 1, TGA_ORIGIN_UL = 2, TGA_ORIGIN_UR = 3; if (buffer.length < 19) console.error("THREE.TGALoader: Not enough data to contain header."); let offset = 0; const content = new Uint8Array(buffer), header = { id_length: content[offset++], colormap_type: content[offset++], image_type: content[offset++], colormap_index: content[offset++] | content[offset++] << 8, colormap_length: content[offset++] | content[offset++] << 8, colormap_size: content[offset++], origin: [content[offset++] | content[offset++] << 8, content[offset++] | content[offset++] << 8], width: content[offset++] | content[offset++] << 8, height: content[offset++] | content[offset++] << 8, pixel_size: content[offset++], flags: content[offset++] }; tgaCheckHeader(header); if (header.id_length + offset > buffer.length) console.error("THREE.TGALoader: No data."); offset += header.id_length; let use_rle = false, use_pal = false, use_grey = false; switch (header.image_type) { case TGA_TYPE_RLE_INDEXED: use_rle = true; use_pal = true; break; case TGA_TYPE_INDEXED: use_pal = true; break; case TGA_TYPE_RLE_RGB: use_rle = true; break; case TGA_TYPE_RGB: break; case TGA_TYPE_RLE_GREY: use_rle = true; use_grey = true; break; case TGA_TYPE_GREY: use_grey = true; break; } const imageData = new Uint8Array(header.width * header.height * 4); const result = tgaParse(use_rle, use_pal, header, offset, content); getTgaRGBA(imageData, header.width, header.height, result.pixel_data, result.palettes); return { data: imageData, width: header.width, height: header.height, flipY: true, generateMipmaps: true, minFilter: LinearMipmapLinearFilter }; } }; //#endregion //#region 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; } }; //#endregion //#region node_modules/three-stdlib/loaders/LUTCubeLoader.js var LUTCubeLoader = class extends Loader { load(url, onLoad, onProgress, onError) { const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("text"); loader.load(url, (text) => { try { onLoad(this.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); this.manager.itemError(url); } }, onProgress, onError); } parse(str) { str = str.replace(/^#.*?(\n|\r)/gm, "").replace(/^\s*?(\n|\r)/gm, "").trim(); let title = null; let size = null; const domainMin = new Vector3(0, 0, 0); const domainMax = new Vector3(1, 1, 1); const lines = str.split(/[\n\r]+/g); let data = null; let currIndex = 0; for (let i = 0, l = lines.length; i < l; i++) { const line = lines[i].trim(); const split = line.split(/\s/g); switch (split[0]) { case "TITLE": title = line.substring(7, line.length - 1); break; case "LUT_3D_SIZE": const sizeToken = split[1]; size = parseFloat(sizeToken); data = new Uint8Array(size * size * size * 4); break; case "DOMAIN_MIN": domainMin.x = parseFloat(split[1]); domainMin.y = parseFloat(split[2]); domainMin.z = parseFloat(split[3]); break; case "DOMAIN_MAX": domainMax.x = parseFloat(split[1]); domainMax.y = parseFloat(split[2]); domainMax.z = parseFloat(split[3]); break; default: const r = parseFloat(split[0]); const g = parseFloat(split[1]); const b = parseFloat(split[2]); if (r > 1 || r < 0 || g > 1 || g < 0 || b > 1 || b < 0) throw new Error("LUTCubeLoader : Non normalized values not supported."); data[currIndex + 0] = r * 255; data[currIndex + 1] = g * 255; data[currIndex + 2] = b * 255; data[currIndex + 3] = 255; currIndex += 4; } } const texture = new DataTexture(); texture.image.data = data; texture.image.width = size; texture.image.height = size * size; texture.type = UnsignedByteType; texture.magFilter = LinearFilter; texture.minFilter = LinearFilter; texture.wrapS = ClampToEdgeWrapping; texture.wrapT = ClampToEdgeWrapping; texture.generateMipmaps = false; texture.needsUpdate = true; const texture3D = new Data3DTexture(); texture3D.image.data = data; texture3D.image.width = size; texture3D.image.height = size; texture3D.image.depth = size; texture3D.type = UnsignedByteType; texture3D.magFilter = LinearFilter; texture3D.minFilter = LinearFilter; texture3D.wrapS = ClampToEdgeWrapping; texture3D.wrapT = ClampToEdgeWrapping; texture3D.wrapR = ClampToEdgeWrapping; texture3D.generateMipmaps = false; texture3D.needsUpdate = true; return { title, size, domainMin, domainMax, texture, texture3D }; } }; //#endregion //#region node_modules/three-stdlib/loaders/NRRDLoader.js var NRRDLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(data) { try { onLoad(scope.parse(data)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(data) { let _data = data; let _dataPointer = 0; const _nativeLittleEndian = new Int8Array(new Int16Array([1]).buffer)[0] > 0; const _littleEndian = true; const headerObject = {}; function scan(type, chunks) { if (chunks === void 0 || chunks === null) chunks = 1; let _chunkSize = 1; let _array_type = Uint8Array; switch (type) { case "uchar": break; case "schar": _array_type = Int8Array; break; case "ushort": _array_type = Uint16Array; _chunkSize = 2; break; case "sshort": _array_type = Int16Array; _chunkSize = 2; break; case "uint": _array_type = Uint32Array; _chunkSize = 4; break; case "sint": _array_type = Int32Array; _chunkSize = 4; break; case "float": _array_type = Float32Array; _chunkSize = 4; break; case "complex": _array_type = Float64Array; _chunkSize = 8; break; case "double": _array_type = Float64Array; _chunkSize = 8; break; } let _bytes2 = new _array_type(_data.slice(_dataPointer, _dataPointer += chunks * _chunkSize)); if (_nativeLittleEndian != _littleEndian) _bytes2 = flipEndianness(_bytes2, _chunkSize); if (chunks == 1) return _bytes2[0]; return _bytes2; } function flipEndianness(array, chunkSize) { const u8 = new Uint8Array(array.buffer, array.byteOffset, array.byteLength); for (let i2 = 0; i2 < array.byteLength; i2 += chunkSize) for (let j = i2 + chunkSize - 1, k = i2; j > k; j--, k++) { const tmp = u8[k]; u8[k] = u8[j]; u8[j] = tmp; } return array; } function parseHeader(header) { let data2, field, fn, i2, l, m, _i, _len; const lines = header.split(/\r?\n/); for (_i = 0, _len = lines.length; _i < _len; _i++) { l = lines[_i]; if (l.match(/NRRD\d+/)) headerObject.isNrrd = true; else if (l.match(/^#/)); else if (m = l.match(/(.*):(.*)/)) { field = m[1].trim(); data2 = m[2].trim(); fn = _fieldFunctions[field]; if (fn) fn.call(headerObject, data2); else headerObject[field] = data2; } } if (!headerObject.isNrrd) throw new Error("Not an NRRD file"); if (headerObject.encoding === "bz2" || headerObject.encoding === "bzip2") throw new Error("Bzip is not supported"); if (!headerObject.vectors) { headerObject.vectors = [ new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1) ]; if (headerObject.spacings) { for (i2 = 0; i2 <= 2; i2++) if (!isNaN(headerObject.spacings[i2])) headerObject.vectors[i2].multiplyScalar(headerObject.spacings[i2]); } } } function parseDataAsText(data2, start, end) { let number = ""; start = start || 0; end = end || data2.length; let value; const lengthOfTheResult = headerObject.sizes.reduce(function(previous, current) { return previous * current; }, 1); let base = 10; if (headerObject.encoding === "hex") base = 16; const result = new headerObject.__array(lengthOfTheResult); let resultIndex = 0; let parsingFunction = parseInt; if (headerObject.__array === Float32Array || headerObject.__array === Float64Array) parsingFunction = parseFloat; for (let i2 = start; i2 < end; i2++) { value = data2[i2]; if ((value < 9 || value > 13) && value !== 32) number += String.fromCharCode(value); else { if (number !== "") { result[resultIndex] = parsingFunction(number, base); resultIndex++; } number = ""; } } if (number !== "") { result[resultIndex] = parsingFunction(number, base); resultIndex++; } return result; } const _bytes = scan("uchar", data.byteLength); const _length = _bytes.length; let _header = null; let _data_start = 0; let i; for (i = 1; i < _length; i++) if (_bytes[i - 1] == 10 && _bytes[i] == 10) { _header = this.parseChars(_bytes, 0, i - 2); _data_start = i + 1; break; } parseHeader(_header); _data = _bytes.subarray(_data_start); if (headerObject.encoding.substring(0, 2) === "gz") _data = gunzipSync(new Uint8Array(_data)); else if (headerObject.encoding === "ascii" || headerObject.encoding === "text" || headerObject.encoding === "txt" || headerObject.encoding === "hex") _data = parseDataAsText(_data); else if (headerObject.encoding === "raw") { const _copy = new Uint8Array(_data.length); for (let i2 = 0; i2 < _data.length; i2++) _copy[i2] = _data[i2]; _data = _copy; } _data = _data.buffer; const volume = new Volume(); volume.header = headerObject; volume.data = new headerObject.__array(_data); const min_max = volume.computeMinMax(); const min = min_max[0]; const max = min_max[1]; volume.windowLow = min; volume.windowHigh = max; volume.dimensions = [ headerObject.sizes[0], headerObject.sizes[1], headerObject.sizes[2] ]; volume.xLength = volume.dimensions[0]; volume.yLength = volume.dimensions[1]; volume.zLength = volume.dimensions[2]; volume.spacing = [ new Vector3(headerObject.vectors[0][0], headerObject.vectors[0][1], headerObject.vectors[0][2]).length(), new Vector3(headerObject.vectors[1][0], headerObject.vectors[1][1], headerObject.vectors[1][2]).length(), new Vector3(headerObject.vectors[2][0], headerObject.vectors[2][1], headerObject.vectors[2][2]).length() ]; volume.matrix = new Matrix4(); let _spaceX = 1; let _spaceY = 1; const _spaceZ = 1; if (headerObject.space == "left-posterior-superior") { _spaceX = -1; _spaceY = -1; } else if (headerObject.space === "left-anterior-superior") _spaceX = -1; if (!headerObject.vectors) volume.matrix.set(_spaceX, 0, 0, 0, 0, _spaceY, 0, 0, 0, 0, _spaceZ, 0, 0, 0, 0, 1); else { const v = headerObject.vectors; volume.matrix.set(_spaceX * v[0][0], _spaceX * v[1][0], _spaceX * v[2][0], 0, _spaceY * v[0][1], _spaceY * v[1][1], _spaceY * v[2][1], 0, _spaceZ * v[0][2], _spaceZ * v[1][2], _spaceZ * v[2][2], 0, 0, 0, 0, 1); } volume.inverseMatrix = new Matrix4(); volume.inverseMatrix.copy(volume.matrix).invert(); volume.RASDimensions = new Vector3(volume.xLength, volume.yLength, volume.zLength).applyMatrix4(volume.matrix).round().toArray().map(Math.abs); if (volume.lowerThreshold === -Infinity) volume.lowerThreshold = min; if (volume.upperThreshold === Infinity) volume.upperThreshold = max; return volume; } parseChars(array, start, end) { if (start === void 0) start = 0; if (end === void 0) end = array.length; let output = ""; let i = 0; for (i = start; i < end; ++i) output += String.fromCharCode(array[i]); return output; } }; var _fieldFunctions = { type: function(data) { switch (data) { case "uchar": case "unsigned char": case "uint8": case "uint8_t": this.__array = Uint8Array; break; case "signed char": case "int8": case "int8_t": this.__array = Int8Array; break; case "short": case "short int": case "signed short": case "signed short int": case "int16": case "int16_t": this.__array = Int16Array; break; case "ushort": case "unsigned short": case "unsigned short int": case "uint16": case "uint16_t": this.__array = Uint16Array; break; case "int": case "signed int": case "int32": case "int32_t": this.__array = Int32Array; break; case "uint": case "unsigned int": case "uint32": case "uint32_t": this.__array = Uint32Array; break; case "float": this.__array = Float32Array; break; case "double": this.__array = Float64Array; break; default: throw new Error("Unsupported NRRD data type: " + data); } return this.type = data; }, endian: function(data) { return this.endian = data; }, encoding: function(data) { return this.encoding = data; }, dimension: function(data) { return this.dim = parseInt(data, 10); }, sizes: function(data) { let i; return this.sizes = function() { const _ref = data.split(/\s+/); const _results = []; for (let _i = 0, _len = _ref.length; _i < _len; _i++) { i = _ref[_i]; _results.push(parseInt(i, 10)); } return _results; }(); }, space: function(data) { return this.space = data; }, "space origin": function(data) { return this.space_origin = data.split("(")[1].split(")")[0].split(","); }, "space directions": function(data) { let f, v; const parts = data.match(/\(.*?\)/g); return this.vectors = function() { const _results = []; for (let _i = 0, _len = parts.length; _i < _len; _i++) { v = parts[_i]; _results.push(function() { const _ref = v.slice(1, -1).split(/,/); const _results2 = []; for (let _j = 0, _len2 = _ref.length; _j < _len2; _j++) { f = _ref[_j]; _results2.push(parseFloat(f)); } return _results2; }()); } return _results; }(); }, spacings: function(data) { let f; const parts = data.split(/\s+/); return this.spacings = function() { const _results = []; for (let _i = 0, _len = parts.length; _i < _len; _i++) { f = parts[_i]; _results.push(parseFloat(f)); } return _results; }(); } }; //#endregion //#region node_modules/three-stdlib/loaders/STLLoader.js var STLLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(data) { function isBinary(data2) { const reader = new DataView(data2); if (84 + reader.getUint32(80, true) * 50 === reader.byteLength) return true; const solid = [ 115, 111, 108, 105, 100 ]; for (let off = 0; off < 5; off++) if (matchDataViewAt(solid, reader, off)) return false; return true; } function matchDataViewAt(query, reader, offset) { for (let i = 0, il = query.length; i < il; i++) if (query[i] !== reader.getUint8(offset + i, false)) return false; return true; } function parseBinary(data2) { const reader = new DataView(data2); const faces = reader.getUint32(80, true); let r, g, b, hasColors = false, colors; let defaultR, defaultG, defaultB, alpha; for (let index = 0; index < 70; index++) if (reader.getUint32(index, false) == 1129270351 && reader.getUint8(index + 4) == 82 && reader.getUint8(index + 5) == 61) { hasColors = true; colors = new Float32Array(faces * 3 * 3); defaultR = reader.getUint8(index + 6) / 255; defaultG = reader.getUint8(index + 7) / 255; defaultB = reader.getUint8(index + 8) / 255; alpha = reader.getUint8(index + 9) / 255; } const dataOffset = 84; const faceLength = 50; const geometry = new BufferGeometry(); const vertices = new Float32Array(faces * 3 * 3); const normals = new Float32Array(faces * 3 * 3); for (let face = 0; face < faces; face++) { const start = dataOffset + face * faceLength; const normalX = reader.getFloat32(start, true); const normalY = reader.getFloat32(start + 4, true); const normalZ = reader.getFloat32(start + 8, true); if (hasColors) { const packedColor = reader.getUint16(start + 48, true); if ((packedColor & 32768) === 0) { r = (packedColor & 31) / 31; g = (packedColor >> 5 & 31) / 31; b = (packedColor >> 10 & 31) / 31; } else { r = defaultR; g = defaultG; b = defaultB; } } for (let i = 1; i <= 3; i++) { const vertexstart = start + i * 12; const componentIdx = face * 3 * 3 + (i - 1) * 3; vertices[componentIdx] = reader.getFloat32(vertexstart, true); vertices[componentIdx + 1] = reader.getFloat32(vertexstart + 4, true); vertices[componentIdx + 2] = reader.getFloat32(vertexstart + 8, true); normals[componentIdx] = normalX; normals[componentIdx + 1] = normalY; normals[componentIdx + 2] = normalZ; if (hasColors) { colors[componentIdx] = r; colors[componentIdx + 1] = g; colors[componentIdx + 2] = b; } } } geometry.setAttribute("position", new BufferAttribute(vertices, 3)); geometry.setAttribute("normal", new BufferAttribute(normals, 3)); if (hasColors) { geometry.setAttribute("color", new BufferAttribute(colors, 3)); geometry.hasColors = true; geometry.alpha = alpha; } return geometry; } function parseASCII(data2) { const geometry = new BufferGeometry(); const patternSolid = /solid([\s\S]*?)endsolid/g; const patternFace = /facet([\s\S]*?)endfacet/g; let faceCounter = 0; const patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source; const patternVertex = new RegExp("vertex" + patternFloat + patternFloat + patternFloat, "g"); const patternNormal = new RegExp("normal" + patternFloat + patternFloat + patternFloat, "g"); const vertices = []; const normals = []; const normal = new Vector3(); let result; let groupCount = 0; let startVertex = 0; let endVertex = 0; while ((result = patternSolid.exec(data2)) !== null) { startVertex = endVertex; const solid = result[0]; while ((result = patternFace.exec(solid)) !== null) { let vertexCountPerFace = 0; let normalCountPerFace = 0; const text = result[0]; while ((result = patternNormal.exec(text)) !== null) { normal.x = parseFloat(result[1]); normal.y = parseFloat(result[2]); normal.z = parseFloat(result[3]); normalCountPerFace++; } while ((result = patternVertex.exec(text)) !== null) { vertices.push(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])); normals.push(normal.x, normal.y, normal.z); vertexCountPerFace++; endVertex++; } if (normalCountPerFace !== 1) console.error("THREE.STLLoader: Something isn't right with the normal of face number " + faceCounter); if (vertexCountPerFace !== 3) console.error("THREE.STLLoader: Something isn't right with the vertices of face number " + faceCounter); faceCounter++; } const start = startVertex; const count = endVertex - startVertex; geometry.addGroup(start, count, groupCount); groupCount++; } geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); return geometry; } function ensureString(buffer) { if (typeof buffer !== "string") return decodeText$1(new Uint8Array(buffer)); return buffer; } function ensureBinary(buffer) { if (typeof buffer === "string") { const array_buffer = new Uint8Array(buffer.length); for (let i = 0; i < buffer.length; i++) array_buffer[i] = buffer.charCodeAt(i) & 255; return array_buffer.buffer || array_buffer; } else return buffer; } const binData = ensureBinary(data); return isBinary(binData) ? parseBinary(binData) : parseASCII(ensureString(data)); } }; //#endregion //#region node_modules/three-stdlib/loaders/MTLLoader.js var MTLLoader = class extends Loader { constructor(manager) { super(manager); } /** * Loads and parses a MTL asset from a URL. * * @param {String} url - URL to the MTL file. * @param {Function} [onLoad] - Callback invoked with the loaded object. * @param {Function} [onProgress] - Callback for download progress. * @param {Function} [onError] - Callback for download errors. * * @see setPath setResourcePath * * @note In order for relative texture references to resolve correctly * you must call setResourcePath() explicitly prior to load. */ load(url, onLoad, onProgress, onError) { const scope = this; const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text, path)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } setMaterialOptions(value) { this.materialOptions = value; return this; } /** * Parses a MTL file. * * @param {String} text - Content of MTL file * @return {MaterialCreator} * * @see setPath setResourcePath * * @note In order for relative texture references to resolve correctly * you must call setResourcePath() explicitly prior to parse. */ parse(text, path) { const lines = text.split("\n"); let info = {}; const delimiter_pattern = /\s+/; const materialsInfo = {}; for (let i = 0; i < lines.length; i++) { let line = lines[i]; line = line.trim(); if (line.length === 0 || line.charAt(0) === "#") continue; const pos = line.indexOf(" "); let key = pos >= 0 ? line.substring(0, pos) : line; key = key.toLowerCase(); let value = pos >= 0 ? line.substring(pos + 1) : ""; value = value.trim(); if (key === "newmtl") { info = { name: value }; materialsInfo[value] = info; } else if (key === "ka" || key === "kd" || key === "ks" || key === "ke") { const ss = value.split(delimiter_pattern, 3); info[key] = [ parseFloat(ss[0]), parseFloat(ss[1]), parseFloat(ss[2]) ]; } else info[key] = value; } const materialCreator = new MaterialCreator(this.resourcePath || path, this.materialOptions); materialCreator.setCrossOrigin(this.crossOrigin); materialCreator.setManager(this.manager); materialCreator.setMaterials(materialsInfo); return materialCreator; } }; var MaterialCreator = class { constructor(baseUrl = "", options = {}) { this.baseUrl = baseUrl; this.options = options; this.materialsInfo = {}; this.materials = {}; this.materialsArray = []; this.nameLookup = {}; this.crossOrigin = "anonymous"; this.side = this.options.side !== void 0 ? this.options.side : 0; this.wrap = this.options.wrap !== void 0 ? this.options.wrap : RepeatWrapping; } setCrossOrigin(value) { this.crossOrigin = value; return this; } setManager(value) { this.manager = value; } setMaterials(materialsInfo) { this.materialsInfo = this.convert(materialsInfo); this.materials = {}; this.materialsArray = []; this.nameLookup = {}; } convert(materialsInfo) { if (!this.options) return materialsInfo; const converted = {}; for (const mn in materialsInfo) { const mat = materialsInfo[mn]; const covmat = {}; converted[mn] = covmat; for (const prop in mat) { let save = true; let value = mat[prop]; const lprop = prop.toLowerCase(); switch (lprop) { case "kd": case "ka": case "ks": if (this.options && this.options.normalizeRGB) value = [ value[0] / 255, value[1] / 255, value[2] / 255 ]; if (this.options && this.options.ignoreZeroRGBs) { if (value[0] === 0 && value[1] === 0 && value[2] === 0) save = false; } break; } if (save) covmat[lprop] = value; } } return converted; } preload() { for (const mn in this.materialsInfo) this.create(mn); } getIndex(materialName) { return this.nameLookup[materialName]; } getAsArray() { let index = 0; for (const mn in this.materialsInfo) { this.materialsArray[index] = this.create(mn); this.nameLookup[mn] = index; index++; } return this.materialsArray; } create(materialName) { if (this.materials[materialName] === void 0) this.createMaterial_(materialName); return this.materials[materialName]; } createMaterial_(materialName) { const scope = this; const mat = this.materialsInfo[materialName]; const params = { name: materialName, side: this.side }; function resolveURL(baseUrl, url) { if (typeof url !== "string" || url === "") return ""; if (/^https?:\/\//i.test(url)) return url; return baseUrl + url; } function setMapForType(mapType, value) { if (params[mapType]) return; const texParams = scope.getTextureParams(value, params); const map = scope.loadTexture(resolveURL(scope.baseUrl, texParams.url)); map.repeat.copy(texParams.scale); map.offset.copy(texParams.offset); map.wrapS = scope.wrap; map.wrapT = scope.wrap; params[mapType] = map; } for (const prop in mat) { const value = mat[prop]; let n; if (value === "") continue; switch (prop.toLowerCase()) { case "kd": params.color = new Color().fromArray(value); break; case "ks": params.specular = new Color().fromArray(value); break; case "ke": params.emissive = new Color().fromArray(value); break; case "map_kd": setMapForType("map", value); break; case "map_ks": setMapForType("specularMap", value); break; case "map_ke": setMapForType("emissiveMap", value); break; case "norm": setMapForType("normalMap", value); break; case "map_bump": case "bump": setMapForType("bumpMap", value); break; case "map_d": setMapForType("alphaMap", value); params.transparent = true; break; case "ns": params.shininess = parseFloat(value); break; case "d": n = parseFloat(value); if (n < 1) { params.opacity = n; params.transparent = true; } break; case "tr": n = parseFloat(value); if (this.options && this.options.invertTrProperty) n = 1 - n; if (n > 0) { params.opacity = 1 - n; params.transparent = true; } break; } } this.materials[materialName] = new MeshPhongMaterial(params); return this.materials[materialName]; } getTextureParams(value, matParams) { const texParams = { scale: new Vector2(1, 1), offset: new Vector2(0, 0) }; const items = value.split(/\s+/); let pos; pos = items.indexOf("-bm"); if (pos >= 0) { matParams.bumpScale = parseFloat(items[pos + 1]); items.splice(pos, 2); } pos = items.indexOf("-s"); if (pos >= 0) { texParams.scale.set(parseFloat(items[pos + 1]), parseFloat(items[pos + 2])); items.splice(pos, 4); } pos = items.indexOf("-o"); if (pos >= 0) { texParams.offset.set(parseFloat(items[pos + 1]), parseFloat(items[pos + 2])); items.splice(pos, 4); } texParams.url = items.join(" ").trim(); return texParams; } loadTexture(url, mapping, onLoad, onProgress, onError) { const manager = this.manager !== void 0 ? this.manager : DefaultLoadingManager; let loader = manager.getHandler(url); if (loader === null) loader = new TextureLoader(manager); if (loader.setCrossOrigin) loader.setCrossOrigin(this.crossOrigin); const texture = loader.load(url, onLoad, onProgress, onError); if (mapping !== void 0) texture.mapping = mapping; return texture; } }; //#endregion //#region node_modules/three-stdlib/loaders/XLoader.js var XLoader = /* @__PURE__ */ function() { var classCallCheck = function(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); }; var createClass = function() { function defineProperties(target, props) { for (let i2 = 0; i2 < props.length; i2++) { var descriptor = props[i2]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, 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 i2 = 0; i2 < XAnimationInfoArray.length; i2++) this.hierarchy.push(this.makeBonekeys(XAnimationInfoArray[i2])); this.length = this.hierarchy[0].keys[this.hierarchy[0].keys.length - 1].time; } }, { key: "clone", value: function clone() { 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 i2 = 0; i2 < XAnimationInfo2.keyFrames.length; i2++) { var keyframe = {}; keyframe.time = XAnimationInfo2.keyFrames[i2].time * this.fps; if (XAnimationInfo2.keyFrames[i2].pos && this.putFlags.putPos) keyframe.pos = XAnimationInfo2.keyFrames[i2].pos; if (XAnimationInfo2.keyFrames[i2].rot && this.putFlags.putRot) keyframe.rot = XAnimationInfo2.keyFrames[i2].rot; if (XAnimationInfo2.keyFrames[i2].scl && this.putFlags.putScl) keyframe.scl = XAnimationInfo2.keyFrames[i2].scl; if (XAnimationInfo2.keyFrames[i2].matrix) { keyframe.matrix = XAnimationInfo2.keyFrames[i2].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; }; return 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 _start = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; if (!_arg) return; for (let i2 = _start; i2 < _arg.length; i2++) switch (i2) { case 0: this.url = _arg[i2]; break; case 1: this.options = _arg[i2]; break; } if (this.options === void 0) this.options = {}; } }, { key: "load", value: function load(_arg, onLoad, onProgress, onError) { var _this = this; this._setArgOption(_arg); var loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(this.url, function(response) { try { _this.parse(response, onLoad); } catch (e) { if (onError) onError(e); else console.error(e); _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); if (84 + reader.getUint32(80, true) * 50 === reader.byteLength) return true; var fileLength = reader.byteLength; for (let index = 0; index < fileLength; index++) if (reader.getUint8(index, 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 i2 = 0; i2 < buf.length; i2++) array_buffer[i2] = buf.charCodeAt(i2) & 255; return array_buffer.buffer || array_buffer; } else return buf; } }, { key: "_ensureString", value: function _ensureString(buf) { if (typeof buf !== "string") return decodeText$1(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$1(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, _end) { var endRead = _end; 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; } } } }, { 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(_obj) { if (_obj.parent) if (_obj.parent.name) return _obj.parent.name; else return this._getParentName(_obj.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 b = new Bone(); b.name = this._currentFrame.name; b.applyMatrix4(this._currentFrame.FrameTransformMatrix); b.matrixWorld = b.matrix; b.FrameTransformMatrix = this._currentFrame.FrameTransformMatrix; this._currentFrame.putBone = b; 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) { endRead = this._readInt1(endRead).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 position = []; var normals = []; var uvs = []; var skinIndices = []; var skinWeights = []; var data = this._currentGeo.GeometryData; for (let i2 = 0, l = data.indices.length; i2 < l; i2++) { var stride2 = data.indices[i2] * 2; var stride3 = data.indices[i2] * 3; var stride4 = data.indices[i2] * 4; position.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(position, 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 i2 = 0; i2 < materialIndices.length; i2++) { var currentMaterialIndex = materialIndices[i2]; if (currentMaterialIndex !== materialIndex) { materialIndex = currentMaterialIndex; if (group !== void 0) { group.count = i2 * 3 - group.start; groups.push(group); } group = { start: i2 * 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) { endRead = this._readInt1(0).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) { endRead = this._readInt1(endRead).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 i2 = 0; i2 < data.length; i2++) this._currentGeo.GeometryData.materialIndices[i2] = parseInt(data[i2]); 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 = 0; _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 = .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 i2 = 0; i2 < data.length; i2++) boneInf.Indeces.push(parseInt(data[i2])); 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 b = new Bone(); b.name = this.HieStack[frame].name; b.applyMatrix4(this.HieStack[frame].FrameTransformMatrix); b.matrixWorld = b.matrix; b.FrameTransformMatrix = this.HieStack[frame].FrameTransformMatrix; b.pos = new Vector3().setFromMatrixPosition(b.FrameTransformMatrix).toArray(); b.rotq = new Quaternion().setFromRotationMatrix(b.FrameTransformMatrix).toArray(); b.scl = new Vector3().setFromMatrixScale(b.FrameTransformMatrix).toArray(); if (this.HieStack[frame].parentName && this.HieStack[frame].parentName.length > 0) { for (let i2 = 0; i2 < _bones.length; i2++) if (this.HieStack[frame].parentName === _bones[i2].name) { _bones[i2].add(b); b.parent = i2; break; } } _bones.push(b); } } }, { 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 bb = 0; bb < putBones.length; bb++) if (putBones[bb].name === this._currentGeo.BoneInfs[bi].boneName) { boneIndex = bb; putBones[bb].OffsetMatrix = new Matrix4(); putBones[bb].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()); mesh = new SkinnedMesh(this._buildGeometry(), this._currentGeo.Materials.length === 1 ? this._currentGeo.Materials[0] : this._currentGeo.Materials); this._initSkeleton(mesh, putBones, offsetList); } else mesh = new Mesh(this._buildGeometry(), 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 i2, il; for (i2 = 0, il = boneList.length; i2 < il; i2++) { gbone = boneList[i2]; 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 (i2 = 0, il = boneList.length; i2 < il; i2++) { gbone = boneList[i2]; if (gbone.parent !== -1 && gbone.parent !== null && bones[gbone.parent] !== void 0) bones[gbone.parent].add(bones[i2]); else mesh.add(bones[i2]); } 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 i2 = 0; i2 < data.length; i2++) { var data2 = data[i2].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 b = 0; b < model.skeleton.bones.length; b++) { var findAnimation = false; for (let i2 = 0; i2 < animation.hierarchy.length; i2++) if (model.skeleton.bones[b].name === animation.hierarchy[i2].name) { findAnimation = true; var c_key = animation.hierarchy[i2].copy(); c_key.parent = -1; if (model.skeleton.bones[b].parent && model.skeleton.bones[b].parent.type === "Bone") { for (let bb = 0; bb < put.hierarchy.length; bb++) if (put.hierarchy[bb].name === model.skeleton.bones[b].parent.name) { c_key.parent = bb; c_key.parentName = model.skeleton.bones[b].parent.name; } } put.hierarchy.push(c_key); break; } if (!findAnimation) { var _c_key = animation.hierarchy[0].copy(); _c_key.name = model.skeleton.bones[b].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; }(); }(); //#endregion //#region node_modules/three-stdlib/loaders/BVHLoader.js var BVHLoader = class extends Loader { constructor(manager) { super(manager); this.animateBonePositions = true; this.animateBoneRotations = true; } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(text) { function readBvh(lines2) { if (nextLine(lines2) !== "HIERARCHY") console.error("THREE.BVHLoader: HIERARCHY expected."); const list = []; const root = readNode(lines2, nextLine(lines2), list); if (nextLine(lines2) !== "MOTION") console.error("THREE.BVHLoader: MOTION expected."); let tokens = nextLine(lines2).split(/[\s]+/); const numFrames = parseInt(tokens[1]); if (isNaN(numFrames)) console.error("THREE.BVHLoader: Failed to read number of frames."); tokens = nextLine(lines2).split(/[\s]+/); const frameTime = parseFloat(tokens[2]); if (isNaN(frameTime)) console.error("THREE.BVHLoader: Failed to read frame time."); for (let i = 0; i < numFrames; i++) { tokens = nextLine(lines2).split(/[\s]+/); readFrameData(tokens, i * frameTime, root); } return list; } function readFrameData(data, frameTime, bone) { if (bone.type === "ENDSITE") return; const keyframe = { time: frameTime, position: new Vector3(), rotation: new Quaternion() }; bone.frames.push(keyframe); const quat = new Quaternion(); const vx = new Vector3(1, 0, 0); const vy = new Vector3(0, 1, 0); const vz = new Vector3(0, 0, 1); for (let i = 0; i < bone.channels.length; i++) switch (bone.channels[i]) { case "Xposition": keyframe.position.x = parseFloat(data.shift().trim()); break; case "Yposition": keyframe.position.y = parseFloat(data.shift().trim()); break; case "Zposition": keyframe.position.z = parseFloat(data.shift().trim()); break; case "Xrotation": quat.setFromAxisAngle(vx, parseFloat(data.shift().trim()) * Math.PI / 180); keyframe.rotation.multiply(quat); break; case "Yrotation": quat.setFromAxisAngle(vy, parseFloat(data.shift().trim()) * Math.PI / 180); keyframe.rotation.multiply(quat); break; case "Zrotation": quat.setFromAxisAngle(vz, parseFloat(data.shift().trim()) * Math.PI / 180); keyframe.rotation.multiply(quat); break; default: console.warn("THREE.BVHLoader: Invalid channel type."); } for (let i = 0; i < bone.children.length; i++) readFrameData(data, frameTime, bone.children[i]); } function readNode(lines2, firstline, list) { const node = { name: "", type: "", frames: [] }; list.push(node); let tokens = firstline.split(/[\s]+/); if (tokens[0].toUpperCase() === "END" && tokens[1].toUpperCase() === "SITE") { node.type = "ENDSITE"; node.name = "ENDSITE"; } else { node.name = tokens[1]; node.type = tokens[0].toUpperCase(); } if (nextLine(lines2) !== "{") console.error("THREE.BVHLoader: Expected opening { after type & name"); tokens = nextLine(lines2).split(/[\s]+/); if (tokens[0] !== "OFFSET") console.error("THREE.BVHLoader: Expected OFFSET but got: " + tokens[0]); if (tokens.length !== 4) console.error("THREE.BVHLoader: Invalid number of values for OFFSET."); const offset = new Vector3(parseFloat(tokens[1]), parseFloat(tokens[2]), parseFloat(tokens[3])); if (isNaN(offset.x) || isNaN(offset.y) || isNaN(offset.z)) console.error("THREE.BVHLoader: Invalid values of OFFSET."); node.offset = offset; if (node.type !== "ENDSITE") { tokens = nextLine(lines2).split(/[\s]+/); if (tokens[0] !== "CHANNELS") console.error("THREE.BVHLoader: Expected CHANNELS definition."); const numChannels = parseInt(tokens[1]); node.channels = tokens.splice(2, numChannels); node.children = []; } while (true) { const line = nextLine(lines2); if (line === "}") return node; else node.children.push(readNode(lines2, line, list)); } } function toTHREEBone(source, list) { const bone = new Bone(); list.push(bone); bone.position.add(source.offset); bone.name = source.name; if (source.type !== "ENDSITE") for (let i = 0; i < source.children.length; i++) bone.add(toTHREEBone(source.children[i], list)); return bone; } function toTHREEAnimation(bones2) { const tracks = []; for (let i = 0; i < bones2.length; i++) { const bone = bones2[i]; if (bone.type === "ENDSITE") continue; const times = []; const positions = []; const rotations = []; for (let j = 0; j < bone.frames.length; j++) { const frame = bone.frames[j]; times.push(frame.time); positions.push(frame.position.x + bone.offset.x); positions.push(frame.position.y + bone.offset.y); positions.push(frame.position.z + bone.offset.z); rotations.push(frame.rotation.x); rotations.push(frame.rotation.y); rotations.push(frame.rotation.z); rotations.push(frame.rotation.w); } if (scope.animateBonePositions) tracks.push(new VectorKeyframeTrack(".bones[" + bone.name + "].position", times, positions)); if (scope.animateBoneRotations) tracks.push(new QuaternionKeyframeTrack(".bones[" + bone.name + "].quaternion", times, rotations)); } return new AnimationClip("animation", -1, tracks); } function nextLine(lines2) { let line; while ((line = lines2.shift().trim()).length === 0); return line; } const scope = this; const bones = readBvh(text.split(/[\r\n]+/g)); const threeBones = []; toTHREEBone(bones[0], threeBones); const threeClip = toTHREEAnimation(bones); return { skeleton: new Skeleton(threeBones), clip: threeClip }; } }; //#endregion //#region node_modules/three-stdlib/loaders/ColladaLoader.js var ColladaLoader = 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 loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text, path)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(text, path) { function getElementsByTagName(xml2, name) { const array = []; const childNodes = xml2.childNodes; for (let i = 0, l = childNodes.length; i < l; i++) { const child = childNodes[i]; if (child.nodeName === name) array.push(child); } return array; } function parseStrings(text2) { if (text2.length === 0) return []; const parts = text2.trim().split(/\s+/); const array = new Array(parts.length); for (let i = 0, l = parts.length; i < l; i++) array[i] = parts[i]; return array; } function parseFloats(text2) { if (text2.length === 0) return []; const parts = text2.trim().split(/\s+/); const array = new Array(parts.length); for (let i = 0, l = parts.length; i < l; i++) array[i] = parseFloat(parts[i]); return array; } function parseInts(text2) { if (text2.length === 0) return []; const parts = text2.trim().split(/\s+/); const array = new Array(parts.length); for (let i = 0, l = parts.length; i < l; i++) array[i] = parseInt(parts[i]); return array; } function parseId(text2) { return text2.substring(1); } function generateId() { return "three_default_" + count++; } function isEmpty(object) { return Object.keys(object).length === 0; } function parseAsset(xml2) { return { unit: parseAssetUnit(getElementsByTagName(xml2, "unit")[0]), upAxis: parseAssetUpAxis(getElementsByTagName(xml2, "up_axis")[0]) }; } function parseAssetUnit(xml2) { if (xml2 !== void 0 && xml2.hasAttribute("meter") === true) return parseFloat(xml2.getAttribute("meter")); else return 1; } function parseAssetUpAxis(xml2) { return xml2 !== void 0 ? xml2.textContent : "Y_UP"; } function parseLibrary(xml2, libraryName, nodeName, parser) { const library2 = getElementsByTagName(xml2, libraryName)[0]; if (library2 !== void 0) { const elements = getElementsByTagName(library2, nodeName); for (let i = 0; i < elements.length; i++) parser(elements[i]); } } function buildLibrary(data, builder) { for (const name in data) { const object = data[name]; object.build = builder(data[name]); } } function getBuild(data, builder) { if (data.build !== void 0) return data.build; data.build = builder(data); return data.build; } function parseAnimation(xml2) { const data = { sources: {}, samplers: {}, channels: {} }; let hasChildren = false; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; let id; switch (child.nodeName) { case "source": id = child.getAttribute("id"); data.sources[id] = parseSource(child); break; case "sampler": id = child.getAttribute("id"); data.samplers[id] = parseAnimationSampler(child); break; case "channel": id = child.getAttribute("target"); data.channels[id] = parseAnimationChannel(child); break; case "animation": parseAnimation(child); hasChildren = true; break; default: console.log(child); } } if (hasChildren === false) library.animations[xml2.getAttribute("id") || MathUtils.generateUUID()] = data; } function parseAnimationSampler(xml2) { const data = { inputs: {} }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "input": const id = parseId(child.getAttribute("source")); const semantic = child.getAttribute("semantic"); data.inputs[semantic] = id; break; } } return data; } function parseAnimationChannel(xml2) { const data = {}; let parts = xml2.getAttribute("target").split("/"); const id = parts.shift(); let sid = parts.shift(); const arraySyntax = sid.indexOf("(") !== -1; const memberSyntax = sid.indexOf(".") !== -1; if (memberSyntax) { parts = sid.split("."); sid = parts.shift(); data.member = parts.shift(); } else if (arraySyntax) { const indices = sid.split("("); sid = indices.shift(); for (let i = 0; i < indices.length; i++) indices[i] = parseInt(indices[i].replace(/\)/, "")); data.indices = indices; } data.id = id; data.sid = sid; data.arraySyntax = arraySyntax; data.memberSyntax = memberSyntax; data.sampler = parseId(xml2.getAttribute("source")); return data; } function buildAnimation(data) { const tracks = []; const channels = data.channels; const samplers = data.samplers; const sources = data.sources; for (const target in channels) if (channels.hasOwnProperty(target)) { const channel = channels[target]; const sampler = samplers[channel.sampler]; const inputId = sampler.inputs.INPUT; const outputId = sampler.inputs.OUTPUT; const inputSource = sources[inputId]; const outputSource = sources[outputId]; createKeyframeTracks(buildAnimationChannel(channel, inputSource, outputSource), tracks); } return tracks; } function getAnimation(id) { return getBuild(library.animations[id], buildAnimation); } function buildAnimationChannel(channel, inputSource, outputSource) { const node = library.nodes[channel.id]; const object3D = getNode(node.id); const transform = node.transforms[channel.sid]; const defaultMatrix = node.matrix.clone().transpose(); let time, stride; let i, il, j, jl; const data = {}; switch (transform) { case "matrix": for (i = 0, il = inputSource.array.length; i < il; i++) { time = inputSource.array[i]; stride = i * outputSource.stride; if (data[time] === void 0) data[time] = {}; if (channel.arraySyntax === true) { const value = outputSource.array[stride]; const index = channel.indices[0] + 4 * channel.indices[1]; data[time][index] = value; } else for (j = 0, jl = outputSource.stride; j < jl; j++) data[time][j] = outputSource.array[stride + j]; } break; case "translate": console.warn("THREE.ColladaLoader: Animation transform type \"%s\" not yet implemented.", transform); break; case "rotate": console.warn("THREE.ColladaLoader: Animation transform type \"%s\" not yet implemented.", transform); break; case "scale": console.warn("THREE.ColladaLoader: Animation transform type \"%s\" not yet implemented.", transform); break; } const keyframes = prepareAnimationData(data, defaultMatrix); return { name: object3D.uuid, keyframes }; } function prepareAnimationData(data, defaultMatrix) { const keyframes = []; for (const time in data) keyframes.push({ time: parseFloat(time), value: data[time] }); keyframes.sort(ascending); for (let i = 0; i < 16; i++) transformAnimationData(keyframes, i, defaultMatrix.elements[i]); return keyframes; function ascending(a, b) { return a.time - b.time; } } const position = new Vector3(); const scale = new Vector3(); const quaternion = new Quaternion(); function createKeyframeTracks(animation, tracks) { const keyframes = animation.keyframes; const name = animation.name; const times = []; const positionData = []; const quaternionData = []; const scaleData = []; for (let i = 0, l = keyframes.length; i < l; i++) { const keyframe = keyframes[i]; const time = keyframe.time; const value = keyframe.value; matrix.fromArray(value).transpose(); matrix.decompose(position, quaternion, scale); times.push(time); positionData.push(position.x, position.y, position.z); quaternionData.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w); scaleData.push(scale.x, scale.y, scale.z); } if (positionData.length > 0) tracks.push(new VectorKeyframeTrack(name + ".position", times, positionData)); if (quaternionData.length > 0) tracks.push(new QuaternionKeyframeTrack(name + ".quaternion", times, quaternionData)); if (scaleData.length > 0) tracks.push(new VectorKeyframeTrack(name + ".scale", times, scaleData)); return tracks; } function transformAnimationData(keyframes, property, defaultValue) { let keyframe; let empty = true; let i, l; for (i = 0, l = keyframes.length; i < l; i++) { keyframe = keyframes[i]; if (keyframe.value[property] === void 0) keyframe.value[property] = null; else empty = false; } if (empty === true) for (i = 0, l = keyframes.length; i < l; i++) { keyframe = keyframes[i]; keyframe.value[property] = defaultValue; } else createMissingKeyframes(keyframes, property); } function createMissingKeyframes(keyframes, property) { let prev, next; for (let i = 0, l = keyframes.length; i < l; i++) { const keyframe = keyframes[i]; if (keyframe.value[property] === null) { prev = getPrev(keyframes, i, property); next = getNext(keyframes, i, property); if (prev === null) { keyframe.value[property] = next.value[property]; continue; } if (next === null) { keyframe.value[property] = prev.value[property]; continue; } interpolate(keyframe, prev, next, property); } } } function getPrev(keyframes, i, property) { while (i >= 0) { const keyframe = keyframes[i]; if (keyframe.value[property] !== null) return keyframe; i--; } return null; } function getNext(keyframes, i, property) { while (i < keyframes.length) { const keyframe = keyframes[i]; if (keyframe.value[property] !== null) return keyframe; i++; } return null; } function interpolate(key, prev, next, property) { if (next.time - prev.time === 0) { key.value[property] = prev.value[property]; return; } key.value[property] = (key.time - prev.time) * (next.value[property] - prev.value[property]) / (next.time - prev.time) + prev.value[property]; } function parseAnimationClip(xml2) { const data = { name: xml2.getAttribute("id") || "default", start: parseFloat(xml2.getAttribute("start") || 0), end: parseFloat(xml2.getAttribute("end") || 0), animations: [] }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "instance_animation": data.animations.push(parseId(child.getAttribute("url"))); break; } } library.clips[xml2.getAttribute("id")] = data; } function buildAnimationClip(data) { const tracks = []; const name = data.name; const duration = data.end - data.start || -1; const animations2 = data.animations; for (let i = 0, il = animations2.length; i < il; i++) { const animationTracks = getAnimation(animations2[i]); for (let j = 0, jl = animationTracks.length; j < jl; j++) tracks.push(animationTracks[j]); } return new AnimationClip(name, duration, tracks); } function getAnimationClip(id) { return getBuild(library.clips[id], buildAnimationClip); } function parseController(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "skin": data.id = parseId(child.getAttribute("source")); data.skin = parseSkin(child); break; case "morph": data.id = parseId(child.getAttribute("source")); console.warn("THREE.ColladaLoader: Morph target animation not supported yet."); break; } } library.controllers[xml2.getAttribute("id")] = data; } function parseSkin(xml2) { const data = { sources: {} }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "bind_shape_matrix": data.bindShapeMatrix = parseFloats(child.textContent); break; case "source": const id = child.getAttribute("id"); data.sources[id] = parseSource(child); break; case "joints": data.joints = parseJoints(child); break; case "vertex_weights": data.vertexWeights = parseVertexWeights(child); break; } } return data; } function parseJoints(xml2) { const data = { inputs: {} }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "input": const semantic = child.getAttribute("semantic"); const id = parseId(child.getAttribute("source")); data.inputs[semantic] = id; break; } } return data; } function parseVertexWeights(xml2) { const data = { inputs: {} }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "input": const semantic = child.getAttribute("semantic"); const id = parseId(child.getAttribute("source")); const offset = parseInt(child.getAttribute("offset")); data.inputs[semantic] = { id, offset }; break; case "vcount": data.vcount = parseInts(child.textContent); break; case "v": data.v = parseInts(child.textContent); break; } } return data; } function buildController(data) { const build = { id: data.id }; const geometry = library.geometries[build.id]; if (data.skin !== void 0) { build.skin = buildSkin(data.skin); geometry.sources.skinIndices = build.skin.indices; geometry.sources.skinWeights = build.skin.weights; } return build; } function buildSkin(data) { const BONE_LIMIT = 4; const build = { joints: [], indices: { array: [], stride: BONE_LIMIT }, weights: { array: [], stride: BONE_LIMIT } }; const sources = data.sources; const vertexWeights = data.vertexWeights; const vcount = vertexWeights.vcount; const v = vertexWeights.v; const jointOffset = vertexWeights.inputs.JOINT.offset; const weightOffset = vertexWeights.inputs.WEIGHT.offset; const jointSource = data.sources[data.joints.inputs.JOINT]; const inverseSource = data.sources[data.joints.inputs.INV_BIND_MATRIX]; const weights = sources[vertexWeights.inputs.WEIGHT.id].array; let stride = 0; let i, j, l; for (i = 0, l = vcount.length; i < l; i++) { const jointCount = vcount[i]; const vertexSkinData = []; for (j = 0; j < jointCount; j++) { const skinIndex = v[stride + jointOffset]; const skinWeight = weights[v[stride + weightOffset]]; vertexSkinData.push({ index: skinIndex, weight: skinWeight }); stride += 2; } vertexSkinData.sort(descending); for (j = 0; j < BONE_LIMIT; j++) { const d = vertexSkinData[j]; if (d !== void 0) { build.indices.array.push(d.index); build.weights.array.push(d.weight); } else { build.indices.array.push(0); build.weights.array.push(0); } } } if (data.bindShapeMatrix) build.bindMatrix = new Matrix4().fromArray(data.bindShapeMatrix).transpose(); else build.bindMatrix = new Matrix4().identity(); for (i = 0, l = jointSource.array.length; i < l; i++) { const name = jointSource.array[i]; const boneInverse = new Matrix4().fromArray(inverseSource.array, i * inverseSource.stride).transpose(); build.joints.push({ name, boneInverse }); } return build; function descending(a, b) { return b.weight - a.weight; } } function getController(id) { return getBuild(library.controllers[id], buildController); } function parseImage(xml2) { const data = { init_from: getElementsByTagName(xml2, "init_from")[0].textContent }; library.images[xml2.getAttribute("id")] = data; } function buildImage(data) { if (data.build !== void 0) return data.build; return data.init_from; } function getImage(id) { const data = library.images[id]; if (data !== void 0) return getBuild(data, buildImage); console.warn("THREE.ColladaLoader: Couldn't find image with ID:", id); return null; } function parseEffect(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "profile_COMMON": data.profile = parseEffectProfileCOMMON(child); break; } } library.effects[xml2.getAttribute("id")] = data; } function parseEffectProfileCOMMON(xml2) { const data = { surfaces: {}, samplers: {} }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "newparam": parseEffectNewparam(child, data); break; case "technique": data.technique = parseEffectTechnique(child); break; case "extra": data.extra = parseEffectExtra(child); break; } } return data; } function parseEffectNewparam(xml2, data) { const sid = xml2.getAttribute("sid"); for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "surface": data.surfaces[sid] = parseEffectSurface(child); break; case "sampler2D": data.samplers[sid] = parseEffectSampler(child); break; } } } function parseEffectSurface(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "init_from": data.init_from = child.textContent; break; } } return data; } function parseEffectSampler(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "source": data.source = child.textContent; break; } } return data; } function parseEffectTechnique(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "constant": case "lambert": case "blinn": case "phong": data.type = child.nodeName; data.parameters = parseEffectParameters(child); break; case "extra": data.extra = parseEffectExtra(child); break; } } return data; } function parseEffectParameters(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "emission": case "diffuse": case "specular": case "bump": case "ambient": case "shininess": case "transparency": data[child.nodeName] = parseEffectParameter(child); break; case "transparent": data[child.nodeName] = { opaque: child.hasAttribute("opaque") ? child.getAttribute("opaque") : "A_ONE", data: parseEffectParameter(child) }; break; } } return data; } function parseEffectParameter(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "color": data[child.nodeName] = parseFloats(child.textContent); break; case "float": data[child.nodeName] = parseFloat(child.textContent); break; case "texture": data[child.nodeName] = { id: child.getAttribute("texture"), extra: parseEffectParameterTexture(child) }; break; } } return data; } function parseEffectParameterTexture(xml2) { const data = { technique: {} }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "extra": parseEffectParameterTextureExtra(child, data); break; } } return data; } function parseEffectParameterTextureExtra(xml2, data) { for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "technique": parseEffectParameterTextureExtraTechnique(child, data); break; } } } function parseEffectParameterTextureExtraTechnique(xml2, data) { for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "repeatU": case "repeatV": case "offsetU": case "offsetV": data.technique[child.nodeName] = parseFloat(child.textContent); break; case "wrapU": case "wrapV": if (child.textContent.toUpperCase() === "TRUE") data.technique[child.nodeName] = 1; else if (child.textContent.toUpperCase() === "FALSE") data.technique[child.nodeName] = 0; else data.technique[child.nodeName] = parseInt(child.textContent); break; case "bump": data[child.nodeName] = parseEffectExtraTechniqueBump(child); break; } } } function parseEffectExtra(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "technique": data.technique = parseEffectExtraTechnique(child); break; } } return data; } function parseEffectExtraTechnique(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "double_sided": data[child.nodeName] = parseInt(child.textContent); break; case "bump": data[child.nodeName] = parseEffectExtraTechniqueBump(child); break; } } return data; } function parseEffectExtraTechniqueBump(xml2) { var data = {}; for (var i = 0, l = xml2.childNodes.length; i < l; i++) { var child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "texture": data[child.nodeName] = { id: child.getAttribute("texture"), texcoord: child.getAttribute("texcoord"), extra: parseEffectParameterTexture(child) }; break; } } return data; } function buildEffect(data) { return data; } function getEffect(id) { return getBuild(library.effects[id], buildEffect); } function parseMaterial(xml2) { const data = { name: xml2.getAttribute("name") }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "instance_effect": data.url = parseId(child.getAttribute("url")); break; } } library.materials[xml2.getAttribute("id")] = data; } function getTextureLoader(image) { let loader; let extension = image.slice((image.lastIndexOf(".") - 1 >>> 0) + 2); extension = extension.toLowerCase(); switch (extension) { case "tga": loader = tgaLoader; break; default: loader = textureLoader; } return loader; } function buildMaterial(data) { const effect = getEffect(data.url); const technique = effect.profile.technique; let material; switch (technique.type) { case "phong": case "blinn": material = new MeshPhongMaterial(); break; case "lambert": material = new MeshLambertMaterial(); break; default: material = new MeshBasicMaterial(); break; } material.name = data.name || ""; function getTexture(textureObject) { const sampler = effect.profile.samplers[textureObject.id]; let image = null; if (sampler !== void 0) { const surface = effect.profile.surfaces[sampler.source]; image = getImage(surface.init_from); } else { console.warn("THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530)."); image = getImage(textureObject.id); } if (image !== null) { const loader = getTextureLoader(image); if (loader !== void 0) { const texture = loader.load(image); const extra = textureObject.extra; if (extra !== void 0 && extra.technique !== void 0 && isEmpty(extra.technique) === false) { const technique2 = extra.technique; texture.wrapS = technique2.wrapU ? RepeatWrapping : ClampToEdgeWrapping; texture.wrapT = technique2.wrapV ? RepeatWrapping : ClampToEdgeWrapping; texture.offset.set(technique2.offsetU || 0, technique2.offsetV || 0); texture.repeat.set(technique2.repeatU || 1, technique2.repeatV || 1); } else { texture.wrapS = RepeatWrapping; texture.wrapT = RepeatWrapping; } return texture; } else { console.warn("THREE.ColladaLoader: Loader for texture %s not found.", image); return null; } } else { console.warn("THREE.ColladaLoader: Couldn't create texture with ID:", textureObject.id); return null; } } const parameters = technique.parameters; for (const key in parameters) { const parameter = parameters[key]; switch (key) { case "diffuse": if (parameter.color) material.color.fromArray(parameter.color); if (parameter.texture) material.map = getTexture(parameter.texture); break; case "specular": if (parameter.color && material.specular) material.specular.fromArray(parameter.color); if (parameter.texture) material.specularMap = getTexture(parameter.texture); break; case "bump": if (parameter.texture) material.normalMap = getTexture(parameter.texture); break; case "ambient": if (parameter.texture) material.lightMap = getTexture(parameter.texture); break; case "shininess": if (parameter.float && material.shininess) material.shininess = parameter.float; break; case "emission": if (parameter.color && material.emissive) material.emissive.fromArray(parameter.color); if (parameter.texture) material.emissiveMap = getTexture(parameter.texture); break; } } let transparent = parameters["transparent"]; let transparency = parameters["transparency"]; if (transparency === void 0 && transparent) transparency = { float: 1 }; if (transparent === void 0 && transparency) transparent = { opaque: "A_ONE", data: { color: [ 1, 1, 1, 1 ] } }; if (transparent && transparency) if (transparent.data.texture) material.transparent = true; else { const color = transparent.data.color; switch (transparent.opaque) { case "A_ONE": material.opacity = color[3] * transparency.float; break; case "RGB_ZERO": material.opacity = 1 - color[0] * transparency.float; break; case "A_ZERO": material.opacity = 1 - color[3] * transparency.float; break; case "RGB_ONE": material.opacity = color[0] * transparency.float; break; default: console.warn("THREE.ColladaLoader: Invalid opaque type \"%s\" of transparent tag.", transparent.opaque); } if (material.opacity < 1) material.transparent = true; } if (technique.extra !== void 0 && technique.extra.technique !== void 0) { const techniques = technique.extra.technique; for (const k in techniques) { const v = techniques[k]; switch (k) { case "double_sided": material.side = v === 1 ? 2 : 0; break; case "bump": material.normalMap = getTexture(v.texture); material.normalScale = new Vector2(1, 1); break; } } } return material; } function getMaterial(id) { return getBuild(library.materials[id], buildMaterial); } function parseCamera(xml2) { const data = { name: xml2.getAttribute("name") }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "optics": data.optics = parseCameraOptics(child); break; } } library.cameras[xml2.getAttribute("id")] = data; } function parseCameraOptics(xml2) { for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; switch (child.nodeName) { case "technique_common": return parseCameraTechnique(child); } } return {}; } function parseCameraTechnique(xml2) { const data = {}; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; switch (child.nodeName) { case "perspective": case "orthographic": data.technique = child.nodeName; data.parameters = parseCameraParameters(child); break; } } return data; } function parseCameraParameters(xml2) { const data = {}; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; switch (child.nodeName) { case "xfov": case "yfov": case "xmag": case "ymag": case "znear": case "zfar": case "aspect_ratio": data[child.nodeName] = parseFloat(child.textContent); break; } } return data; } function buildCamera(data) { let camera; switch (data.optics.technique) { case "perspective": camera = new PerspectiveCamera(data.optics.parameters.yfov, data.optics.parameters.aspect_ratio, data.optics.parameters.znear, data.optics.parameters.zfar); break; case "orthographic": let ymag = data.optics.parameters.ymag; let xmag = data.optics.parameters.xmag; const aspectRatio = data.optics.parameters.aspect_ratio; xmag = xmag === void 0 ? ymag * aspectRatio : xmag; ymag = ymag === void 0 ? xmag / aspectRatio : ymag; xmag *= .5; ymag *= .5; camera = new OrthographicCamera(-xmag, xmag, ymag, -ymag, data.optics.parameters.znear, data.optics.parameters.zfar); break; default: camera = new PerspectiveCamera(); break; } camera.name = data.name || ""; return camera; } function getCamera(id) { const data = library.cameras[id]; if (data !== void 0) return getBuild(data, buildCamera); console.warn("THREE.ColladaLoader: Couldn't find camera with ID:", id); return null; } function parseLight(xml2) { let data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "technique_common": data = parseLightTechnique(child); break; } } library.lights[xml2.getAttribute("id")] = data; } function parseLightTechnique(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "directional": case "point": case "spot": case "ambient": data.technique = child.nodeName; data.parameters = parseLightParameters(child); } } return data; } function parseLightParameters(xml2) { const data = {}; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "color": const array = parseFloats(child.textContent); data.color = new Color().fromArray(array); break; case "falloff_angle": data.falloffAngle = parseFloat(child.textContent); break; case "quadratic_attenuation": const f = parseFloat(child.textContent); data.distance = f ? Math.sqrt(1 / f) : 0; break; } } return data; } function buildLight(data) { let light; switch (data.technique) { case "directional": light = new DirectionalLight(); break; case "point": light = new PointLight(); break; case "spot": light = new SpotLight(); break; case "ambient": light = new AmbientLight(); break; } if (data.parameters.color) light.color.copy(data.parameters.color); if (data.parameters.distance) light.distance = data.parameters.distance; return light; } function getLight(id) { const data = library.lights[id]; if (data !== void 0) return getBuild(data, buildLight); console.warn("THREE.ColladaLoader: Couldn't find light with ID:", id); return null; } function parseGeometry(xml2) { const data = { name: xml2.getAttribute("name"), sources: {}, vertices: {}, primitives: [] }; const mesh = getElementsByTagName(xml2, "mesh")[0]; if (mesh === void 0) return; for (let i = 0; i < mesh.childNodes.length; i++) { const child = mesh.childNodes[i]; if (child.nodeType !== 1) continue; const id = child.getAttribute("id"); switch (child.nodeName) { case "source": data.sources[id] = parseSource(child); break; case "vertices": data.vertices = parseGeometryVertices(child); break; case "polygons": console.warn("THREE.ColladaLoader: Unsupported primitive type: ", child.nodeName); break; case "lines": case "linestrips": case "polylist": case "triangles": data.primitives.push(parseGeometryPrimitive(child)); break; default: console.log(child); } } library.geometries[xml2.getAttribute("id")] = data; } function parseSource(xml2) { const data = { array: [], stride: 3 }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "float_array": data.array = parseFloats(child.textContent); break; case "Name_array": data.array = parseStrings(child.textContent); break; case "technique_common": const accessor = getElementsByTagName(child, "accessor")[0]; if (accessor !== void 0) data.stride = parseInt(accessor.getAttribute("stride")); break; } } return data; } function parseGeometryVertices(xml2) { const data = {}; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; data[child.getAttribute("semantic")] = parseId(child.getAttribute("source")); } return data; } function parseGeometryPrimitive(xml2) { const primitive = { type: xml2.nodeName, material: xml2.getAttribute("material"), count: parseInt(xml2.getAttribute("count")), inputs: {}, stride: 0, hasUV: false }; for (let i = 0, l = xml2.childNodes.length; i < l; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "input": const id = parseId(child.getAttribute("source")); const semantic = child.getAttribute("semantic"); const offset = parseInt(child.getAttribute("offset")); const set = parseInt(child.getAttribute("set")); const inputname = set > 0 ? semantic + set : semantic; primitive.inputs[inputname] = { id, offset }; primitive.stride = Math.max(primitive.stride, offset + 1); if (semantic === "TEXCOORD") primitive.hasUV = true; break; case "vcount": primitive.vcount = parseInts(child.textContent); break; case "p": primitive.p = parseInts(child.textContent); break; } } return primitive; } function groupPrimitives(primitives) { const build = {}; for (let i = 0; i < primitives.length; i++) { const primitive = primitives[i]; if (build[primitive.type] === void 0) build[primitive.type] = []; build[primitive.type].push(primitive); } return build; } function checkUVCoordinates(primitives) { let count2 = 0; for (let i = 0, l = primitives.length; i < l; i++) if (primitives[i].hasUV === true) count2++; if (count2 > 0 && count2 < primitives.length) primitives.uvsNeedsFix = true; } function buildGeometry(data) { const build = {}; const sources = data.sources; const vertices = data.vertices; const primitives = data.primitives; if (primitives.length === 0) return {}; const groupedPrimitives = groupPrimitives(primitives); for (const type in groupedPrimitives) { const primitiveType = groupedPrimitives[type]; checkUVCoordinates(primitiveType); build[type] = buildGeometryType(primitiveType, sources, vertices); } return build; } function buildGeometryType(primitives, sources, vertices) { const build = {}; const position2 = { array: [], stride: 0 }; const normal = { array: [], stride: 0 }; const uv = { array: [], stride: 0 }; const uv1 = { array: [], stride: 0 }; const color = { array: [], stride: 0 }; const skinIndex = { array: [], stride: 4 }; const skinWeight = { array: [], stride: 4 }; const geometry = new BufferGeometry(); const materialKeys = []; let start = 0; for (let p = 0; p < primitives.length; p++) { const primitive = primitives[p]; const inputs = primitive.inputs; let count2 = 0; switch (primitive.type) { case "lines": case "linestrips": count2 = primitive.count * 2; break; case "triangles": count2 = primitive.count * 3; break; case "polylist": for (let g = 0; g < primitive.count; g++) { const vc = primitive.vcount[g]; switch (vc) { case 3: count2 += 3; break; case 4: count2 += 6; break; default: count2 += (vc - 2) * 3; break; } } break; default: console.warn("THREE.ColladaLoader: Unknow primitive type:", primitive.type); } geometry.addGroup(start, count2, p); start += count2; if (primitive.material) materialKeys.push(primitive.material); for (const name in inputs) { const input = inputs[name]; switch (name) { case "VERTEX": for (const key in vertices) { const id = vertices[key]; switch (key) { case "POSITION": const prevLength = position2.array.length; buildGeometryData(primitive, sources[id], input.offset, position2.array); position2.stride = sources[id].stride; if (sources.skinWeights && sources.skinIndices) { buildGeometryData(primitive, sources.skinIndices, input.offset, skinIndex.array); buildGeometryData(primitive, sources.skinWeights, input.offset, skinWeight.array); } if (primitive.hasUV === false && primitives.uvsNeedsFix === true) { const count3 = (position2.array.length - prevLength) / position2.stride; for (let i = 0; i < count3; i++) uv.array.push(0, 0); } break; case "NORMAL": buildGeometryData(primitive, sources[id], input.offset, normal.array); normal.stride = sources[id].stride; break; case "COLOR": buildGeometryData(primitive, sources[id], input.offset, color.array); color.stride = sources[id].stride; break; case "TEXCOORD": buildGeometryData(primitive, sources[id], input.offset, uv.array); uv.stride = sources[id].stride; break; case "TEXCOORD1": buildGeometryData(primitive, sources[id], input.offset, uv1.array); uv.stride = sources[id].stride; break; default: console.warn("THREE.ColladaLoader: Semantic \"%s\" not handled in geometry build process.", key); } } break; case "NORMAL": buildGeometryData(primitive, sources[input.id], input.offset, normal.array); normal.stride = sources[input.id].stride; break; case "COLOR": buildGeometryData(primitive, sources[input.id], input.offset, color.array); color.stride = sources[input.id].stride; break; case "TEXCOORD": buildGeometryData(primitive, sources[input.id], input.offset, uv.array); uv.stride = sources[input.id].stride; break; case "TEXCOORD1": buildGeometryData(primitive, sources[input.id], input.offset, uv1.array); uv1.stride = sources[input.id].stride; break; } } } if (position2.array.length > 0) geometry.setAttribute("position", new Float32BufferAttribute(position2.array, position2.stride)); if (normal.array.length > 0) geometry.setAttribute("normal", new Float32BufferAttribute(normal.array, normal.stride)); if (color.array.length > 0) geometry.setAttribute("color", new Float32BufferAttribute(color.array, color.stride)); if (uv.array.length > 0) geometry.setAttribute("uv", new Float32BufferAttribute(uv.array, uv.stride)); if (uv1.array.length > 0) geometry.setAttribute(UV1, new Float32BufferAttribute(uv1.array, uv1.stride)); if (skinIndex.array.length > 0) geometry.setAttribute("skinIndex", new Float32BufferAttribute(skinIndex.array, skinIndex.stride)); if (skinWeight.array.length > 0) geometry.setAttribute("skinWeight", new Float32BufferAttribute(skinWeight.array, skinWeight.stride)); build.data = geometry; build.type = primitives[0].type; build.materialKeys = materialKeys; return build; } function buildGeometryData(primitive, source, offset, array) { const indices = primitive.p; const stride = primitive.stride; const vcount = primitive.vcount; function pushVector(i) { let index = indices[i + offset] * sourceStride; const length = index + sourceStride; for (; index < length; index++) array.push(sourceArray[index]); } const sourceArray = source.array; const sourceStride = source.stride; if (primitive.vcount !== void 0) { let index = 0; for (let i = 0, l = vcount.length; i < l; i++) { const count2 = vcount[i]; if (count2 === 4) { const a = index + stride * 0; const b = index + stride * 1; const c = index + stride * 2; const d = index + stride * 3; pushVector(a); pushVector(b); pushVector(d); pushVector(b); pushVector(c); pushVector(d); } else if (count2 === 3) { const a = index + stride * 0; const b = index + stride * 1; const c = index + stride * 2; pushVector(a); pushVector(b); pushVector(c); } else if (count2 > 4) for (let k = 1, kl = count2 - 2; k <= kl; k++) { const a = index + stride * 0; const b = index + stride * k; const c = index + stride * (k + 1); pushVector(a); pushVector(b); pushVector(c); } index += stride * count2; } } else for (let i = 0, l = indices.length; i < l; i += stride) pushVector(i); } function getGeometry(id) { return getBuild(library.geometries[id], buildGeometry); } function parseKinematicsModel(xml2) { const data = { name: xml2.getAttribute("name") || "", joints: {}, links: [] }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "technique_common": parseKinematicsTechniqueCommon(child, data); break; } } library.kinematicsModels[xml2.getAttribute("id")] = data; } function buildKinematicsModel(data) { if (data.build !== void 0) return data.build; return data; } function getKinematicsModel(id) { return getBuild(library.kinematicsModels[id], buildKinematicsModel); } function parseKinematicsTechniqueCommon(xml2, data) { for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "joint": data.joints[child.getAttribute("sid")] = parseKinematicsJoint(child); break; case "link": data.links.push(parseKinematicsLink(child)); break; } } } function parseKinematicsJoint(xml2) { let data; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "prismatic": case "revolute": data = parseKinematicsJointParameter(child); break; } } return data; } function parseKinematicsJointParameter(xml2) { const data = { sid: xml2.getAttribute("sid"), name: xml2.getAttribute("name") || "", axis: new Vector3(), limits: { min: 0, max: 0 }, type: xml2.nodeName, static: false, zeroPosition: 0, middlePosition: 0 }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "axis": const array = parseFloats(child.textContent); data.axis.fromArray(array); break; case "limits": const max = child.getElementsByTagName("max")[0]; const min = child.getElementsByTagName("min")[0]; data.limits.max = parseFloat(max.textContent); data.limits.min = parseFloat(min.textContent); break; } } if (data.limits.min >= data.limits.max) data.static = true; data.middlePosition = (data.limits.min + data.limits.max) / 2; return data; } function parseKinematicsLink(xml2) { const data = { sid: xml2.getAttribute("sid"), name: xml2.getAttribute("name") || "", attachments: [], transforms: [] }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "attachment_full": data.attachments.push(parseKinematicsAttachment(child)); break; case "matrix": case "translate": case "rotate": data.transforms.push(parseKinematicsTransform(child)); break; } } return data; } function parseKinematicsAttachment(xml2) { const data = { joint: xml2.getAttribute("joint").split("/").pop(), transforms: [], links: [] }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "link": data.links.push(parseKinematicsLink(child)); break; case "matrix": case "translate": case "rotate": data.transforms.push(parseKinematicsTransform(child)); break; } } return data; } function parseKinematicsTransform(xml2) { const data = { type: xml2.nodeName }; const array = parseFloats(xml2.textContent); switch (data.type) { case "matrix": data.obj = new Matrix4(); data.obj.fromArray(array).transpose(); break; case "translate": data.obj = new Vector3(); data.obj.fromArray(array); break; case "rotate": data.obj = new Vector3(); data.obj.fromArray(array); data.angle = MathUtils.degToRad(array[3]); break; } return data; } function parsePhysicsModel(xml2) { const data = { name: xml2.getAttribute("name") || "", rigidBodies: {} }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "rigid_body": data.rigidBodies[child.getAttribute("name")] = {}; parsePhysicsRigidBody(child, data.rigidBodies[child.getAttribute("name")]); break; } } library.physicsModels[xml2.getAttribute("id")] = data; } function parsePhysicsRigidBody(xml2, data) { for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "technique_common": parsePhysicsTechniqueCommon(child, data); break; } } } function parsePhysicsTechniqueCommon(xml2, data) { for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "inertia": data.inertia = parseFloats(child.textContent); break; case "mass": data.mass = parseFloats(child.textContent)[0]; break; } } } function parseKinematicsScene(xml2) { const data = { bindJointAxis: [] }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "bind_joint_axis": data.bindJointAxis.push(parseKinematicsBindJointAxis(child)); break; } } library.kinematicsScenes[parseId(xml2.getAttribute("url"))] = data; } function parseKinematicsBindJointAxis(xml2) { const data = { target: xml2.getAttribute("target").split("/").pop() }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; switch (child.nodeName) { case "axis": data.axis = child.getElementsByTagName("param")[0].textContent; const tmpJointIndex = data.axis.split("inst_").pop().split("axis")[0]; data.jointIndex = tmpJointIndex.substr(0, tmpJointIndex.length - 1); break; } } return data; } function buildKinematicsScene(data) { if (data.build !== void 0) return data.build; return data; } function getKinematicsScene(id) { return getBuild(library.kinematicsScenes[id], buildKinematicsScene); } function setupKinematics() { const kinematicsModelId = Object.keys(library.kinematicsModels)[0]; const kinematicsSceneId = Object.keys(library.kinematicsScenes)[0]; const visualSceneId = Object.keys(library.visualScenes)[0]; if (kinematicsModelId === void 0 || kinematicsSceneId === void 0) return; const kinematicsModel = getKinematicsModel(kinematicsModelId); const kinematicsScene = getKinematicsScene(kinematicsSceneId); const visualScene = getVisualScene(visualSceneId); const bindJointAxis = kinematicsScene.bindJointAxis; const jointMap = {}; for (let i = 0, l = bindJointAxis.length; i < l; i++) { const axis = bindJointAxis[i]; const targetElement = collada.querySelector("[sid=\"" + axis.target + "\"]"); if (targetElement) { const parentVisualElement = targetElement.parentElement; connect(axis.jointIndex, parentVisualElement); } } function connect(jointIndex, visualElement) { const visualElementName = visualElement.getAttribute("name"); const joint = kinematicsModel.joints[jointIndex]; visualScene.traverse(function(object) { if (object.name === visualElementName) jointMap[jointIndex] = { object, transforms: buildTransformList(visualElement), joint, position: joint.zeroPosition }; }); } const m0 = new Matrix4(); kinematics = { joints: kinematicsModel && kinematicsModel.joints, getJointValue: function(jointIndex) { const jointData = jointMap[jointIndex]; if (jointData) return jointData.position; else console.warn("THREE.ColladaLoader: Joint " + jointIndex + " doesn't exist."); }, setJointValue: function(jointIndex, value) { const jointData = jointMap[jointIndex]; if (jointData) { const joint = jointData.joint; if (value > joint.limits.max || value < joint.limits.min) console.warn("THREE.ColladaLoader: Joint " + jointIndex + " value " + value + " outside of limits (min: " + joint.limits.min + ", max: " + joint.limits.max + ")."); else if (joint.static) console.warn("THREE.ColladaLoader: Joint " + jointIndex + " is static."); else { const object = jointData.object; const axis = joint.axis; const transforms = jointData.transforms; matrix.identity(); for (let i = 0; i < transforms.length; i++) { const transform = transforms[i]; if (transform.sid && transform.sid.indexOf(jointIndex) !== -1) switch (joint.type) { case "revolute": matrix.multiply(m0.makeRotationAxis(axis, MathUtils.degToRad(value))); break; case "prismatic": matrix.multiply(m0.makeTranslation(axis.x * value, axis.y * value, axis.z * value)); break; default: console.warn("THREE.ColladaLoader: Unknown joint type: " + joint.type); break; } else switch (transform.type) { case "matrix": matrix.multiply(transform.obj); break; case "translate": matrix.multiply(m0.makeTranslation(transform.obj.x, transform.obj.y, transform.obj.z)); break; case "scale": matrix.scale(transform.obj); break; case "rotate": matrix.multiply(m0.makeRotationAxis(transform.obj, transform.angle)); break; } } object.matrix.copy(matrix); object.matrix.decompose(object.position, object.quaternion, object.scale); jointMap[jointIndex].position = value; } } else console.log("THREE.ColladaLoader: " + jointIndex + " does not exist."); } }; } function buildTransformList(node) { const transforms = []; const xml2 = collada.querySelector("[id=\"" + node.id + "\"]"); for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; let array, vector2; switch (child.nodeName) { case "matrix": array = parseFloats(child.textContent); const matrix2 = new Matrix4().fromArray(array).transpose(); transforms.push({ sid: child.getAttribute("sid"), type: child.nodeName, obj: matrix2 }); break; case "translate": case "scale": array = parseFloats(child.textContent); vector2 = new Vector3().fromArray(array); transforms.push({ sid: child.getAttribute("sid"), type: child.nodeName, obj: vector2 }); break; case "rotate": array = parseFloats(child.textContent); vector2 = new Vector3().fromArray(array); const angle = MathUtils.degToRad(array[3]); transforms.push({ sid: child.getAttribute("sid"), type: child.nodeName, obj: vector2, angle }); break; } } return transforms; } function prepareNodes(xml2) { const elements = xml2.getElementsByTagName("node"); for (let i = 0; i < elements.length; i++) { const element = elements[i]; if (element.hasAttribute("id") === false) element.setAttribute("id", generateId()); } } const matrix = new Matrix4(); const vector = new Vector3(); function parseNode(xml2) { const data = { name: xml2.getAttribute("name") || "", type: xml2.getAttribute("type"), id: xml2.getAttribute("id"), sid: xml2.getAttribute("sid"), matrix: new Matrix4(), nodes: [], instanceCameras: [], instanceControllers: [], instanceLights: [], instanceGeometries: [], instanceNodes: [], transforms: {} }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; if (child.nodeType !== 1) continue; let array; switch (child.nodeName) { case "node": data.nodes.push(child.getAttribute("id")); parseNode(child); break; case "instance_camera": data.instanceCameras.push(parseId(child.getAttribute("url"))); break; case "instance_controller": data.instanceControllers.push(parseNodeInstance(child)); break; case "instance_light": data.instanceLights.push(parseId(child.getAttribute("url"))); break; case "instance_geometry": data.instanceGeometries.push(parseNodeInstance(child)); break; case "instance_node": data.instanceNodes.push(parseId(child.getAttribute("url"))); break; case "matrix": array = parseFloats(child.textContent); data.matrix.multiply(matrix.fromArray(array).transpose()); data.transforms[child.getAttribute("sid")] = child.nodeName; break; case "translate": array = parseFloats(child.textContent); vector.fromArray(array); data.matrix.multiply(matrix.makeTranslation(vector.x, vector.y, vector.z)); data.transforms[child.getAttribute("sid")] = child.nodeName; break; case "rotate": array = parseFloats(child.textContent); const angle = MathUtils.degToRad(array[3]); data.matrix.multiply(matrix.makeRotationAxis(vector.fromArray(array), angle)); data.transforms[child.getAttribute("sid")] = child.nodeName; break; case "scale": array = parseFloats(child.textContent); data.matrix.scale(vector.fromArray(array)); data.transforms[child.getAttribute("sid")] = child.nodeName; break; case "extra": break; default: console.log(child); } } if (hasNode(data.id)) console.warn("THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.", data.id); else library.nodes[data.id] = data; return data; } function parseNodeInstance(xml2) { const data = { id: parseId(xml2.getAttribute("url")), materials: {}, skeletons: [] }; for (let i = 0; i < xml2.childNodes.length; i++) { const child = xml2.childNodes[i]; switch (child.nodeName) { case "bind_material": const instances = child.getElementsByTagName("instance_material"); for (let j = 0; j < instances.length; j++) { const instance = instances[j]; const symbol = instance.getAttribute("symbol"); const target = instance.getAttribute("target"); data.materials[symbol] = parseId(target); } break; case "skeleton": data.skeletons.push(parseId(child.textContent)); break; } } return data; } function buildSkeleton(skeletons, joints) { const boneData = []; const sortedBoneData = []; let i, j, data; for (i = 0; i < skeletons.length; i++) { const skeleton = skeletons[i]; let root; if (hasNode(skeleton)) { root = getNode(skeleton); buildBoneHierarchy(root, joints, boneData); } else if (hasVisualScene(skeleton)) { const children = library.visualScenes[skeleton].children; for (let j2 = 0; j2 < children.length; j2++) { const child = children[j2]; if (child.type === "JOINT") buildBoneHierarchy(getNode(child.id), joints, boneData); } } else console.error("THREE.ColladaLoader: Unable to find root bone of skeleton with ID:", skeleton); } for (i = 0; i < joints.length; i++) for (j = 0; j < boneData.length; j++) { data = boneData[j]; if (data.bone.name === joints[i].name) { sortedBoneData[i] = data; data.processed = true; break; } } for (i = 0; i < boneData.length; i++) { data = boneData[i]; if (data.processed === false) { sortedBoneData.push(data); data.processed = true; } } const bones = []; const boneInverses = []; for (i = 0; i < sortedBoneData.length; i++) { data = sortedBoneData[i]; bones.push(data.bone); boneInverses.push(data.boneInverse); } return new Skeleton(bones, boneInverses); } function buildBoneHierarchy(root, joints, boneData) { root.traverse(function(object) { if (object.isBone === true) { let boneInverse; for (let i = 0; i < joints.length; i++) { const joint = joints[i]; if (joint.name === object.name) { boneInverse = joint.boneInverse; break; } } if (boneInverse === void 0) boneInverse = new Matrix4(); boneData.push({ bone: object, boneInverse, processed: false }); } }); } function buildNode(data) { const objects = []; const matrix2 = data.matrix; const nodes = data.nodes; const type = data.type; const instanceCameras = data.instanceCameras; const instanceControllers = data.instanceControllers; const instanceLights = data.instanceLights; const instanceGeometries = data.instanceGeometries; const instanceNodes = data.instanceNodes; for (let i = 0, l = nodes.length; i < l; i++) objects.push(getNode(nodes[i])); for (let i = 0, l = instanceCameras.length; i < l; i++) { const instanceCamera = getCamera(instanceCameras[i]); if (instanceCamera !== null) objects.push(instanceCamera.clone()); } for (let i = 0, l = instanceControllers.length; i < l; i++) { const instance = instanceControllers[i]; const controller = getController(instance.id); const newObjects = buildObjects(getGeometry(controller.id), instance.materials); const skeletons = instance.skeletons; const joints = controller.skin.joints; const skeleton = buildSkeleton(skeletons, joints); for (let j = 0, jl = newObjects.length; j < jl; j++) { const object2 = newObjects[j]; if (object2.isSkinnedMesh) { object2.bind(skeleton, controller.skin.bindMatrix); object2.normalizeSkinWeights(); } objects.push(object2); } } for (let i = 0, l = instanceLights.length; i < l; i++) { const instanceLight = getLight(instanceLights[i]); if (instanceLight !== null) objects.push(instanceLight.clone()); } for (let i = 0, l = instanceGeometries.length; i < l; i++) { const instance = instanceGeometries[i]; const newObjects = buildObjects(getGeometry(instance.id), instance.materials); for (let j = 0, jl = newObjects.length; j < jl; j++) objects.push(newObjects[j]); } for (let i = 0, l = instanceNodes.length; i < l; i++) objects.push(getNode(instanceNodes[i]).clone()); let object; if (nodes.length === 0 && objects.length === 1) object = objects[0]; else { object = type === "JOINT" ? new Bone() : new Group(); for (let i = 0; i < objects.length; i++) object.add(objects[i]); } object.name = type === "JOINT" ? data.sid : data.name; object.matrix.copy(matrix2); object.matrix.decompose(object.position, object.quaternion, object.scale); return object; } const fallbackMaterial = new MeshBasicMaterial({ color: 16711935 }); function resolveMaterialBinding(keys, instanceMaterials) { const materials = []; for (let i = 0, l = keys.length; i < l; i++) { const id = instanceMaterials[keys[i]]; if (id === void 0) { console.warn("THREE.ColladaLoader: Material with key %s not found. Apply fallback material.", keys[i]); materials.push(fallbackMaterial); } else materials.push(getMaterial(id)); } return materials; } function buildObjects(geometries, instanceMaterials) { const objects = []; for (const type in geometries) { const geometry = geometries[type]; const materials = resolveMaterialBinding(geometry.materialKeys, instanceMaterials); if (materials.length === 0) if (type === "lines" || type === "linestrips") materials.push(new LineBasicMaterial()); else materials.push(new MeshPhongMaterial()); const skinning = geometry.data.attributes.skinIndex !== void 0; const material = materials.length === 1 ? materials[0] : materials; let object; switch (type) { case "lines": object = new LineSegments(geometry.data, material); break; case "linestrips": object = new Line(geometry.data, material); break; case "triangles": case "polylist": if (skinning) object = new SkinnedMesh(geometry.data, material); else object = new Mesh(geometry.data, material); break; } objects.push(object); } return objects; } function hasNode(id) { return library.nodes[id] !== void 0; } function getNode(id) { return getBuild(library.nodes[id], buildNode); } function parseVisualScene(xml2) { const data = { name: xml2.getAttribute("name"), children: [] }; prepareNodes(xml2); const elements = getElementsByTagName(xml2, "node"); for (let i = 0; i < elements.length; i++) data.children.push(parseNode(elements[i])); library.visualScenes[xml2.getAttribute("id")] = data; } function buildVisualScene(data) { const group = new Group(); group.name = data.name; const children = data.children; for (let i = 0; i < children.length; i++) { const child = children[i]; group.add(getNode(child.id)); } return group; } function hasVisualScene(id) { return library.visualScenes[id] !== void 0; } function getVisualScene(id) { return getBuild(library.visualScenes[id], buildVisualScene); } function parseScene(xml2) { const instance = getElementsByTagName(xml2, "instance_visual_scene")[0]; return getVisualScene(parseId(instance.getAttribute("url"))); } function setupAnimations() { const clips = library.clips; if (isEmpty(clips) === true) { if (isEmpty(library.animations) === false) { const tracks = []; for (const id in library.animations) { const animationTracks = getAnimation(id); for (let i = 0, l = animationTracks.length; i < l; i++) tracks.push(animationTracks[i]); } animations.push(new AnimationClip("default", -1, tracks)); } } else for (const id in clips) animations.push(getAnimationClip(id)); } function parserErrorToText(parserError2) { let result = ""; const stack = [parserError2]; while (stack.length) { const node = stack.shift(); if (node.nodeType === Node.TEXT_NODE) result += node.textContent; else { result += "\n"; stack.push.apply(stack, node.childNodes); } } return result.trim(); } if (text.length === 0) return { scene: new Scene() }; const xml = new DOMParser().parseFromString(text, "application/xml"); const collada = getElementsByTagName(xml, "COLLADA")[0]; const parserError = xml.getElementsByTagName("parsererror")[0]; if (parserError !== void 0) { const errorElement = getElementsByTagName(parserError, "div")[0]; let errorText; if (errorElement) errorText = errorElement.textContent; else errorText = parserErrorToText(parserError); console.error("THREE.ColladaLoader: Failed to parse collada file.\n", errorText); return null; } const version = collada.getAttribute("version"); console.log("THREE.ColladaLoader: File version", version); const asset = parseAsset(getElementsByTagName(collada, "asset")[0]); const textureLoader = new TextureLoader(this.manager); textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin); let tgaLoader; if (TGALoader) { tgaLoader = new TGALoader(this.manager); tgaLoader.setPath(this.resourcePath || path); } const animations = []; let kinematics = {}; let count = 0; const library = { animations: {}, clips: {}, controllers: {}, images: {}, effects: {}, materials: {}, cameras: {}, lights: {}, geometries: {}, nodes: {}, visualScenes: {}, kinematicsModels: {}, physicsModels: {}, kinematicsScenes: {} }; parseLibrary(collada, "library_animations", "animation", parseAnimation); parseLibrary(collada, "library_animation_clips", "animation_clip", parseAnimationClip); parseLibrary(collada, "library_controllers", "controller", parseController); parseLibrary(collada, "library_images", "image", parseImage); parseLibrary(collada, "library_effects", "effect", parseEffect); parseLibrary(collada, "library_materials", "material", parseMaterial); parseLibrary(collada, "library_cameras", "camera", parseCamera); parseLibrary(collada, "library_lights", "light", parseLight); parseLibrary(collada, "library_geometries", "geometry", parseGeometry); parseLibrary(collada, "library_nodes", "node", parseNode); parseLibrary(collada, "library_visual_scenes", "visual_scene", parseVisualScene); parseLibrary(collada, "library_kinematics_models", "kinematics_model", parseKinematicsModel); parseLibrary(collada, "library_physics_models", "physics_model", parsePhysicsModel); parseLibrary(collada, "scene", "instance_kinematics_scene", parseKinematicsScene); buildLibrary(library.animations, buildAnimation); buildLibrary(library.clips, buildAnimationClip); buildLibrary(library.controllers, buildController); buildLibrary(library.images, buildImage); buildLibrary(library.effects, buildEffect); buildLibrary(library.materials, buildMaterial); buildLibrary(library.cameras, buildCamera); buildLibrary(library.lights, buildLight); buildLibrary(library.geometries, buildGeometry); buildLibrary(library.visualScenes, buildVisualScene); setupAnimations(); setupKinematics(); const scene = parseScene(getElementsByTagName(collada, "scene")[0]); scene.animations = animations; if (asset.upAxis === "Z_UP") scene.quaternion.setFromEuler(new Euler(-Math.PI / 2, 0, 0)); scene.scale.multiplyScalar(asset.unit); return { get animations() { console.warn("THREE.ColladaLoader: Please access animations over scene.animations now."); return animations; }, kinematics, library, scene }; } }; //#endregion //#region node_modules/three-stdlib/loaders/KMZLoader.js var KMZLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(data) { function findFile(url) { for (const path in zip) if (path.substr(-url.length) === url) return zip[path]; } const manager = new LoadingManager(); manager.setURLModifier(function(url) { const image = findFile(url); if (image) { console.log("Loading", url); const blob = new Blob([image.buffer], { type: "application/octet-stream" }); return URL.createObjectURL(blob); } return url; }); const zip = unzipSync(new Uint8Array(data)); if (zip["doc.kml"]) { const model = new DOMParser().parseFromString(fflate.strFromU8(zip["doc.kml"]), "application/xml").querySelector("Placemark Model Link href"); if (model) return new ColladaLoader(manager).parse(fflate.strFromU8(zip[model.textContent])); } else { console.warn("KMZLoader: Missing doc.kml file."); for (const path in zip) if (path.split(".").pop().toLowerCase() === "dae") return new ColladaLoader(manager).parse(fflate.strFromU8(zip[path])); } console.error("KMZLoader: Couldn't find .dae file."); return { scene: new Group() }; } }; //#endregion //#region node_modules/three-stdlib/loaders/VRMLoader.js var VRMLoader = class extends Loader { constructor(manager) { super(manager); this.gltfLoader = new GLTFLoader(manager); } load(url, onLoad, onProgress, onError) { const scope = this; this.gltfLoader.load(url, function(gltf) { try { scope.parse(gltf, onLoad); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } setDRACOLoader(dracoLoader) { this.gltfLoader.setDRACOLoader(dracoLoader); return this; } parse(gltf, onLoad) { onLoad(gltf); } }; //#endregion //#region node_modules/three-stdlib/libs/chevrotain.js var { CstParser, Lexer, createToken } = /* @__PURE__ */ (() => { const freeGlobal$1 = typeof global == "object" && global && global.Object === Object && global; var freeSelf = typeof self == "object" && self && self.Object === Object && self; const root$1 = freeGlobal$1 || freeSelf || Function("return this")(); const Symbol$2 = root$1.Symbol; 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 (e) {} var result = nativeObjectToString$1.call(value); if (unmasked) if (isOwn) value[symToStringTag$1] = tag; else delete value[symToStringTag$1]; return result; } var nativeObjectToString = Object.prototype.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 index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) result[index] = iteratee(array[index], index, array); return result; } const isArray$1 = Array.isArray; var INFINITY$3 = Infinity; 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 index = string.length; while (index-- && reWhitespace.test(string.charAt(index))); return index; } 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 = NaN; 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 = Infinity, MAX_INTEGER = 17976931348623157e292; function toFinite(value) { if (!value) return value === 0 ? value : 0; value = toNumber(value); if (value === INFINITY$2 || value === -INFINITY$2) return (value < 0 ? -1 : 1) * 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 identity(value) { return value; } var asyncTag = "[object AsyncFunction]", funcTag$2 = "[object Function]", genTag$1 = "[object GeneratorFunction]", proxyTag = "[object Proxy]"; function isFunction(value) { if (!isObject(value)) return false; var tag = baseGetTag(value); return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag; } const coreJsData$1 = root$1["__core-js_shared__"]; 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 funcToString$1 = Function.prototype.toString; function toSource(func) { if (func != null) { try { return funcToString$1.call(func); } catch (e) {} try { return func + ""; } catch (e) {} } 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; return (isFunction(value) ? reIsNative : reIsHostCtor).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; } const WeakMap$1 = getNative(root$1, "WeakMap"); var objectCreate = Object.create; const baseCreate$1 = 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; }; }(); 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 noop() {} function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) array[index] = source[index]; 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; }; } const defineProperty$1 = function() { try { var func = getNative(Object, "defineProperty"); func({}, "", {}); return func; } catch (e) {} }(); const setToString$1 = shortOut(!defineProperty$1 ? identity : function(func, string) { return defineProperty$1(func, "toString", { configurable: true, enumerable: false, value: constant(string), writable: true }); }); function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) if (iteratee(array[index], index, array) === false) break; return array; } function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while (fromRight ? index-- : ++index < length) if (predicate(array[index], index, array)) return index; return -1; } function baseIsNaN(value) { return value !== value; } function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) if (array[index] === value) return index; return -1; } function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } function arrayIncludes(array, value) { return !!(array == null ? 0 : array.length) && baseIndexOf(array, value, 0) > -1; } var MAX_SAFE_INTEGER$1 = 9007199254740991; var reIsUint = /^(?:0|[1-9]\d*)$/; function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER$1 : length; return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length; } 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 hasOwnProperty$e = Object.prototype.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 index = -1, length = props.length; while (++index < length) { var key = props[index]; 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, index = -1, length = nativeMax$3(args.length - start, 0), array = Array(length); while (++index < length) array[index] = args[start + index]; index = -1; var otherArgs = Array(start + 1); while (++index < start) otherArgs[index] = args[index]; otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } function baseRest(func, start) { return setToString$1(overRest(func, start, identity), 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) && !isFunction(value); } function isIterateeCall(value, index, object) { if (!isObject(object)) return false; var type = typeof index; if (type == "number" ? isArrayLike(object) && isIndex(index, object.length) : type == "string" && index in object) return eq(object[index], value); return false; } function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : void 0, guard = length > 2 ? sources[2] : void 0; customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : void 0; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? void 0 : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) assigner(object, source, index, customizer); } return object; }); } var objectProto$f = Object.prototype; function isPrototype(value) { var Ctor = value && value.constructor; return value === (typeof Ctor == "function" && Ctor.prototype || objectProto$f); } function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) result[index] = iteratee(index); 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; const isArguments$1 = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty$d.call(value, "callee") && !propertyIsEnumerable$1.call(value, "callee"); }; 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 Buffer$1 = freeModule$2 && freeModule$2.exports === freeExports$2 ? root$1.Buffer : void 0; const isBuffer$1 = (Buffer$1 ? Buffer$1.isBuffer : void 0) || stubFalse; 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 freeProcess = freeModule$1 && freeModule$1.exports === freeExports$1 && freeGlobal$1.process; const nodeUtil$1 = function() { try { var types = freeModule$1 && freeModule$1.require && freeModule$1.require("util").types; if (types) return types; return freeProcess && freeProcess.binding && freeProcess.binding("util"); } catch (e) {} }(); var nodeIsTypedArray = nodeUtil$1 && nodeUtil$1.isTypedArray; const isTypedArray$1 = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; var hasOwnProperty$c = Object.prototype.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) : [], length = result.length; for (var key in value) if ((inherited || hasOwnProperty$c.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex(key, length)))) result.push(key); return result; } function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } const nativeKeys$1 = overArg(Object.keys, Object); var hasOwnProperty$b = Object.prototype.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 hasOwnProperty$a = Object.prototype.hasOwnProperty; const assign$1 = 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]); }); function nativeKeysIn(object) { var result = []; if (object != null) for (var key in Object(object)) result.push(key); return result; } var hasOwnProperty$9 = Object.prototype.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); } const nativeCreate$1 = getNative(Object, "create"); 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 hasOwnProperty$8 = Object.prototype.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 hasOwnProperty$7 = Object.prototype.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 index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; 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 length = array.length; while (length--) if (eq(array[length][0], key)) return length; return -1; } var splice = Array.prototype.splice; function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) return false; if (index == data.length - 1) data.pop(); else splice.call(data, index, 1); --this.size; return true; } function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? void 0 : data[index][1]; } function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else data[index][1] = value; return this; } function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; 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; const Map$2 = getNative(root$1, "Map"); 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(map2, key) { var data = map2.__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), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; 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; const stringToPath$1 = 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; }); 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 = Infinity; 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 index = 0, length = path.length; while (object != null && index < length) object = object[toKey(path[index++])]; return index && index == length ? 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 index = -1, length = values2.length, offset = array.length; while (++index < length) array[offset + index] = values2[index]; 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 index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; 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) { return (array == null ? 0 : array.length) ? baseFlatten(array, 1) : []; } const getPrototype$1 = overArg(Object.getPrototypeOf, Object); function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) start = -start > length ? 0 : length + start; end = end > length ? length : end; if (end < 0) end += length; length = start > end ? 0 : end - start >>> 0; start >>>= 0; var result = Array(length); while (++index < length) result[index] = array[index + start]; return result; } function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) accumulator = array[++index]; while (++index < length) accumulator = iteratee(accumulator, array[index], index, 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 Buffer = freeModule && freeModule.exports === freeExports ? root$1.Buffer : void 0, allocUnsafe = Buffer ? Buffer.allocUnsafe : void 0; function cloneBuffer(buffer, isDeep) { if (isDeep) return buffer.slice(); var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) result[resIndex++] = value; } return result; } function stubArray() { return []; } var propertyIsEnumerable = Object.prototype.propertyIsEnumerable; var nativeGetSymbols$1 = Object.getOwnPropertySymbols; const getSymbols$1 = !nativeGetSymbols$1 ? stubArray : function(object) { if (object == null) return []; object = Object(object); return arrayFilter(nativeGetSymbols$1(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; function copySymbols(source, object) { return copyObject(source, getSymbols$1(source), object); } const getSymbolsIn$1 = !Object.getOwnPropertySymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols$1(object)); object = getPrototype$1(object); } return result; }; 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); } const DataView$1 = getNative(root$1, "DataView"); const Promise$2 = getNative(root$1, "Promise"); const Set$1 = getNative(root$1, "Set"); 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(/* @__PURE__ */ 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 hasOwnProperty$6 = Object.prototype.hasOwnProperty; function initCloneArray(array) { var length = array.length, result = new array.constructor(length); if (length && typeof array[0] == "string" && hasOwnProperty$6.call(array, "index")) { result.index = array.index; result.input = array.input; } return result; } const Uint8Array$1 = root$1.Uint8Array; 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 buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, 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 buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, 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; const isMap$1 = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; var setTag$3 = "[object Set]"; function baseIsSet(value) { return isObjectLike(value) && getTag$1(value) == setTag$3; } var nodeIsSet = nodeUtil$1 && nodeUtil$1.isSet; const isSet$1 = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; 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(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); else if (isMap$1(value)) value.forEach(function(subValue, key2) { result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); }); var props = isArr ? void 0 : (isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys)(value); arrayEach(props || value, function(subValue, key2) { if (props) { key2 = subValue; subValue = value[key2]; } assignValue(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); }); return result; } var CLONE_SYMBOLS_FLAG = 4; function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; 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 index = -1, length = values2 == null ? 0 : values2.length; this.__data__ = new MapCache(); while (++index < length) this.add(values2[index]); } SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) if (predicate(array[index], index, 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 index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG$3 ? new SetCache() : void 0; stack.set(array, other); stack.set(other, array); while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, 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(map2) { var index = -1, result = Array(map2.size); map2.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = 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 hasOwnProperty$5 = Object.prototype.hasOwnProperty; function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3, objProps = getAllKeys(object), objLength = objProps.length; if (objLength != getAllKeys(other).length && !isPartial) return false; var index = objLength; while (index--) { var key = objProps[index]; 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 (++index < objLength) { key = objProps[index]; 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 hasOwnProperty$4 = Object.prototype.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 index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) return !length; object = Object(object); while (index--) { var data = matchData[index]; if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) return false; } while (++index < length) { data = matchData[index]; 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), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [ 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 index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) break; object = object[key]; } if (result || ++index != length) return result; length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (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 identity; 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 index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) break; } return object; }; } const baseFor$1 = createBaseFor(); 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 length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while (fromRight ? index-- : ++index < length) if (iteratee(iterable[index], index, iterable) === false) break; return collection; }; } const baseEach$1 = createBaseEach(baseForOwn); 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; const defaults$1 = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : void 0; if (guard && isIterateeCall(sources[0], sources[1], guard)) length = 1; while (++index < length) { var source = sources[index]; 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; }); function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) if (comparator(value, array[index])) return true; return false; } var LARGE_ARRAY_SIZE$1 = 200; function baseDifference(array, values2, iteratee, comparator) { var index = -1, includes2 = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values2.length; if (!length) 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 (++index < length) { var value = array[index], 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; } const difference$1 = baseRest(function(array, values2) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true)) : []; }); function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : void 0; } function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) return []; n = guard || n === void 0 ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) return []; n = guard || n === void 0 ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } function castFunction(value) { return typeof value == "function" ? value : identity; } function forEach(collection, iteratee) { return (isArray$1(collection) ? arrayEach : baseEach$1)(collection, castFunction(iteratee)); } function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) if (!predicate(array[index], index, array)) return false; return true; } function baseEvery(collection, predicate) { var result = true; baseEach$1(collection, function(value, index, collection2) { result = !!predicate(value, index, 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, index, collection2) { if (predicate(value, index, collection2)) result.push(value); }); return result; } function filter(collection, predicate) { return (isArray$1(collection) ? arrayFilter : baseFilter)(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 index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : void 0; }; } var nativeMax$2 = Math.max; function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) return -1; var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) index = nativeMax$2(length + index, 0); return baseFindIndex(array, baseIteratee(predicate), index); } const find$1 = createFind(findIndex); function head(array) { return array && array.length ? array[0] : void 0; } function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach$1(collection, function(value, key, collection2) { result[++index] = iteratee(value, key, collection2); }); return result; } function map(collection, iteratee) { return (isArray$1(collection) ? arrayMap : baseMap)(collection, baseIteratee(iteratee)); } function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } var hasOwnProperty$2 = Object.prototype.hasOwnProperty; const groupBy$1 = createAggregator(function(result, value, key) { if (hasOwnProperty$2.call(result, key)) result[key].push(value); else baseAssignValue(result, key, [value]); }); var hasOwnProperty$1 = Object.prototype.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 length = collection.length; if (fromIndex < 0) fromIndex = nativeMax$1(length + fromIndex, 0); return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1; } var nativeMax = Math.max; function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) return -1; var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) index = nativeMax(length + index, 0); return baseIndexOf(array, value, index); } var mapTag = "[object Map]", setTag = "[object Set]"; var hasOwnProperty = Object.prototype.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; const isRegExp$1 = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; 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 index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (key === "__proto__" || key === "constructor" || key === "prototype") return object; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : void 0; if (newValue === void 0) newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; } assignValue(nested, key, newValue); nested = nested[key]; } return object; } function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], 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, index, collection2) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection2); }); return accumulator; } function reduce(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) { return (isArray$1(collection) ? arrayFilter : baseFilter)(collection, negate(baseIteratee(predicate))); } function baseSome(collection, predicate) { var result; baseEach$1(collection, function(value, index, collection2) { result = predicate(value, index, 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)); } const createSet$1 = !(Set$1 && 1 / setToArray(new Set$1([, -0]))[1] == Infinity) ? noop : function(values2) { return new Set$1(values2); }; var LARGE_ARRAY_SIZE = 200; function baseUniq(array, iteratee, comparator) { var index = -1, includes2 = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes2 = arrayIncludesWith; } else if (length >= 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 (++index < length) { var value = array[index], 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 timer(func) { const start = (/* @__PURE__ */ new Date()).getTime(); const val = func(); return { time: (/* @__PURE__ */ new Date()).getTime() - start, 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, (v) => v !== 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, (v) => v !== void 0)); } } class Alternative extends AbstractProduction { constructor(options) { super(options.definition); this.ignoreAmbiguities = false; assign$1(this, pickBy(options, (v) => v !== void 0)); } } class Option extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1(this, pickBy(options, (v) => v !== void 0)); } } class RepetitionMandatory extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1(this, pickBy(options, (v) => v !== void 0)); } } class RepetitionMandatoryWithSeparator extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1(this, pickBy(options, (v) => v !== void 0)); } } class Repetition extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1(this, pickBy(options, (v) => v !== void 0)); } } class RepetitionWithSeparator extends AbstractProduction { constructor(options) { super(options.definition); this.idx = 1; assign$1(this, pickBy(options, (v) => v !== 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, (v) => v !== void 0)); } } class Terminal { constructor(options) { this.idx = 1; assign$1(this, pickBy(options, (v) => v !== void 0)); } accept(visitor) { visitor.visit(this); } } function serializeGrammar(topRules) { return map(topRules, serializeProduction); } function serializeProduction(node) { function convertDefinition(definition) { return map(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 = []) { if (prod instanceof Option || prod instanceof Repetition || prod instanceof RepetitionWithSeparator) 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, index) => { const currRest = drop(prod.definition, index + 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) { return [new Option({ definition: [new Terminal({ terminalType: repSepProd.separator })].concat(repSepProd.definition) })].concat(currRest, prevRest); } function first(prod) { if (prod instanceof NonTerminal) return first(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(first(currSubProd)); nextSubProdIdx = nextSubProdIdx + 1; hasInnerProdsRemaining = seq.length > nextSubProdIdx; } return uniq(firstSet); } function firstForBranching(prod) { return uniq(flatten(map(prod.definition, (innerProd) => { return first(innerProd); }))); } 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 t_in_topProd_follows = first(new Alternative({ definition: currRest.concat(prevRest) })); this.follows[followName] = t_in_topProd_follows; } } function computeAllProdsFollows(topProductions) { const reSyncFollows = {}; forEach(topProductions, (topProd) => { assign$1(reSyncFollows, new ResyncFollowsWalker(topProd).startWalking()); }); 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 i = cc("0"); i <= cc("9"); i++) digitsCharCodes.push(i); const wordCharCodes = [cc("_")].concat(digitsCharCodes); for (let i = cc("a"); i <= cc("z"); i++) wordCharCodes.push(i); for (let i = cc("A"); i <= cc("Z"); i++) wordCharCodes.push(i); const whitespaceCodes = [ cc(" "), cc("\f"), cc("\n"), cc("\r"), cc(" "), cc("\v"), cc(" "), cc("\xA0"), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc(" "), cc("\u2028"), cc("\u2029"), cc(" "), cc(" "), cc(" "), cc("") ]; 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; ASSERT_EXISTS(range); break; } if (isBacktracking === true && range === void 0) return; 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() { return { type: "GroupBackReference", value: this.positiveInteger() }; } 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 "); return { type: "Character", value: letter.toUpperCase().charCodeAt(0) - 64 }; } 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() { return { type: "Character", value: cc(this.popChar()) }; } classPatternCharacterAtom() { switch (this.peekChar()) { case "\n": case "\r": case "\u2028": case "\u2029": case "\\": case "]": throw Error("TBD"); default: return { type: "Character", value: cc(this.popChar()) }; } } 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; if (isCharacter(from) && this.isRangeDash()) { this.consumeChar("-"); const to = this.classAtom(); to.type; 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 (e) { 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 i = 0; i < howMany; i++) { const hexChar = this.popChar(); if (hexDigitPattern.test(hexChar) === false) throw Error("Expecting a HexDecimal digits"); hexString += hexChar; } return { type: "Character", value: parseInt(hexString, 16) }; } 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) {} visitStartAnchor(node) {} visitEndAnchor(node) {} visitWordBoundary(node) {} visitNonWordBoundary(node) {} visitLookahead(node) {} visitNegativeLookahead(node) {} 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); return firstCharOptimizedIndices(ast.value, {}, ast.flags.ignoreCase); } catch (e) { if (e.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 i = 0; i < ast.value.length; i++) firstCharOptimizedIndices(ast.value[i], result, ignoreCase); break; case "Alternative": const terms = ast.value; for (let i = 0; i < terms.length; i++) { const term = terms[i]; 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 (atom.type === "Group" && isWholeOptional(atom) === false || 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 (/* @__PURE__ */ 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 = map(onlyRelevantTypes, (currType) => { const currPattern = currType[PATTERN]; if (isRegExp$1(currPattern)) { const regExpSource = currPattern.source; if (regExpSource.length === 1 && regExpSource !== "^" && regExpSource !== "$" && regExpSource !== "." && !currPattern.ignoreCase) return regExpSource; else if (regExpSource.length === 2 && regExpSource[0] === "\\" && !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 (isFunction(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 = map(onlyRelevantTypes, (currType) => currType.tokenTypeIdx); patternIdxToGroup = map(onlyRelevantTypes, (clazz) => { const groupName = clazz.GROUP; if (groupName === Lexer2.SKIPPED) return; else if (isString(groupName)) return groupName; else if (isUndefined(groupName)) return false; else throw Error("non exhaustive match"); }); patternIdxToLongerAltIdxArr = map(onlyRelevantTypes, (clazz) => { const longerAltType = clazz.LONGER_ALT; if (longerAltType) return isArray$1(longerAltType) ? map(longerAltType, (type) => indexOf(onlyRelevantTypes, type)) : [indexOf(onlyRelevantTypes, longerAltType)]; }); patternIdxToPushMode = map(onlyRelevantTypes, (clazz) => clazz.PUSH_MODE); patternIdxToPopMode = map(onlyRelevantTypes, (clazz) => has(clazz, "POP_MODE")); }); let patternIdxToCanLineTerminator; tracer("Line Terminator Handling", () => { const lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters); patternIdxToCanLineTerminator = map(onlyRelevantTypes, (tokType) => false); if (options.positionTracking !== "onlyOffset") patternIdxToCanLineTerminator = map(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 = map(onlyRelevantTypes, isCustomPattern); patternIdxToShort = map(allTransformedPatterns, isShortPattern); emptyGroups = reduce(onlyRelevantTypes, (acc, clazz) => { const groupName = clazz.GROUP; if (isString(groupName) && !(groupName === Lexer2.SKIPPED)) acc[groupName] = []; return acc; }, {}); patternIdxToConfig = map(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 = reduce(onlyRelevantTypes, (result, currTokType, idx) => { if (typeof currTokType.PATTERN === "string") addToMapOfArrays(result, charCodeToOptimizedIndex(currTokType.PATTERN.charCodeAt(0)), patternIdxToConfig[idx]); else if (isArray$1(currTokType.START_CHARS_HINT)) { let lastOptimizedIdx; forEach(currTokType.START_CHARS_HINT, (charOrInt) => { const currOptimizedIdx = charCodeToOptimizedIndex(typeof charOrInt === "string" ? charOrInt.charCodeAt(0) : charOrInt); 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); }); return { errors: map(tokenTypesWithMissingPattern, (currType) => { return { message: "Token Type: ->" + currType.name + "<- missing static 'PATTERN' property", type: LexerDefinitionErrorType.MISSING_PATTERN, tokenTypes: [currType] }; }), valid: difference$1(tokenTypes, tokenTypesWithMissingPattern) }; } function findInvalidPatterns(tokenTypes) { const tokenTypesWithInvalidPattern = filter(tokenTypes, (currType) => { const pattern = currType[PATTERN]; return !isRegExp$1(pattern) && !isFunction(pattern) && !has(pattern, "exec") && !isString(pattern); }); return { errors: map(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] }; }), valid: difference$1(tokenTypes, tokenTypesWithInvalidPattern) }; } const end_of_input = /[^\\][$]/; function findEndOfInputAnchor(tokenTypes) { class EndAnchorFinder extends BaseRegExpVisitor { constructor() { super(...arguments); this.found = false; } visitEndAnchor(node) { this.found = true; } } return map(filter(tokenTypes, (currType) => { const pattern = currType.PATTERN; try { const regexpAst = getRegExpAst(pattern); const endAnchorVisitor = new EndAnchorFinder(); endAnchorVisitor.visit(regexpAst); return endAnchorVisitor.found; } catch (e) { return end_of_input.test(pattern.source); } }), (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] }; }); } function findEmptyMatchRegExps(tokenTypes) { return map(filter(tokenTypes, (currType) => { return currType.PATTERN.test(""); }), (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' must not match an empty string", type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, tokenTypes: [currType] }; }); } const start_of_input = /[^\\[][\^]|^\^/; function findStartOfInputAnchor(tokenTypes) { class StartAnchorFinder extends BaseRegExpVisitor { constructor() { super(...arguments); this.found = false; } visitStartAnchor(node) { this.found = true; } } return map(filter(tokenTypes, (currType) => { const pattern = currType.PATTERN; try { const regexpAst = getRegExpAst(pattern); const startAnchorVisitor = new StartAnchorFinder(); startAnchorVisitor.visit(regexpAst); return startAnchorVisitor.found; } catch (e) { return start_of_input.test(pattern.source); } }), (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] }; }); } function findUnsupportedFlags(tokenTypes) { return map(filter(tokenTypes, (currType) => { const pattern = currType[PATTERN]; return pattern instanceof RegExp && (pattern.multiline || pattern.global); }), (currType) => { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", type: LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, tokenTypes: [currType] }; }); } function findDuplicatePatterns(tokenTypes) { const found = []; let identicalPatterns = map(tokenTypes, (outerType) => { return reduce(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); return map(filter(identicalPatterns, (currIdenticalSet) => { return currIdenticalSet.length > 1; }), (setOfIdentical) => { const tokenTypeNames = map(setOfIdentical, (currType) => { return currType.name; }); return { message: `The same RegExp pattern ->${head(setOfIdentical).PATTERN}<-has been used in all of the following Token Types: ${tokenTypeNames.join(", ")} <-`, type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, tokenTypes: setOfIdentical }; }); } function findInvalidGroupType(tokenTypes) { return map(filter(tokenTypes, (clazz) => { if (!has(clazz, "GROUP")) return false; const group = clazz.GROUP; return group !== Lexer2.SKIPPED && group !== Lexer2.NA && !isString(group); }), (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] }; }); } function findModesThatDoNotExist(tokenTypes, validModes) { return map(filter(tokenTypes, (clazz) => { return clazz.PUSH_MODE !== void 0 && !includes(validModes, clazz.PUSH_MODE); }), (tokType) => { return { message: `Token Type: ->${tokType.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${tokType.PUSH_MODE}<-which does not exist`, type: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, tokenTypes: [tokType] }; }); } function findUnreachablePatterns(tokenTypes) { const errors = []; const canBeTested = reduce(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 (isFunction(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) { return find$1([ ".", "\\", "[", "]", "|", "^", "$", "(", ")", "?", "*", "+", "{" ], (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 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 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")) forEach(isArray$1(currTokType.LONGER_ALT) ? currTokType.LONGER_ALT : [currTokType.LONGER_ALT], (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 concreteTokenTypes = reject(compact(flatten(values(lexerDefinition.modes))), (currType) => currType[PATTERN] === Lexer2.NA); const terminatorCharCodes = getCharCodes(lineTerminatorCharacters); if (trackLines) forEach(concreteTokenTypes, (tokType) => { const currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes); if (currIssue !== false) { const warningDescriptor = { message: buildLineBreakIssueMessage(tokType, currIssue), 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 = {}; forEach(keys(emptyGroups), (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 (isFunction(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 = { test: function(text) { const len = text.length; for (let i = this.lastIndex; i < len; i++) { const c = text.charCodeAt(i); if (c === 10) { this.lastIndex = i + 1; return true; } else if (c === 13) { if (text.charCodeAt(i + 1) === 10) this.lastIndex = i + 2; else this.lastIndex = i + 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 (e) { return { issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR, errMsg: e.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) { return map(charsOrCodes, (numOrString) => { if (isString(numOrString)) return numOrString.charCodeAt(0); else return numOrString; }); } function addToMapOfArrays(map2, key, value) { if (map2[key] === void 0) map2[key] = [value]; else map2[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 i = 0; i < 65536; i++) charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i; } } 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 = clone(tokenTypes); let categories = tokenTypes; let searching = true; while (searching) { categories = compact(flatten(map(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, length, line, column) { return `unexpected character: ->${fullText.charAt(startOffset)}<- at offset: ${startOffset}, skipped ${length} 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 } = timer(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: clone(lexerDefinition) }, defaultMode: DEFAULT_MODE }; else { hasOnlySingleMode = false; actualDefinition = clone(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 allErrMessagesString = map(this.lexerDefinitionErrors, (error) => { return error.message; }).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 = identity; this.match = this.matchWithTest; } else { this.updateLastIndex = noop; this.match = this.matchWithExec; } if (hasOnlySingleMode) this.handleModes = noop; if (this.trackStartLines === false) this.computeNewColumn = identity; if (this.trackEndLines === false) this.updateTokenEndLineColumnLocation = noop; 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 = reduce(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 allErrMessagesString = map(this.lexerDefinitionErrors, (error) => { return error.message; }).join("-----------------------\n"); throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" + allErrMessagesString); } return this.tokenizeInternal(text, initialMode); } tokenizeInternal(text, initialMode) { let i, 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 && 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 (i = 0; i < chosenPatternsLength; i++) { currConfig = chosenPatternIdxToConfig[i]; 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, length) { return text.substring(length); } updateLastIndex(regExp, newLastIndex) { regExp.lastIndex = newLastIndex; } 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, index, tokenToAdd) { tokenVector.push(tokenToAdd); return index; } addTokenUsingMemberAccess(tokenVector, index, tokenToAdd) { tokenVector[index] = tokenToAdd; index++; return index; } handlePayloadNoCustom(token, payload) {} handlePayloadWithCustom(token, payload) { if (payload !== null) token.payload = payload; } matchWithTest(pattern, text, offset) { if (pattern.test(text) === 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 }) { return `Expecting ${hasTokenLabel(expected) ? `--> ${tokenLabel(expected)} <--` : `token of type --> ${expected.name} <--`} but found --> '${actual.image}' <--`; }, buildNotAllInputParsedMessage({ firstRedundant, ruleName }) { return "Redundant input, expecting EOF but found: " + firstRedundant.image; }, buildNoViableAltMessage({ expectedPathsPerAlt, actual, previous, customUserDescription, ruleName }) { const errPrefix = "Expecting: "; const errSuffix = "\nbut found: '" + head(actual).image + "'"; if (customUserDescription) return errPrefix + customUserDescription + errSuffix; else return `Expecting: one of these possible Token sequences: ${map(map(reduce(expectedPathsPerAlt, (result, currAltPaths) => result.concat(currAltPaths), []), (currPath) => `[${map(currPath, (currTokenType) => tokenLabel(currTokenType)).join(", ")}]`), (itemMsg, idx) => ` ${idx + 1}. ${itemMsg}`).join("\n")}` + errSuffix; }, buildEarlyExitMessage({ expectedIterationPaths, actual, customUserDescription, ruleName }) { const errPrefix = "Expecting: "; const errSuffix = "\nbut found: '" + head(actual).image + "'"; if (customUserDescription) return errPrefix + customUserDescription + errSuffix; else return `Expecting: expecting at least one iteration which starts with one of these possible Token sequences:: <${map(expectedIterationPaths, (currPath) => `[${map(currPath, (currTokenType) => tokenLabel(currTokenType)).join(",")}]`).join(" ,")}>` + errSuffix; } }; Object.freeze(defaultParserErrorProvider); const defaultGrammarResolverErrorProvider = { buildRuleNotFoundError(topLevelRule, undefinedRule) { return "Invalid grammar, reference to a rule which is not defined: ->" + undefinedRule.nonTerminalName + "<-\ninside top level rule: ->" + topLevelRule.name + "<-"; } }; 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 index = duplicateProd.idx; const dslName = getProductionDslName(duplicateProd); const extraArgument = getExtraProductionArgument2(duplicateProd); let msg = `->${dslName}${index > 0 ? index : ""}<- ${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) { return `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.`; }, buildAlternationPrefixAmbiguityError(options) { const pathMsg = map(options.prefixPath, (currTok) => tokenLabel(currTok)).join(", "); const occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; return `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.`; }, buildAlternationAmbiguityError(options) { const pathMsg = map(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; return `The repetition <${dslName}> within Rule <${options.topLevelRule.name}> can never consume any tokens. This could lead to an infinite loop.`; }, buildTokenNameError(options) { return "deprecated"; }, buildEmptyAlternationError(options) { return `Ambiguous empty alternative: <${options.emptyChoiceIdx + 1}> in inside <${options.topLevelRule.name}> Rule. Only the last alternative may be an empty alternative.`; }, buildTooManyAlternativesError(options) { return `An Alternation cannot have more than 256 alternatives: inside <${options.topLevelRule.name}> Rule. has ${options.alternation.definition.length + 1} alternatives.`; }, buildLeftRecursionError(options) { const ruleName = options.topLevelRule.name; return `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: ${`${ruleName} --> ${map(options.leftRecursionPath, (currRule) => currRule.name).concat([ruleName]).join(" --> ")}`} To fix this refactor your grammar to remove the left recursion. see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`; }, buildInvalidRuleNameError(options) { return "deprecated"; }, buildDuplicateRuleNameError(options) { let ruleName; if (options.topLevelRule instanceof Rule) ruleName = options.topLevelRule.name; else ruleName = options.topLevelRule; return `Duplicate definition, rule: ->${ruleName}<- is already defined in the grammar: ->${options.grammarName}<-`; } }; 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 = clone(this.path.ruleStack).reverse(); this.occurrenceStack = clone(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 restProd = new Alternative({ definition: currRest.concat(prevRest) }); this.possibleTokTypes = first(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 = clone(currPath); let result = []; let i = 0; function remainingPathWith(nextDef) { return nextDef.concat(drop(targetDef, i + 1)); } function getAlternativesForProd(definition) { const alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath); return result.concat(alternatives); } while (currPath.length < maxLength && i < targetDef.length) { const prod = targetDef[i]; 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) return getAlternativesForProd(prod.definition.concat([new Repetition({ definition: prod.definition })])); else if (prod instanceof RepetitionMandatoryWithSeparator) return getAlternativesForProd([new Alternative({ definition: prod.definition }), new Repetition({ definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition) })]); else if (prod instanceof RepetitionWithSeparator) result = getAlternativesForProd(prod.definition.concat([new Repetition({ definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition) })])); else if (prod instanceof Repetition) result = getAlternativesForProd(prod.definition.concat([new Repetition({ definition: prod.definition })])); 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"); i++; } result.push({ partialPath: currPath, suffixDef: drop(targetDef, i) }); 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 = clone(currRuleStack); newRuleStack.push(prod.nonTerminalName); const newOccurrenceStack = clone(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 nextPath = { idx: currIdx, def: prod.definition.concat([secondIteration], drop(currDef)), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPath); } else if (prod instanceof RepetitionMandatoryWithSeparator) { const secondIteration = new Repetition({ definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition), idx: prod.idx }); const nextPath = { idx: currIdx, def: prod.definition.concat([secondIteration], drop(currDef)), 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 nthRepetition = new Repetition({ definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition), idx: prod.idx }); const nextPathWith = { idx: currIdx, def: prod.definition.concat([nthRepetition], drop(currDef)), 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 nextPathWith = { idx: currIdx, def: prod.definition.concat([nthRepetition], drop(currDef)), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWith); } else if (prod instanceof Alternation) for (let i = prod.definition.length - 1; i >= 0; i--) { const currAltPath = { idx: currIdx, def: prod.definition[i].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 = clone(currRuleStack); newRuleStack.push(topRule.name); const newCurrOccurrenceStack = clone(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); return laFuncBuilder(lookAheadPaths, hasPredicates, areTokenCategoriesNotUsed(lookAheadPaths) ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher, 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 = map(orAlts, (currAlt) => currAlt.GATE); for (let t = 0; t < numOfAlts; t++) { const currAlt = alts[t]; const currNumOfPaths = currAlt.length; const currPredicate = predicates[t]; 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 i = 0; i < currPathLength; i++) if (tokenMatcher2(this.LA(i + 1), currPath[i]) === false) continue nextPath; return t; } } }; else if (areAllOneTokenLookahead && !dynamicTokensEnabled) { const choiceToAlt = reduce(map(alts, (currAlt) => { return flatten(currAlt); }), (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() { return choiceToAlt[this.LA(1).tokenTypeIdx]; }; } else return function() { for (let t = 0; t < numOfAlts; t++) { const currAlt = alts[t]; const currNumOfPaths = currAlt.length; nextPath: for (let j = 0; j < currNumOfPaths; j++) { const currPath = currAlt[j]; const currPathLength = currPath.length; for (let i = 0; i < currPathLength; i++) if (tokenMatcher2(this.LA(i + 1), currPath[i]) === false) continue nextPath; return t; } } }; } 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 expectedTokenUniqueKey = singleTokensTypes[0].tokenTypeIdx; return function() { return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey; }; } else { const choiceToAlt = reduce(singleTokensTypes, (result, currTokType, idx) => { result[currTokType.tokenTypeIdx] = true; forEach(currTokType.categoryMatches, (currExtendingType) => { result[currExtendingType] = true; }); return result; }, []); return function() { return choiceToAlt[this.LA(1).tokenTypeIdx] === true; }; } } else return function() { nextPath: for (let j = 0; j < numOfPaths; j++) { const currPath = alt[j]; const currPathLength = currPath.length; for (let i = 0; i < currPathLength; i++) if (tokenMatcher2(this.LA(i + 1), currPath[i]) === 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(size) { const result = new Array(size); for (let i = 0; i < size; i++) result[i] = []; return result; } function pathToHashKeys(path) { let keys2 = [""]; for (let i = 0; i < path.length; i++) { const tokType = path[i]; const longerKeys = []; for (let j = 0; j < keys2.length; j++) { const currShorterKey = keys2[j]; longerKeys.push(currShorterKey + "_" + tokType.tokenTypeIdx); for (let t = 0; t < tokType.categoryMatches.length; t++) { const categoriesKeySuffix = "_" + tokType.categoryMatches[t]; 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++) if (otherAltKnownPathsKeys[searchPathKeys[searchIdx]] === true) return false; } return true; } function lookAheadSequenceFromAlternatives(altsDefs, k) { const partialAlts = map(altsDefs, (currAlt) => possiblePathsFrom([currAlt], 1)); const finalResult = initializeArrayOfArrays(partialAlts.length); const altsHashes = map(partialAlts, (currAltPaths) => { const dict = {}; forEach(currAltPaths, (item) => { forEach(pathToHashKeys(item.partialPath), (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); if (isUniquePrefixHash(altsHashes, prefixKeys, altIdx) || 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) => { forEach(pathToHashKeys(item.partialPath), (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 afterDef = new RestDefinitionFinderWalker(ruleGrammar, occurrence, prodType).startWalking(); return lookAheadSequenceFromAlternatives([new Alternative({ definition: insideDef }), new Alternative({ definition: afterDef })], k); } function containsPath(alternative, searchPath) { compareOtherPath: for (let i = 0; i < alternative.length; i++) { const otherPath = alternative[i]; if (otherPath.length !== searchPath.length) continue; for (let j = 0; j < otherPath.length; j++) { const searchTok = searchPath[j]; const otherTok = otherPath[j]; if ((searchTok === otherTok || otherTok.categoryMatchesMap[searchTok.tokenTypeIdx] !== void 0) === 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) { return map(options.lookaheadStrategy.validate({ rules: options.rules, tokenTypes: options.tokenTypes, grammarName: options.grammarName }), (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; return map(values(pickBy(groupBy$1(allRuleProductions, identifyProductionForDuplicates), (currGroup) => { return currGroup.length > 1; })), (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; }); } 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 = []; if (reduce(allRules, (result, curRule) => { if (curRule.name === rule.name) return result + 1; return result; }, 0) > 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; if (includes(nextNonTerminals, topRule)) errors.push({ message: errMsgProvider.buildLeftRecursionError({ topLevelRule: topRule, leftRecursionPath: path }), type: ParserDefinitionErrorType.LEFT_RECURSION, ruleName }); const errorsFromNextSteps = flatMap(difference$1(nextNonTerminals, path.concat([topRule])), (currRefRule) => { const newPath = clone(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(map(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; return flatMap(ors, (currOr) => { return flatMap(dropRight(currOr.definition), (currAlternative, currAltIdx) => { if (isEmpty(nextPossibleTokensAfter([currAlternative], [], tokenStructuredMatcher, 1))) 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 []; }); }); } function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, errMsgProvider) { const orCollector = new OrCollector(); topLevelRule.accept(orCollector); let ors = orCollector.alternations; ors = reject(ors, (currOr) => currOr.ignoreAmbiguities === true); return flatMap(ors, (currOr) => { const currOccurrence = currOr.idx; const alternatives = getLookaheadPathsForOr(currOccurrence, topLevelRule, currOr.maxLookahead || globalMaxLookahead, currOr); const altsAmbiguityErrors = checkAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); const altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors); }); } 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; return 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 []; }); } 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 pathsInsideProduction = getLookaheadPathsForOptionalProd(currOccurrence, currTopRule, prodType, actualMaxLookahead)[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 = []; return map(reduce(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) && 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; }, []), (currAmbDescriptor) => { const ambgIndices = map(currAmbDescriptor.alts, (currAltIdx) => currAltIdx + 1); return { message: errMsgProvider.buildAlternationAmbiguityError({ topLevelRule: rule, alternation, ambiguityIndices: ambgIndices, prefixPath: currAmbDescriptor.path }), type: ParserDefinitionErrorType.AMBIGUOUS_ALTS, ruleName: rule.name, occurrence: alternation.idx, alternatives: currAmbDescriptor.alts }; }); } function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { const pathsAndIndices = reduce(alternatives, (result, currAlt, idx) => { const currPathsAndIdx = map(currAlt, (currPath) => { return { idx, path: currPath }; }); return result.concat(currPathsAndIdx); }, []); return compact(flatMap(pathsAndIndices, (currPathAndIdx) => { if (alternation.definition[currPathAndIdx.idx].ignoreAmbiguities === true) return []; const targetIdx = currPathAndIdx.idx; const targetPath = currPathAndIdx.path; return map(filter(pathsAndIndices, (searchPathAndIdx) => { return alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities !== true && searchPathAndIdx.idx < targetIdx && isStrictPrefixOfPath(searchPathAndIdx.path, targetPath); }), (currAmbPathAndIdx) => { const ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1]; const occurrence = alternation.idx === 0 ? "" : alternation.idx; return { message: errMsgProvider.buildAlternationPrefixAmbiguityError({ topLevelRule: rule, alternation, ambiguityIndices: ambgIndices, prefixPath: currAmbPathAndIdx.path }), type: ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, ruleName: rule.name, occurrence, alternatives: ambgIndices }; }); })); } function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) { const errors = []; const tokenNames = map(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 error = new MismatchedTokenException(this.errorMessageProvider.buildMismatchTokenMessage({ expected: expectedTokType, actual: nextTokenWithoutResync, previous: previousToken, ruleName: this.getCurrRuleFullName() }), 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; } getFollowsForInRuleRecovery(tokType, tokIdxInRule) { const grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule); return this.getNextPossibleTokenTypes(grammarPath); } tryInRuleRecovery(expectedTokType, follows) { if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) return this.getTokenToInsert(expectedTokType); 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); return find$1(follows, (possibleFollowsTokType) => { return this.tokenMatcher(mismatchedTok, possibleFollowsTokType); }) !== void 0; } canRecoverWithSingleTokenDeletion(expectedTokType) { if (!this.canTokenTypeBeDeletedInRecovery(expectedTokType)) return false; return this.tokenMatcher(this.LA(2), expectedTokType); } isInCurrentRuleReSyncSet(tokenTypeIdx) { const followKey = this.getCurrFollowKey(); return includes(this.getFollowSetFromFollowKey(followKey), tokenTypeIdx); } findReSyncTokenType() { const allPossibleReSyncTokTypes = this.flattenFollowSet(); let nextToken = this.LA(1); let k = 2; while (true) { const foundMatch = find$1(allPossibleReSyncTokTypes, (resyncTokType) => { return tokenMatcher(nextToken, resyncTokType); }); 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 map(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() { return flatten(map(this.buildFullFollowKeyStack(), (currKey) => { return this.getFollowSetFromFollowKey(currKey); })); } getFollowSetFromFollowKey(followKey) { if (followKey === EOF_FOLLOW_KEY) return [EOF]; const followName = followKey.ruleName + followKey.idxInCallingRule + IN + followKey.inRule; return this.resyncFollows[followName]; } 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) { return { ruleStack: this.getHumanReadableRuleStack(), occurrenceStack: clone(this.RULE_OCCURRENCE_STACK), lastTok: tokType, lastTokOccurrence: tokIdxInRule }; } getHumanReadableRuleStack() { return map(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]; firstAfterRepInfo = new nextToksWalker(ruleGrammar, prodOccurrence).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_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 _a; this.maxLookahead = (_a = options === null || options === void 0 ? void 0 : options.maxLookahead) !== null && _a !== void 0 ? _a : 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); return [ ...leftRecursionErrors, ...emptyAltErrors, ...ambiguousAltsErrors, ...emptyRepetitionErrors ]; } 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); }); } getKeyForAutomaticLookahead(dslMethodIdx, occurrence) { return getKeyForAutomaticLookahead(this.getLastExplicitRuleShortName(), 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 i = 0; i < childrenNamesLength; i++) { const currChildArray = ctx[childrenNames[i]]; 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"); derivedConstructor.prototype = { visit: function(cstNode, param) { if (isArray$1(cstNode)) cstNode = cstNode[0]; if (isUndefined(cstNode)) return; return this[cstNode.name](cstNode.children, param); }, validateVisitor: function() { const semanticDefinitionErrors = validateVisitor(this, ruleNames); if (!isEmpty(semanticDefinitionErrors)) { const errorMessages = map(semanticDefinitionErrors, (currDefError) => currDefError.msg); throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: ${errorMessages.join("\n\n").replace(/\n/g, "\n ")}`); } } }; 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) { return validateMissingCstMethods(visitorInstance, ruleNames); } function validateMissingCstMethods(visitorInstance, ruleNames) { return compact(map(filter(ruleNames, (currRuleName) => { return isFunction(visitorInstance[currRuleName]) === false; }), (currRuleName) => { return { msg: `Missing visitor method: <${currRuleName}> on ${visitorInstance.constructor.name} CST Visitor.`, type: CstVisitorDefinitionError.MISSING_METHOD, methodName: currRuleName }; })); } 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 = noop; this.cstFinallyStateUpdate = noop; this.cstPostTerminal = noop; this.cstPostNonTerminal = noop; this.cstPostRule = noop; } else if (/full/i.test(this.nodeLocationTracking)) if (this.recoveryEnabled) { this.setNodeLocationFromToken = setNodeLocationFull; this.setNodeLocationFromNode = setNodeLocationFull; this.cstPostRule = noop; this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery; } else { this.setNodeLocationFromToken = noop; this.setNodeLocationFromNode = noop; 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 = noop; this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery; } else { this.setNodeLocationFromToken = noop; this.setNodeLocationFromNode = noop; this.cstPostRule = this.cstPostRuleOnlyOffset; this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular; } else if (/none/i.test(this.nodeLocationTracking)) { this.setNodeLocationFromToken = noop; this.setNodeLocationFromNode = noop; this.cstPostRule = noop; this.setInitialNodeLocation = noop; } else throw Error(`Invalid config option: "${config.nodeLocationTracking}"`); } setInitialNodeLocationOnlyOffsetRecovery(cstNode) { cstNode.location = { startOffset: NaN, endOffset: NaN }; } setInitialNodeLocationOnlyOffsetRegular(cstNode) { cstNode.location = { 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; } SKIP_TOKEN() { if (this.currIdx <= this.tokVector.length - 2) { this.consumeToken(); return this.LA(1); } else return END_OF_FILE; } 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 error = { message: defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ topLevelRule: name, grammarName: this.className }), 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 (e) { if (isRecognitionException(e)) return false; else throw e; } finally { this.reloadRecogState(orgState); this.isBackTrackingStack.pop(); } }; } 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 = reduce(tokenVocabulary, (acc, tokType) => { acc[tokType.name] = tokType; return acc; }, {}); else if (has(tokenVocabulary, "modes") && every(flatten(values(tokenVocabulary.modes)), isTokenType)) { const uniqueTokens = uniq(flatten(values(tokenVocabulary.modes))); this.tokensMap = reduce(uniqueTokens, (acc, tokType) => { acc[tokType.name] = tokType; return acc; }, {}); } else if (isObject(tokenVocabulary)) this.tokensMap = clone(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 noTokenCategoriesUsed = every(has(tokenVocabulary, "modes") ? flatten(values(tokenVocabulary.modes)) : values(tokenVocabulary), (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 << 12; 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 (e) { return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc); } finally { this.ruleFinallyStateUpdate(); } }; else invokeRuleWithTry = function invokeRuleWithTryCst(...args) { try { this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx); return impl.apply(this, args); } catch (e) { return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc); } finally { this.ruleFinallyStateUpdate(); } }; return Object.assign(invokeRuleWithTry, { ruleName, originalGrammarAction: impl }); } invokeRuleCatch(e, resyncEnabledConfig, recoveryValueFunc) { const isFirstInvokedRule = this.RULE_STACK.length === 1; const reSyncEnabled = resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled; if (isRecognitionException(e)) { const recogError = e; 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(e); } 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(e); } else throw recogError; } else throw e; } 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); } 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; if (this.getLaFuncFromCache(key).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, 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; if (this.getLaFuncFromCache(key).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); return this.getLexerPosition() > beforeIteration; } orInternal(altsOrOpts, occurrence) { const laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence); const alts = isArray$1(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF; const altIdxToTake = this.getLaFuncFromCache(laKey).call(this, alts); if (altIdxToTake !== void 0) return alts[altIdxToTake].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 (e) { throw this.subruleInternalError(e, options, ruleToCall.ruleName); } } subruleInternalError(e, options, ruleName) { if (isRecognitionException(e) && e.partialCstResult !== void 0) { this.cstPostNonTerminal(e.partialCstResult, options !== void 0 && options.LABEL !== void 0 ? options.LABEL : ruleName); delete e.partialCstResult; } throw e; } 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 && 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 = clone(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: clone(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 clone(this._errors); } set errors(newErrors) { this._errors = newErrors; } raiseEarlyExitException(occurrence, prodType, userDefinedErrMsg) { const ruleName = this.getCurrRuleFullName(); const ruleGrammar = this.getGAstProductions()[ruleName]; const insideProdPaths = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, this.maxLookahead)[0]; const actualTokens = []; for (let i = 1; i <= this.maxLookahead; i++) actualTokens.push(this.LA(i)); 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))); } raiseNoAltException(occurrence, errMsgTypes) { const ruleName = this.getCurrRuleFullName(); const ruleGrammar = this.getGAstProductions()[ruleName]; const lookAheadPathsPerAlternative = getLookaheadPathsForOr(occurrence, ruleGrammar, this.maxLookahead); const actualTokens = []; for (let i = 1; i <= this.maxLookahead; i++) actualTokens.push(this.LA(i)); 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); } getNextPossibleTokenTypes(grammarPath) { const topRuleName = head(grammarPath.ruleStack); const topProduction = this.getGAstProductions()[topRuleName]; return new NextAfterTokenWalker(topProduction, grammarPath).startWalking(); } } 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", -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 i = 0; i < 10; i++) { const idx = i > 0 ? i : ""; this[`CONSUME${idx}`] = function(arg1, arg2) { return this.consumeInternalRecord(arg1, i, arg2); }; this[`SUBRULE${idx}`] = function(arg1, arg2) { return this.subruleInternalRecord(arg1, i, arg2); }; this[`OPTION${idx}`] = function(arg1) { return this.optionInternalRecord(arg1, i); }; this[`OR${idx}`] = function(arg1) { return this.orInternalRecord(arg1, i); }; this[`MANY${idx}`] = function(arg1) { this.manyInternalRecord(i, arg1); }; this[`MANY_SEP${idx}`] = function(arg1) { this.manySepFirstInternalRecord(i, arg1); }; this[`AT_LEAST_ONE${idx}`] = function(arg1) { this.atLeastOneInternalRecord(i, arg1); }; this[`AT_LEAST_ONE_SEP${idx}`] = function(arg1) { this.atLeastOneSepFirstInternalRecord(i, 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 i = 0; i < 10; i++) { const idx = i > 0 ? i : ""; 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; }); } ACTION_RECORD(impl) {} BACKTRACK_RECORD(grammarRule, args) { return () => true; } 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; } } 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 = /* @__PURE__ */ 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, 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 = /* @__PURE__ */ 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 = isFunction(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; newOrProd.hasPredicates = some(alts, (currAlt) => isFunction(currAlt.GATE)); 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 = /* @__PURE__ */ new Error(`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 } = timer(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 Parser { /** * @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 originalGrammarAction = this[currRuleName]["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 _a, _b; (_b = (_a = this.lookaheadStrategy).initialize) === null || _b === void 0 || _b.call(_a, { rules: values(this.gastProductionsCache) }); this.preComputeLookaheadFunctions(values(this.gastProductionsCache)); }); } if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING && !isEmpty(this.definitionErrors)) { defErrorsMsgs = map(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; } } Parser.DEFER_DEFINITION_ERRORS_HANDLING = false; applyMixins(Parser, [ Recoverable, LooksAhead, TreeBuilder, LexerAdapter, RecognizerEngine, RecognizerApi, ErrorHandler, ContentAssist, GastRecorder, PerformanceTracer ]); class CstParser2 extends Parser { constructor(tokenVocabulary, config = DEFAULT_PARSER_CONFIG) { const configClone = clone(config); configClone.outputCst = true; super(tokenVocabulary, configClone); } } return { CstParser: CstParser2, Lexer: Lexer2, createToken: createToken2 }; })(); //#endregion //#region node_modules/three-stdlib/loaders/VRMLLoader.js var VRMLLoader = 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 loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text, path)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(data, path) { const nodeMap = {}; function generateVRMLTree(data2) { const tokenData = createTokens(); const lexer = new VRMLLexer(tokenData.tokens); const parser = new VRMLParser(tokenData.tokenVocabulary); const visitor = createVisitor(parser.getBaseCstVisitorConstructor()); parser.input = lexer.lex(data2).tokens; const cstOutput = parser.vrml(); if (parser.errors.length > 0) { console.error(parser.errors); throw Error("THREE.VRMLLoader: Parsing errors detected."); } return visitor.visit(cstOutput); } function createTokens() { const RouteIdentifier = createToken({ name: "RouteIdentifier", pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/ }); const Identifier = createToken({ name: "Identifier", pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/, longer_alt: RouteIdentifier }); const nodeTypes = [ "Anchor", "Billboard", "Collision", "Group", "Transform", "Inline", "LOD", "Switch", "AudioClip", "DirectionalLight", "PointLight", "Script", "Shape", "Sound", "SpotLight", "WorldInfo", "CylinderSensor", "PlaneSensor", "ProximitySensor", "SphereSensor", "TimeSensor", "TouchSensor", "VisibilitySensor", "Box", "Cone", "Cylinder", "ElevationGrid", "Extrusion", "IndexedFaceSet", "IndexedLineSet", "PointSet", "Sphere", "Color", "Coordinate", "Normal", "TextureCoordinate", "Appearance", "FontStyle", "ImageTexture", "Material", "MovieTexture", "PixelTexture", "TextureTransform", "ColorInterpolator", "CoordinateInterpolator", "NormalInterpolator", "OrientationInterpolator", "PositionInterpolator", "ScalarInterpolator", "Background", "Fog", "NavigationInfo", "Viewpoint", "Text" ]; const Version = createToken({ name: "Version", pattern: /#VRML.*/, longer_alt: Identifier }); const NodeName = createToken({ name: "NodeName", pattern: new RegExp(nodeTypes.join("|")), longer_alt: Identifier }); const DEF = createToken({ name: "DEF", pattern: /DEF/, longer_alt: Identifier }); const USE = createToken({ name: "USE", pattern: /USE/, longer_alt: Identifier }); const ROUTE = createToken({ name: "ROUTE", pattern: /ROUTE/, longer_alt: Identifier }); const TO = createToken({ name: "TO", pattern: /TO/, longer_alt: Identifier }); const StringLiteral = createToken({ name: "StringLiteral", pattern: /"(?:[^\\"\n\r]|\\[bfnrtv"\\/]|\\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])*"/ }); const HexLiteral = createToken({ name: "HexLiteral", pattern: /0[xX][0-9a-fA-F]+/ }); const NumberLiteral = createToken({ name: "NumberLiteral", pattern: /[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/ }); const TrueLiteral = createToken({ name: "TrueLiteral", pattern: /TRUE/ }); const FalseLiteral = createToken({ name: "FalseLiteral", pattern: /FALSE/ }); const NullLiteral = createToken({ name: "NullLiteral", pattern: /NULL/ }); const LSquare = createToken({ name: "LSquare", pattern: /\[/ }); const RSquare = createToken({ name: "RSquare", pattern: /]/ }); const LCurly = createToken({ name: "LCurly", pattern: /{/ }); const RCurly = createToken({ name: "RCurly", pattern: /}/ }); const Comment = createToken({ name: "Comment", pattern: /#.*/, group: Lexer.SKIPPED }); const tokens = [ createToken({ name: "WhiteSpace", pattern: /[ ,\s]/, group: Lexer.SKIPPED }), NodeName, DEF, USE, ROUTE, TO, TrueLiteral, FalseLiteral, NullLiteral, Version, Identifier, RouteIdentifier, StringLiteral, HexLiteral, NumberLiteral, LSquare, RSquare, LCurly, RCurly, Comment ]; const tokenVocabulary = {}; for (let i = 0, l = tokens.length; i < l; i++) { const token = tokens[i]; tokenVocabulary[token.name] = token; } return { tokens, tokenVocabulary }; } function createVisitor(BaseVRMLVisitor) { function VRMLToASTVisitor() { BaseVRMLVisitor.call(this); this.validateVisitor(); } VRMLToASTVisitor.prototype = Object.assign(Object.create(BaseVRMLVisitor.prototype), { constructor: VRMLToASTVisitor, vrml: function(ctx) { const data2 = { version: this.visit(ctx.version), nodes: [], routes: [] }; for (let i = 0, l = ctx.node.length; i < l; i++) { const node = ctx.node[i]; data2.nodes.push(this.visit(node)); } if (ctx.route) for (let i = 0, l = ctx.route.length; i < l; i++) { const route = ctx.route[i]; data2.routes.push(this.visit(route)); } return data2; }, version: function(ctx) { return ctx.Version[0].image; }, node: function(ctx) { const data2 = { name: ctx.NodeName[0].image, fields: [] }; if (ctx.field) for (let i = 0, l = ctx.field.length; i < l; i++) { const field = ctx.field[i]; data2.fields.push(this.visit(field)); } if (ctx.def) data2.DEF = this.visit(ctx.def[0]); return data2; }, field: function(ctx) { const data2 = { name: ctx.Identifier[0].image, type: null, values: null }; let result; if (ctx.singleFieldValue) result = this.visit(ctx.singleFieldValue[0]); if (ctx.multiFieldValue) result = this.visit(ctx.multiFieldValue[0]); data2.type = result.type; data2.values = result.values; return data2; }, def: function(ctx) { return (ctx.Identifier || ctx.NodeName)[0].image; }, use: function(ctx) { return { USE: (ctx.Identifier || ctx.NodeName)[0].image }; }, singleFieldValue: function(ctx) { return processField(this, ctx); }, multiFieldValue: function(ctx) { return processField(this, ctx); }, route: function(ctx) { return { FROM: ctx.RouteIdentifier[0].image, TO: ctx.RouteIdentifier[1].image }; } }); function processField(scope, ctx) { const field = { type: null, values: [] }; if (ctx.node) { field.type = "node"; for (let i = 0, l = ctx.node.length; i < l; i++) { const node = ctx.node[i]; field.values.push(scope.visit(node)); } } if (ctx.use) { field.type = "use"; for (let i = 0, l = ctx.use.length; i < l; i++) { const use = ctx.use[i]; field.values.push(scope.visit(use)); } } if (ctx.StringLiteral) { field.type = "string"; for (let i = 0, l = ctx.StringLiteral.length; i < l; i++) { const stringLiteral = ctx.StringLiteral[i]; field.values.push(stringLiteral.image.replace(/'|"/g, "")); } } if (ctx.NumberLiteral) { field.type = "number"; for (let i = 0, l = ctx.NumberLiteral.length; i < l; i++) { const numberLiteral = ctx.NumberLiteral[i]; field.values.push(parseFloat(numberLiteral.image)); } } if (ctx.HexLiteral) { field.type = "hex"; for (let i = 0, l = ctx.HexLiteral.length; i < l; i++) { const hexLiteral = ctx.HexLiteral[i]; field.values.push(hexLiteral.image); } } if (ctx.TrueLiteral) { field.type = "boolean"; for (let i = 0, l = ctx.TrueLiteral.length; i < l; i++) if (ctx.TrueLiteral[i].image === "TRUE") field.values.push(true); } if (ctx.FalseLiteral) { field.type = "boolean"; for (let i = 0, l = ctx.FalseLiteral.length; i < l; i++) if (ctx.FalseLiteral[i].image === "FALSE") field.values.push(false); } if (ctx.NullLiteral) { field.type = "null"; ctx.NullLiteral.forEach(function() { field.values.push(null); }); } return field; } return new VRMLToASTVisitor(); } function parseTree(tree2) { const nodes = tree2.nodes; const scene2 = new Scene(); for (let i = 0, l = nodes.length; i < l; i++) { const node = nodes[i]; buildNodeMap(node); } for (let i = 0, l = nodes.length; i < l; i++) { const node = nodes[i]; const object = getNode(node); if (object instanceof Object3D) scene2.add(object); if (node.name === "WorldInfo") scene2.userData.worldInfo = object; } return scene2; } function buildNodeMap(node) { if (node.DEF) nodeMap[node.DEF] = node; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; if (field.type === "node") { const fieldValues = field.values; for (let j = 0, jl = fieldValues.length; j < jl; j++) buildNodeMap(fieldValues[j]); } } } function getNode(node) { if (node.USE) return resolveUSE(node.USE); if (node.build !== void 0) return node.build; node.build = buildNode(node); return node.build; } function buildNode(node) { const nodeName = node.name; let build; switch (nodeName) { case "Group": case "Transform": case "Collision": build = buildGroupingNode(node); break; case "Background": build = buildBackgroundNode(node); break; case "Shape": build = buildShapeNode(node); break; case "Appearance": build = buildAppearanceNode(node); break; case "Material": build = buildMaterialNode(node); break; case "ImageTexture": build = buildImageTextureNode(node); break; case "PixelTexture": build = buildPixelTextureNode(node); break; case "TextureTransform": build = buildTextureTransformNode(node); break; case "IndexedFaceSet": build = buildIndexedFaceSetNode(node); break; case "IndexedLineSet": build = buildIndexedLineSetNode(node); break; case "PointSet": build = buildPointSetNode(node); break; case "Box": build = buildBoxNode(node); break; case "Cone": build = buildConeNode(node); break; case "Cylinder": build = buildCylinderNode(node); break; case "Sphere": build = buildSphereNode(node); break; case "ElevationGrid": build = buildElevationGridNode(node); break; case "Extrusion": build = buildExtrusionNode(node); break; case "Color": case "Coordinate": case "Normal": case "TextureCoordinate": build = buildGeometricNode(node); break; case "WorldInfo": build = buildWorldInfoNode(node); break; case "Anchor": case "Billboard": case "Inline": case "LOD": case "Switch": case "AudioClip": case "DirectionalLight": case "PointLight": case "Script": case "Sound": case "SpotLight": case "CylinderSensor": case "PlaneSensor": case "ProximitySensor": case "SphereSensor": case "TimeSensor": case "TouchSensor": case "VisibilitySensor": case "Text": case "FontStyle": case "MovieTexture": case "ColorInterpolator": case "CoordinateInterpolator": case "NormalInterpolator": case "OrientationInterpolator": case "PositionInterpolator": case "ScalarInterpolator": case "Fog": case "NavigationInfo": case "Viewpoint": break; default: console.warn("THREE.VRMLLoader: Unknown node:", nodeName); break; } if (build !== void 0 && node.DEF !== void 0 && build.hasOwnProperty("name") === true) build.name = node.DEF; return build; } function buildGroupingNode(node) { const object = new Group(); const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "bboxCenter": break; case "bboxSize": break; case "center": break; case "children": parseFieldChildren(fieldValues, object); break; case "collide": break; case "rotation": const axis = new Vector3(fieldValues[0], fieldValues[1], fieldValues[2]).normalize(); const angle = fieldValues[3]; object.quaternion.setFromAxisAngle(axis, angle); break; case "scale": object.scale.set(fieldValues[0], fieldValues[1], fieldValues[2]); break; case "scaleOrientation": break; case "translation": object.position.set(fieldValues[0], fieldValues[1], fieldValues[2]); break; case "proxy": break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } return object; } function buildBackgroundNode(node) { const group = new Group(); let groundAngle, groundColor; let skyAngle, skyColor; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "groundAngle": groundAngle = fieldValues; break; case "groundColor": groundColor = fieldValues; break; case "backUrl": break; case "bottomUrl": break; case "frontUrl": break; case "leftUrl": break; case "rightUrl": break; case "topUrl": break; case "skyAngle": skyAngle = fieldValues; break; case "skyColor": skyColor = fieldValues; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } const radius = 1e4; if (skyColor) { const skyGeometry = new SphereGeometry(radius, 32, 16); const skyMaterial = new MeshBasicMaterial({ fog: false, side: 1, depthWrite: false, depthTest: false }); if (skyColor.length > 3) { paintFaces(skyGeometry, radius, skyAngle, toColorArray(skyColor), true); skyMaterial.vertexColors = true; } else skyMaterial.color.setRGB(skyColor[0], skyColor[1], skyColor[2]); const sky = new Mesh(skyGeometry, skyMaterial); group.add(sky); } if (groundColor) { if (groundColor.length > 0) { const groundGeometry = new SphereGeometry(radius, 32, 16, 0, 2 * Math.PI, .5 * Math.PI, 1.5 * Math.PI); const groundMaterial = new MeshBasicMaterial({ fog: false, side: 1, vertexColors: true, depthWrite: false, depthTest: false }); paintFaces(groundGeometry, radius, groundAngle, toColorArray(groundColor), false); const ground = new Mesh(groundGeometry, groundMaterial); group.add(ground); } } group.renderOrder = -Infinity; return group; } function buildShapeNode(node) { const fields = node.fields; let material = new MeshBasicMaterial({ color: 0 }); let geometry; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "appearance": if (fieldValues[0] !== null) material = getNode(fieldValues[0]); break; case "geometry": if (fieldValues[0] !== null) geometry = getNode(fieldValues[0]); break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } let object; if (geometry && geometry.attributes.position) { const type = geometry._type; if (type === "points") { const pointsMaterial = new PointsMaterial({ color: 16777215 }); if (geometry.attributes.color !== void 0) pointsMaterial.vertexColors = true; else if (material.isMeshPhongMaterial) pointsMaterial.color.copy(material.emissive); object = new Points(geometry, pointsMaterial); } else if (type === "line") { const lineMaterial = new LineBasicMaterial({ color: 16777215 }); if (geometry.attributes.color !== void 0) lineMaterial.vertexColors = true; else if (material.isMeshPhongMaterial) lineMaterial.color.copy(material.emissive); object = new LineSegments(geometry, lineMaterial); } else { if (geometry._solid !== void 0) material.side = geometry._solid ? 0 : 2; if (geometry.attributes.color !== void 0) material.vertexColors = true; object = new Mesh(geometry, material); } } else { object = new Object3D(); object.visible = false; } return object; } function buildAppearanceNode(node) { let material = new MeshPhongMaterial(); let transformData; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "material": if (fieldValues[0] !== null) { const materialData = getNode(fieldValues[0]); if (materialData.diffuseColor) material.color.copy(materialData.diffuseColor); if (materialData.emissiveColor) material.emissive.copy(materialData.emissiveColor); if (materialData.shininess) material.shininess = materialData.shininess; if (materialData.specularColor) material.specular.copy(materialData.specularColor); if (materialData.transparency) material.opacity = 1 - materialData.transparency; if (materialData.transparency > 0) material.transparent = true; } else material = new MeshBasicMaterial({ color: 0 }); break; case "texture": const textureNode = fieldValues[0]; if (textureNode !== null) { if (textureNode.name === "ImageTexture" || textureNode.name === "PixelTexture") material.map = getNode(textureNode); } break; case "textureTransform": if (fieldValues[0] !== null) transformData = getNode(fieldValues[0]); break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } if (material.map) { if (material.map.__type) { switch (material.map.__type) { case TEXTURE_TYPE.INTENSITY_ALPHA: material.opacity = 1; break; case TEXTURE_TYPE.RGB: material.color.set(16777215); break; case TEXTURE_TYPE.RGBA: material.color.set(16777215); material.opacity = 1; break; } delete material.map.__type; } if (transformData) { material.map.center.copy(transformData.center); material.map.rotation = transformData.rotation; material.map.repeat.copy(transformData.scale); material.map.offset.copy(transformData.translation); } } return material; } function buildMaterialNode(node) { const materialData = {}; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "ambientIntensity": break; case "diffuseColor": materialData.diffuseColor = new Color(fieldValues[0], fieldValues[1], fieldValues[2]); break; case "emissiveColor": materialData.emissiveColor = new Color(fieldValues[0], fieldValues[1], fieldValues[2]); break; case "shininess": materialData.shininess = fieldValues[0]; break; case "specularColor": materialData.emissiveColor = new Color(fieldValues[0], fieldValues[1], fieldValues[2]); break; case "transparency": materialData.transparency = fieldValues[0]; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } return materialData; } function parseHexColor(hex, textureType, color) { let value; switch (textureType) { case TEXTURE_TYPE.INTENSITY: value = parseInt(hex); color.r = value; color.g = value; color.b = value; color.a = 1; break; case TEXTURE_TYPE.INTENSITY_ALPHA: value = parseInt("0x" + hex.substring(2, 4)); color.r = value; color.g = value; color.b = value; color.a = parseInt("0x" + hex.substring(4, 6)); break; case TEXTURE_TYPE.RGB: color.r = parseInt("0x" + hex.substring(2, 4)); color.g = parseInt("0x" + hex.substring(4, 6)); color.b = parseInt("0x" + hex.substring(6, 8)); color.a = 1; break; case TEXTURE_TYPE.RGBA: color.r = parseInt("0x" + hex.substring(2, 4)); color.g = parseInt("0x" + hex.substring(4, 6)); color.b = parseInt("0x" + hex.substring(6, 8)); color.a = parseInt("0x" + hex.substring(8, 10)); break; } } function getTextureType(num_components) { let type; switch (num_components) { case 1: type = TEXTURE_TYPE.INTENSITY; break; case 2: type = TEXTURE_TYPE.INTENSITY_ALPHA; break; case 3: type = TEXTURE_TYPE.RGB; break; case 4: type = TEXTURE_TYPE.RGBA; break; } return type; } function buildPixelTextureNode(node) { let texture; let wrapS = RepeatWrapping; let wrapT = RepeatWrapping; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "image": const width = fieldValues[0]; const height = fieldValues[1]; const num_components = fieldValues[2]; const textureType = getTextureType(num_components); const data2 = new Uint8Array(4 * width * height); const color = { r: 0, g: 0, b: 0, a: 0 }; for (let j = 3, k = 0, jl = fieldValues.length; j < jl; j++, k++) { parseHexColor(fieldValues[j], textureType, color); const stride = k * 4; data2[stride + 0] = color.r; data2[stride + 1] = color.g; data2[stride + 2] = color.b; data2[stride + 3] = color.a; } texture = new DataTexture(data2, width, height); texture.needsUpdate = true; texture.__type = textureType; break; case "repeatS": if (fieldValues[0] === false) wrapS = ClampToEdgeWrapping; break; case "repeatT": if (fieldValues[0] === false) wrapT = ClampToEdgeWrapping; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } if (texture) { texture.wrapS = wrapS; texture.wrapT = wrapT; } return texture; } function buildImageTextureNode(node) { let texture; let wrapS = RepeatWrapping; let wrapT = RepeatWrapping; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "url": const url = fieldValues[0]; if (url) texture = textureLoader.load(url); break; case "repeatS": if (fieldValues[0] === false) wrapS = ClampToEdgeWrapping; break; case "repeatT": if (fieldValues[0] === false) wrapT = ClampToEdgeWrapping; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } if (texture) { texture.wrapS = wrapS; texture.wrapT = wrapT; } return texture; } function buildTextureTransformNode(node) { const transformData = { center: new Vector2(), rotation: new Vector2(), scale: new Vector2(), translation: new Vector2() }; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "center": transformData.center.set(fieldValues[0], fieldValues[1]); break; case "rotation": transformData.rotation = fieldValues[0]; break; case "scale": transformData.scale.set(fieldValues[0], fieldValues[1]); break; case "translation": transformData.translation.set(fieldValues[0], fieldValues[1]); break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } return transformData; } function buildGeometricNode(node) { return node.fields[0].values; } function buildWorldInfoNode(node) { const worldInfo = {}; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "title": worldInfo.title = fieldValues[0]; break; case "info": worldInfo.info = fieldValues; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } return worldInfo; } function buildIndexedFaceSetNode(node) { let color, coord, normal, texCoord; let ccw = true, solid = true, creaseAngle = 0; let colorIndex, coordIndex, normalIndex, texCoordIndex; let colorPerVertex = true, normalPerVertex = true; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "color": const colorNode = fieldValues[0]; if (colorNode !== null) color = getNode(colorNode); break; case "coord": const coordNode = fieldValues[0]; if (coordNode !== null) coord = getNode(coordNode); break; case "normal": const normalNode = fieldValues[0]; if (normalNode !== null) normal = getNode(normalNode); break; case "texCoord": const texCoordNode = fieldValues[0]; if (texCoordNode !== null) texCoord = getNode(texCoordNode); break; case "ccw": ccw = fieldValues[0]; break; case "colorIndex": colorIndex = fieldValues; break; case "colorPerVertex": colorPerVertex = fieldValues[0]; break; case "convex": break; case "coordIndex": coordIndex = fieldValues; break; case "creaseAngle": creaseAngle = fieldValues[0]; break; case "normalIndex": normalIndex = fieldValues; break; case "normalPerVertex": normalPerVertex = fieldValues[0]; break; case "solid": solid = fieldValues[0]; break; case "texCoordIndex": texCoordIndex = fieldValues; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } if (coordIndex === void 0) { console.warn("THREE.VRMLLoader: Missing coordIndex."); return new BufferGeometry(); } const triangulatedCoordIndex = triangulateFaceIndex(coordIndex, ccw); let colorAttribute; let normalAttribute; let uvAttribute; if (color) if (colorPerVertex === true) if (colorIndex && colorIndex.length > 0) colorAttribute = computeAttributeFromIndexedData(triangulatedCoordIndex, triangulateFaceIndex(colorIndex, ccw), color, 3); else colorAttribute = toNonIndexedAttribute(triangulatedCoordIndex, new Float32BufferAttribute(color, 3)); else if (colorIndex && colorIndex.length > 0) colorAttribute = computeAttributeFromFaceData(triangulatedCoordIndex, triangulateFaceData(flattenData(color, colorIndex), coordIndex)); else colorAttribute = computeAttributeFromFaceData(triangulatedCoordIndex, triangulateFaceData(color, coordIndex)); if (normal) if (normalPerVertex === true) if (normalIndex && normalIndex.length > 0) normalAttribute = computeAttributeFromIndexedData(triangulatedCoordIndex, triangulateFaceIndex(normalIndex, ccw), normal, 3); else normalAttribute = toNonIndexedAttribute(triangulatedCoordIndex, new Float32BufferAttribute(normal, 3)); else if (normalIndex && normalIndex.length > 0) normalAttribute = computeAttributeFromFaceData(triangulatedCoordIndex, triangulateFaceData(flattenData(normal, normalIndex), coordIndex)); else normalAttribute = computeAttributeFromFaceData(triangulatedCoordIndex, triangulateFaceData(normal, coordIndex)); else normalAttribute = computeNormalAttribute(triangulatedCoordIndex, coord, creaseAngle); if (texCoord) if (texCoordIndex && texCoordIndex.length > 0) uvAttribute = computeAttributeFromIndexedData(triangulatedCoordIndex, triangulateFaceIndex(texCoordIndex, ccw), texCoord, 2); else uvAttribute = toNonIndexedAttribute(triangulatedCoordIndex, new Float32BufferAttribute(texCoord, 2)); const geometry = new BufferGeometry(); const positionAttribute = toNonIndexedAttribute(triangulatedCoordIndex, new Float32BufferAttribute(coord, 3)); geometry.setAttribute("position", positionAttribute); geometry.setAttribute("normal", normalAttribute); if (colorAttribute) geometry.setAttribute("color", colorAttribute); if (uvAttribute) geometry.setAttribute("uv", uvAttribute); geometry._solid = solid; geometry._type = "mesh"; return geometry; } function buildIndexedLineSetNode(node) { let color, coord; let colorIndex, coordIndex; let colorPerVertex = true; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "color": const colorNode = fieldValues[0]; if (colorNode !== null) color = getNode(colorNode); break; case "coord": const coordNode = fieldValues[0]; if (coordNode !== null) coord = getNode(coordNode); break; case "colorIndex": colorIndex = fieldValues; break; case "colorPerVertex": colorPerVertex = fieldValues[0]; break; case "coordIndex": coordIndex = fieldValues; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } let colorAttribute; const expandedLineIndex = expandLineIndex(coordIndex); if (color) if (colorPerVertex === true) if (colorIndex.length > 0) colorAttribute = computeAttributeFromIndexedData(expandedLineIndex, expandLineIndex(colorIndex), color, 3); else colorAttribute = toNonIndexedAttribute(expandedLineIndex, new Float32BufferAttribute(color, 3)); else if (colorIndex.length > 0) colorAttribute = computeAttributeFromLineData(expandedLineIndex, expandLineData(flattenData(color, colorIndex), coordIndex)); else colorAttribute = computeAttributeFromLineData(expandedLineIndex, expandLineData(color, coordIndex)); const geometry = new BufferGeometry(); const positionAttribute = toNonIndexedAttribute(expandedLineIndex, new Float32BufferAttribute(coord, 3)); geometry.setAttribute("position", positionAttribute); if (colorAttribute) geometry.setAttribute("color", colorAttribute); geometry._type = "line"; return geometry; } function buildPointSetNode(node) { let color, coord; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "color": const colorNode = fieldValues[0]; if (colorNode !== null) color = getNode(colorNode); break; case "coord": const coordNode = fieldValues[0]; if (coordNode !== null) coord = getNode(coordNode); break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } const geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute(coord, 3)); if (color) geometry.setAttribute("color", new Float32BufferAttribute(color, 3)); geometry._type = "points"; return geometry; } function buildBoxNode(node) { const size = new Vector3(2, 2, 2); const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "size": size.x = fieldValues[0]; size.y = fieldValues[1]; size.z = fieldValues[2]; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } return new BoxGeometry(size.x, size.y, size.z); } function buildConeNode(node) { let radius = 1, height = 2, openEnded = false; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "bottom": openEnded = !fieldValues[0]; break; case "bottomRadius": radius = fieldValues[0]; break; case "height": height = fieldValues[0]; break; case "side": break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } return new ConeGeometry(radius, height, 16, 1, openEnded); } function buildCylinderNode(node) { let radius = 1, height = 2; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "bottom": break; case "radius": radius = fieldValues[0]; break; case "height": height = fieldValues[0]; break; case "side": break; case "top": break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } return new CylinderGeometry(radius, radius, height, 16, 1); } function buildSphereNode(node) { let radius = 1; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "radius": radius = fieldValues[0]; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } return new SphereGeometry(radius, 16, 16); } function buildElevationGridNode(node) { let color; let normal; let texCoord; let height; let colorPerVertex = true; let normalPerVertex = true; let solid = true; let ccw = true; let creaseAngle = 0; let xDimension = 2; let zDimension = 2; let xSpacing = 1; let zSpacing = 1; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "color": const colorNode = fieldValues[0]; if (colorNode !== null) color = getNode(colorNode); break; case "normal": const normalNode = fieldValues[0]; if (normalNode !== null) normal = getNode(normalNode); break; case "texCoord": const texCoordNode = fieldValues[0]; if (texCoordNode !== null) texCoord = getNode(texCoordNode); break; case "height": height = fieldValues; break; case "ccw": ccw = fieldValues[0]; break; case "colorPerVertex": colorPerVertex = fieldValues[0]; break; case "creaseAngle": creaseAngle = fieldValues[0]; break; case "normalPerVertex": normalPerVertex = fieldValues[0]; break; case "solid": solid = fieldValues[0]; break; case "xDimension": xDimension = fieldValues[0]; break; case "xSpacing": xSpacing = fieldValues[0]; break; case "zDimension": zDimension = fieldValues[0]; break; case "zSpacing": zSpacing = fieldValues[0]; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } const vertices = []; const normals = []; const colors = []; const uvs = []; for (let i = 0; i < zDimension; i++) for (let j = 0; j < xDimension; j++) { const index = i * xDimension + j; const x = xSpacing * i; const y = height[index]; const z = zSpacing * j; vertices.push(x, y, z); if (color && colorPerVertex === true) { const r = color[index * 3 + 0]; const g = color[index * 3 + 1]; const b = color[index * 3 + 2]; colors.push(r, g, b); } if (normal && normalPerVertex === true) { const xn = normal[index * 3 + 0]; const yn = normal[index * 3 + 1]; const zn = normal[index * 3 + 2]; normals.push(xn, yn, zn); } if (texCoord) { const s = texCoord[index * 2 + 0]; const t = texCoord[index * 2 + 1]; uvs.push(s, t); } else uvs.push(i / (xDimension - 1), j / (zDimension - 1)); } const indices = []; for (let i = 0; i < xDimension - 1; i++) for (let j = 0; j < zDimension - 1; j++) { const a = i + j * xDimension; const b = i + (j + 1) * xDimension; const c = i + 1 + (j + 1) * xDimension; const d = i + 1 + j * xDimension; if (ccw === true) { indices.push(a, c, b); indices.push(c, a, d); } else { indices.push(a, b, c); indices.push(c, d, a); } } const positionAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(vertices, 3)); const uvAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(uvs, 2)); let colorAttribute; let normalAttribute; if (color) if (colorPerVertex === false) { for (let i = 0; i < xDimension - 1; i++) for (let j = 0; j < zDimension - 1; j++) { const index = i + j * (xDimension - 1); const r = color[index * 3 + 0]; const g = color[index * 3 + 1]; const b = color[index * 3 + 2]; colors.push(r, g, b); colors.push(r, g, b); colors.push(r, g, b); colors.push(r, g, b); colors.push(r, g, b); colors.push(r, g, b); } colorAttribute = new Float32BufferAttribute(colors, 3); } else colorAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(colors, 3)); if (normal) if (normalPerVertex === false) { for (let i = 0; i < xDimension - 1; i++) for (let j = 0; j < zDimension - 1; j++) { const index = i + j * (xDimension - 1); const xn = normal[index * 3 + 0]; const yn = normal[index * 3 + 1]; const zn = normal[index * 3 + 2]; normals.push(xn, yn, zn); normals.push(xn, yn, zn); normals.push(xn, yn, zn); normals.push(xn, yn, zn); normals.push(xn, yn, zn); normals.push(xn, yn, zn); } normalAttribute = new Float32BufferAttribute(normals, 3); } else normalAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(normals, 3)); else normalAttribute = computeNormalAttribute(indices, vertices, creaseAngle); const geometry = new BufferGeometry(); geometry.setAttribute("position", positionAttribute); geometry.setAttribute("normal", normalAttribute); geometry.setAttribute("uv", uvAttribute); if (colorAttribute) geometry.setAttribute("color", colorAttribute); geometry._solid = solid; geometry._type = "mesh"; return geometry; } function buildExtrusionNode(node) { let crossSection = [ 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 ]; let spine = [ 0, 0, 0, 0, 1, 0 ]; let scale; let orientation; let beginCap = true; let ccw = true; let creaseAngle = 0; let endCap = true; let solid = true; const fields = node.fields; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; const fieldName = field.name; const fieldValues = field.values; switch (fieldName) { case "beginCap": beginCap = fieldValues[0]; break; case "ccw": ccw = fieldValues[0]; break; case "convex": break; case "creaseAngle": creaseAngle = fieldValues[0]; break; case "crossSection": crossSection = fieldValues; break; case "endCap": endCap = fieldValues[0]; break; case "orientation": orientation = fieldValues; break; case "scale": scale = fieldValues; break; case "solid": solid = fieldValues[0]; break; case "spine": spine = fieldValues; break; default: console.warn("THREE.VRMLLoader: Unknown field:", fieldName); break; } } const crossSectionClosed = crossSection[0] === crossSection[crossSection.length - 2] && crossSection[1] === crossSection[crossSection.length - 1]; const vertices = []; const spineVector = new Vector3(); const scaling = new Vector3(); const axis = new Vector3(); const vertex = new Vector3(); const quaternion = new Quaternion(); for (let i = 0, j = 0, o = 0, il = spine.length; i < il; i += 3, j += 2, o += 4) { spineVector.fromArray(spine, i); scaling.x = scale ? scale[j + 0] : 1; scaling.y = 1; scaling.z = scale ? scale[j + 1] : 1; axis.x = orientation ? orientation[o + 0] : 0; axis.y = orientation ? orientation[o + 1] : 0; axis.z = orientation ? orientation[o + 2] : 1; const angle = orientation ? orientation[o + 3] : 0; for (let k = 0, kl = crossSection.length; k < kl; k += 2) { vertex.x = crossSection[k + 0]; vertex.y = 0; vertex.z = crossSection[k + 1]; vertex.multiply(scaling); quaternion.setFromAxisAngle(axis, angle); vertex.applyQuaternion(quaternion); vertex.add(spineVector); vertices.push(vertex.x, vertex.y, vertex.z); } } const indices = []; const spineCount = spine.length / 3; const crossSectionCount = crossSection.length / 2; for (let i = 0; i < spineCount - 1; i++) for (let j = 0; j < crossSectionCount - 1; j++) { const a = j + i * crossSectionCount; let b = j + 1 + i * crossSectionCount; const c = j + (i + 1) * crossSectionCount; let d = j + 1 + (i + 1) * crossSectionCount; if (j === crossSectionCount - 2 && crossSectionClosed === true) { b = i * crossSectionCount; d = (i + 1) * crossSectionCount; } if (ccw === true) { indices.push(a, b, c); indices.push(c, b, d); } else { indices.push(a, c, b); indices.push(c, d, b); } } if (beginCap === true || endCap === true) { const contour = []; for (let i = 0, l = crossSection.length; i < l; i += 2) contour.push(new Vector2(crossSection[i], crossSection[i + 1])); const faces = ShapeUtils.triangulateShape(contour, []); const capIndices = []; for (let i = 0, l = faces.length; i < l; i++) { const face = faces[i]; capIndices.push(face[0], face[1], face[2]); } if (beginCap === true) for (let i = 0, l = capIndices.length; i < l; i += 3) if (ccw === true) indices.push(capIndices[i + 0], capIndices[i + 1], capIndices[i + 2]); else indices.push(capIndices[i + 0], capIndices[i + 2], capIndices[i + 1]); if (endCap === true) { const indexOffset = crossSectionCount * (spineCount - 1); for (let i = 0, l = capIndices.length; i < l; i += 3) if (ccw === true) indices.push(indexOffset + capIndices[i + 0], indexOffset + capIndices[i + 2], indexOffset + capIndices[i + 1]); else indices.push(indexOffset + capIndices[i + 0], indexOffset + capIndices[i + 1], indexOffset + capIndices[i + 2]); } } const positionAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(vertices, 3)); const normalAttribute = computeNormalAttribute(indices, vertices, creaseAngle); const geometry = new BufferGeometry(); geometry.setAttribute("position", positionAttribute); geometry.setAttribute("normal", normalAttribute); geometry._solid = solid; geometry._type = "mesh"; return geometry; } function resolveUSE(identifier) { const node = nodeMap[identifier]; const build = getNode(node); return build.isObject3D || build.isMaterial ? build.clone() : build; } function parseFieldChildren(children, owner) { for (let i = 0, l = children.length; i < l; i++) { const object = getNode(children[i]); if (object instanceof Object3D) owner.add(object); } } function triangulateFaceIndex(index, ccw) { const indices = []; let start = 0; for (let i = 0, l = index.length; i < l; i++) { const i1 = index[start]; const i2 = index[i + (ccw ? 1 : 2)]; const i3 = index[i + (ccw ? 2 : 1)]; indices.push(i1, i2, i3); if (index[i + 3] === -1 || i + 3 >= l) { i += 3; start = i + 1; } } return indices; } function triangulateFaceData(data2, index) { const triangulatedData = []; let start = 0; for (let i = 0, l = index.length; i < l; i++) { const stride = start * 3; const x = data2[stride]; const y = data2[stride + 1]; const z = data2[stride + 2]; triangulatedData.push(x, y, z); if (index[i + 3] === -1 || i + 3 >= l) { i += 3; start++; } } return triangulatedData; } function flattenData(data2, index) { const flattenData2 = []; for (let i = 0, l = index.length; i < l; i++) { const stride = index[i] * 3; const x = data2[stride]; const y = data2[stride + 1]; const z = data2[stride + 2]; flattenData2.push(x, y, z); } return flattenData2; } function expandLineIndex(index) { const indices = []; for (let i = 0, l = index.length; i < l; i++) { const i1 = index[i]; const i2 = index[i + 1]; indices.push(i1, i2); if (index[i + 2] === -1 || i + 2 >= l) i += 2; } return indices; } function expandLineData(data2, index) { const triangulatedData = []; let start = 0; for (let i = 0, l = index.length; i < l; i++) { const stride = start * 3; const x = data2[stride]; const y = data2[stride + 1]; const z = data2[stride + 2]; triangulatedData.push(x, y, z); if (index[i + 2] === -1 || i + 2 >= l) { i += 2; start++; } } return triangulatedData; } const vA = new Vector3(); const vB = new Vector3(); const vC = new Vector3(); const uvA = new Vector2(); const uvB = new Vector2(); const uvC = new Vector2(); function computeAttributeFromIndexedData(coordIndex, index, data2, itemSize) { const array = []; for (let i = 0, l = coordIndex.length; i < l; i += 3) { const a = index[i]; const b = index[i + 1]; const c = index[i + 2]; if (itemSize === 2) { uvA.fromArray(data2, a * itemSize); uvB.fromArray(data2, b * itemSize); uvC.fromArray(data2, c * itemSize); array.push(uvA.x, uvA.y); array.push(uvB.x, uvB.y); array.push(uvC.x, uvC.y); } else { vA.fromArray(data2, a * itemSize); vB.fromArray(data2, b * itemSize); vC.fromArray(data2, c * itemSize); array.push(vA.x, vA.y, vA.z); array.push(vB.x, vB.y, vB.z); array.push(vC.x, vC.y, vC.z); } } return new Float32BufferAttribute(array, itemSize); } function computeAttributeFromFaceData(index, faceData) { const array = []; for (let i = 0, j = 0, l = index.length; i < l; i += 3, j++) { vA.fromArray(faceData, j * 3); array.push(vA.x, vA.y, vA.z); array.push(vA.x, vA.y, vA.z); array.push(vA.x, vA.y, vA.z); } return new Float32BufferAttribute(array, 3); } function computeAttributeFromLineData(index, lineData) { const array = []; for (let i = 0, j = 0, l = index.length; i < l; i += 2, j++) { vA.fromArray(lineData, j * 3); array.push(vA.x, vA.y, vA.z); array.push(vA.x, vA.y, vA.z); } return new Float32BufferAttribute(array, 3); } function toNonIndexedAttribute(indices, attribute) { const array = attribute.array; const itemSize = attribute.itemSize; const array2 = new array.constructor(indices.length * itemSize); let index = 0, index2 = 0; for (let i = 0, l = indices.length; i < l; i++) { index = indices[i] * itemSize; for (let j = 0; j < itemSize; j++) array2[index2++] = array[index++]; } return new Float32BufferAttribute(array2, itemSize); } const ab = new Vector3(); const cb = new Vector3(); function computeNormalAttribute(index, coord, creaseAngle) { const faces = []; const vertexNormals = {}; for (let i = 0, l = index.length; i < l; i += 3) { const a = index[i]; const b = index[i + 1]; const c = index[i + 2]; const face = new Face(a, b, c); vA.fromArray(coord, a * 3); vB.fromArray(coord, b * 3); vC.fromArray(coord, c * 3); cb.subVectors(vC, vB); ab.subVectors(vA, vB); cb.cross(ab); cb.normalize(); face.normal.copy(cb); if (vertexNormals[a] === void 0) vertexNormals[a] = []; if (vertexNormals[b] === void 0) vertexNormals[b] = []; if (vertexNormals[c] === void 0) vertexNormals[c] = []; vertexNormals[a].push(face.normal); vertexNormals[b].push(face.normal); vertexNormals[c].push(face.normal); faces.push(face); } const normals = []; for (let i = 0, l = faces.length; i < l; i++) { const face = faces[i]; const nA = weightedNormal(vertexNormals[face.a], face.normal, creaseAngle); const nB = weightedNormal(vertexNormals[face.b], face.normal, creaseAngle); const nC = weightedNormal(vertexNormals[face.c], face.normal, creaseAngle); vA.fromArray(coord, face.a * 3); vB.fromArray(coord, face.b * 3); vC.fromArray(coord, face.c * 3); normals.push(nA.x, nA.y, nA.z); normals.push(nB.x, nB.y, nB.z); normals.push(nC.x, nC.y, nC.z); } return new Float32BufferAttribute(normals, 3); } function weightedNormal(normals, vector, creaseAngle) { const normal = new Vector3(); if (creaseAngle === 0) normal.copy(vector); else for (let i = 0, l = normals.length; i < l; i++) if (normals[i].angleTo(vector) < creaseAngle) normal.add(normals[i]); return normal.normalize(); } function toColorArray(colors) { const array = []; for (let i = 0, l = colors.length; i < l; i += 3) array.push(new Color(colors[i], colors[i + 1], colors[i + 2])); return array; } function paintFaces(geometry, radius, angles, colors, topDown) { const thresholds = []; const startAngle = topDown === true ? 0 : Math.PI; for (let i = 0, l = colors.length; i < l; i++) { let angle = i === 0 ? 0 : angles[i - 1]; angle = topDown === true ? angle : startAngle - angle; const point = new Vector3(); point.setFromSphericalCoords(radius, angle, 0); thresholds.push(point); } const indices = geometry.index; const positionAttribute = geometry.attributes.position; const colorAttribute = new BufferAttribute(new Float32Array(geometry.attributes.position.count * 3), 3); const position = new Vector3(); const color = new Color(); for (let i = 0; i < indices.count; i++) { const index = indices.getX(i); position.fromBufferAttribute(positionAttribute, index); let thresholdIndexA, thresholdIndexB; let t = 1; for (let j = 1; j < thresholds.length; j++) { thresholdIndexA = j - 1; thresholdIndexB = j; const thresholdA = thresholds[thresholdIndexA]; const thresholdB = thresholds[thresholdIndexB]; if (topDown === true) { if (position.y <= thresholdA.y && position.y > thresholdB.y) { t = Math.abs(thresholdA.y - position.y) / Math.abs(thresholdA.y - thresholdB.y); break; } } else if (position.y >= thresholdA.y && position.y < thresholdB.y) { t = Math.abs(thresholdA.y - position.y) / Math.abs(thresholdA.y - thresholdB.y); break; } } const colorA = colors[thresholdIndexA]; const colorB = colors[thresholdIndexB]; color.copy(colorA).lerp(colorB, t); colorAttribute.setXYZ(index, color.r, color.g, color.b); } geometry.setAttribute("color", colorAttribute); } const textureLoader = new TextureLoader(this.manager); textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin); if (data.indexOf("#VRML V2.0") === -1) throw Error("THREE.VRMLLexer: Version of VRML asset not supported."); return parseTree(generateVRMLTree(data)); } }; var VRMLLexer = class { constructor(tokens) { this.lexer = new Lexer(tokens); } lex(inputText) { const lexingResult = this.lexer.tokenize(inputText); if (lexingResult.errors.length > 0) { console.error(lexingResult.errors); throw Error("THREE.VRMLLexer: Lexing errors detected."); } return lexingResult; } }; var VRMLParser = class extends CstParser { constructor(tokenVocabulary) { super(tokenVocabulary); const $ = this; const Version = tokenVocabulary["Version"]; const LCurly = tokenVocabulary["LCurly"]; const RCurly = tokenVocabulary["RCurly"]; const LSquare = tokenVocabulary["LSquare"]; const RSquare = tokenVocabulary["RSquare"]; const Identifier = tokenVocabulary["Identifier"]; const RouteIdentifier = tokenVocabulary["RouteIdentifier"]; const StringLiteral = tokenVocabulary["StringLiteral"]; const HexLiteral = tokenVocabulary["HexLiteral"]; const NumberLiteral = tokenVocabulary["NumberLiteral"]; const TrueLiteral = tokenVocabulary["TrueLiteral"]; const FalseLiteral = tokenVocabulary["FalseLiteral"]; const NullLiteral = tokenVocabulary["NullLiteral"]; const DEF = tokenVocabulary["DEF"]; const USE = tokenVocabulary["USE"]; const ROUTE = tokenVocabulary["ROUTE"]; const TO = tokenVocabulary["TO"]; const NodeName = tokenVocabulary["NodeName"]; $.RULE("vrml", function() { $.SUBRULE($.version); $.AT_LEAST_ONE(function() { $.SUBRULE($.node); }); $.MANY(function() { $.SUBRULE($.route); }); }); $.RULE("version", function() { $.CONSUME(Version); }); $.RULE("node", function() { $.OPTION(function() { $.SUBRULE($.def); }); $.CONSUME(NodeName); $.CONSUME(LCurly); $.MANY(function() { $.SUBRULE($.field); }); $.CONSUME(RCurly); }); $.RULE("field", function() { $.CONSUME(Identifier); $.OR2([{ ALT: function() { $.SUBRULE($.singleFieldValue); } }, { ALT: function() { $.SUBRULE($.multiFieldValue); } }]); }); $.RULE("def", function() { $.CONSUME(DEF); $.OR([{ ALT: function() { $.CONSUME(Identifier); } }, { ALT: function() { $.CONSUME(NodeName); } }]); }); $.RULE("use", function() { $.CONSUME(USE); $.OR([{ ALT: function() { $.CONSUME(Identifier); } }, { ALT: function() { $.CONSUME(NodeName); } }]); }); $.RULE("singleFieldValue", function() { $.AT_LEAST_ONE(function() { $.OR([ { ALT: function() { $.SUBRULE($.node); } }, { ALT: function() { $.SUBRULE($.use); } }, { ALT: function() { $.CONSUME(StringLiteral); } }, { ALT: function() { $.CONSUME(HexLiteral); } }, { ALT: function() { $.CONSUME(NumberLiteral); } }, { ALT: function() { $.CONSUME(TrueLiteral); } }, { ALT: function() { $.CONSUME(FalseLiteral); } }, { ALT: function() { $.CONSUME(NullLiteral); } } ]); }); }); $.RULE("multiFieldValue", function() { $.CONSUME(LSquare); $.MANY(function() { $.OR([ { ALT: function() { $.SUBRULE($.node); } }, { ALT: function() { $.SUBRULE($.use); } }, { ALT: function() { $.CONSUME(StringLiteral); } }, { ALT: function() { $.CONSUME(HexLiteral); } }, { ALT: function() { $.CONSUME(NumberLiteral); } }, { ALT: function() { $.CONSUME(NullLiteral); } } ]); }); $.CONSUME(RSquare); }); $.RULE("route", function() { $.CONSUME(ROUTE); $.CONSUME(RouteIdentifier); $.CONSUME(TO); $.CONSUME2(RouteIdentifier); }); this.performSelfAnalysis(); } }; var Face = class { constructor(a, b, c) { this.a = a; this.b = b; this.c = c; this.normal = new Vector3(); } }; var TEXTURE_TYPE = { INTENSITY: 1, INTENSITY_ALPHA: 2, RGB: 3, RGBA: 4 }; //#endregion //#region 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 i = 0; i < this.pool; i++) if (!(this.workerStatus & 1 << i)) return i; return -1; } _onMessage(workerId, msg) { const resolve = this.workersResolve[workerId]; resolve && resolve(msg); if (this.queue.length) { const { resolve: resolve2, msg: msg2, transfer } = this.queue.shift(); this.workersResolve[workerId] = resolve2; this.workers[workerId].postMessage(msg2, transfer); } else this.workerStatus ^= 1 << workerId; } 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; } }; var KTX2Container = class { constructor() { this.vkFormat = 0; this.typeSize = 1; this.pixelWidth = 0; this.pixelHeight = 0; this.pixelDepth = 0; this.layerCount = 0; this.faceCount = 1; this.supercompressionScheme = 0; this.levels = []; this.dataFormatDescriptor = [{ vendorId: 0, descriptorType: 0, descriptorBlockSize: 0, versionNumber: 2, colorModel: 0, colorPrimaries: 1, transferFunction: 2, flags: 0, texelBlockDimension: [ 0, 0, 0, 0 ], bytesPlane: [ 0, 0, 0, 0, 0, 0, 0, 0 ], samples: [] }]; this.keyValue = {}; this.globalData = null; } }; var 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 value = this._dataView.getUint32(this._offset, this._littleEndian) + 2 ** 32 * this._dataView.getUint32(this._offset + 4, this._littleEndian); 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 = [ 171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10 ]; function decodeText(buffer) { if (typeof TextDecoder !== "undefined") return new TextDecoder().decode(buffer); return Buffer.from(buffer).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] || id[2] !== KTX2_ID[2] || id[3] !== KTX2_ID[3] || id[4] !== KTX2_ID[4] || id[5] !== KTX2_ID[5] || id[6] !== KTX2_ID[6] || id[7] !== KTX2_ID[7] || id[8] !== KTX2_ID[8] || id[9] !== KTX2_ID[9] || id[10] !== KTX2_ID[10] || 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 i = 0; i < levelCount; i++) 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)._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 numSamples = (dfd.descriptorBlockSize / 4 - 6) / 4; for (let i = 0; i < numSamples; i++) { 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 & 64) { sample.sampleLower = dfdReader._nextInt32(); sample.sampleUpper = dfdReader._nextInt32(); } else { sample.sampleLower = dfdReader._nextUint32(); sample.sampleUpper = dfdReader._nextUint32(); } dfd.samples[i] = 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 = decodeText(keyData); container.keyValue[key] = kvdReader._nextUint8Array(keyValueByteLength - keyData.byteLength - 1); if (key.match(/^ktx/i)) { const text = decodeText(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 i = 0; i < levelCount; i++) 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; container.globalData = { endpointCount, selectorCount, imageDescs, endpointsData: new Uint8Array(data.buffer, data.byteOffset + endpointsByteOffset, endpointsByteLength), selectorsData: new Uint8Array(data.buffer, data.byteOffset + selectorsByteOffset, selectorsByteLength), tablesData: new Uint8Array(data.buffer, data.byteOffset + tablesByteOffset, tablesByteLength), extendedData: new Uint8Array(data.buffer, data.byteOffset + extendedByteOffset, extendedByteLength) }; return container; } //#endregion //#region node_modules/three-stdlib/libs/zstddec.js var init$1; var instance; var heap; var IMPORT_OBJECT = { env: { emscripten_notify_memory_growth: function(index) { heap = new Uint8Array(instance.exports.memory.buffer); } } }; var ZSTDDecoder = class { init() { if (init$1) return init$1; if (typeof fetch !== "undefined") init$1 = fetch("data:application/wasm;base64," + wasm).then((response) => response.arrayBuffer()).then((arrayBuffer) => WebAssembly.instantiate(arrayBuffer, IMPORT_OBJECT)).then(this._init); else init$1 = WebAssembly.instantiate(Buffer.from(wasm, "base64"), IMPORT_OBJECT).then(this._init); return init$1; } _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"; //#endregion //#region 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, 301); this.isCompressedCubeTexture = true; this.isCubeTexture = true; this.image = images; } }; //#endregion //#region 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; } }; //#endregion //#region node_modules/three-stdlib/loaders/KTX2Loader.js var __defProp$2 = Object.defineProperty; var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$2 = (obj, key, value) => { __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var LinearEncoding = 3e3; var sRGBEncoding = 3001; var NoColorSpace = ""; var DisplayP3ColorSpace = "display-p3"; var LinearDisplayP3ColorSpace = "display-p3-linear"; var LinearSRGBColorSpace = "srgb-linear"; var SRGBColorSpace = "srgb"; var _taskCache$3 = /* @__PURE__ */ new WeakMap(); var _activeLoaders = 0; var _zstd; var KTX2Loader = /* @__PURE__ */ (() => { 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 loader = new FileLoader(this.manager); loader.setResponseType("arraybuffer"); loader.setWithCredentials(this.withCredentials); loader.load(url, (buffer) => { if (_taskCache$3.has(buffer)) return _taskCache$3.get(buffer).promise.then(onLoad).catch(onError); this._createTexture(buffer).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 === SRGBColorSpace ? sRGBEncoding : LinearEncoding; texture.premultiplyAlpha = !!(dfdFlags & 1); return texture; } /** * @param {ArrayBuffer} buffer * @param {object?} config * @return {Promise} */ async _createTexture(buffer, config = {}) { const container = read(new Uint8Array(buffer)); if (container.vkFormat !== 0) return createRawTexture(container); const taskConfig = config; const texturePending = this.init().then(() => { return this.workerPool.postMessage({ type: "transcode", buffer, taskConfig }, [buffer]); }).then((e) => this._createTextureFrom(e.data, container)); _taskCache$3.set(buffer, { promise: texturePending }); return texturePending; } dispose() { this.workerPool.dispose(); if (this.workerSourceURL) URL.revokeObjectURL(this.workerSourceURL); _activeLoaders--; return this; } }; let KTX2Loader2 = _KTX2Loader; __publicField$2(KTX2Loader2, "BasisFormat", { ETC1S: 0, UASTC_4x4: 1 }); __publicField$2(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 }); __publicField$2(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 }); __publicField$2(KTX2Loader2, "BasisWorker", function() { let config; let transcoderPending; let BasisModule; const EngineFormat = _EngineFormat; const TranscoderFormat = _TranscoderFormat; const BasisFormat = _BasisFormat; self.addEventListener("message", function(e) { const message = e.data; switch (message.type) { case "init": config = message.config; init(message.transcoderBinary); break; case "transcode": transcoderPending.then(() => { try { const { faces, buffers, width, 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 init(wasmBinary) { transcoderPending = new Promise((resolve) => { BasisModule = { wasmBinary, onRuntimeInitialized: resolve }; BASIS(BasisModule); }).then(() => { BasisModule.initializeBasis(); if (BasisModule.KTX2File === void 0) console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder."); }); } function transcode(buffer) { const ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer)); function cleanup() { ktx2File.close(); ktx2File.delete(); } if (!ktx2File.isValid()) { cleanup(); throw new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file"); } 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)); if (!ktx2File.transcodeImage(dst, mip, layer, face, transcoderFormat, 0, -1, -1)) { 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(a, b) { return a.priorityETC1S - b.priorityETC1S; }); const UASTC_OPTIONS = FORMAT_OPTIONS.sort(function(a, b) { return a.priorityUASTC - b.priorityUASTC; }); function getTranscoderFormat(basisFormat, width, height, hasAlpha) { let transcoderFormat; let engineFormat; const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; for (let i = 0; i < options.length; i++) { const opt = options[i]; 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 i = 0; i < arrays.length; i++) { const array = arrays[i]; totalByteLength += array.byteLength; } const result = new Uint8Array(totalByteLength); let byteOffset = 0; for (let i = 0; i < arrays.length; i++) { const array = arrays[i]; result.set(array, byteOffset); byteOffset += array.byteLength; } return result; } }); return KTX2Loader2; })(); var UNCOMPRESSED_FORMATS = /* @__PURE__ */ new Set([ RGBAFormat, RGFormat, RedFormat ]); var FORMAT_MAP = { [109]: RGBAFormat, [97]: RGBAFormat, [37]: RGBAFormat, [43]: RGBAFormat, [103]: RGFormat, [83]: RGFormat, [16]: RGFormat, [22]: RGFormat, [100]: RedFormat, [76]: RedFormat, [15]: RedFormat, [9]: RedFormat, [166]: RGBA_ASTC_6x6_Format, [165]: RGBA_ASTC_6x6_Format }; var TYPE_MAP = { [109]: FloatType, [97]: HalfFloatType, [37]: UnsignedByteType, [43]: UnsignedByteType, [103]: FloatType, [83]: HalfFloatType, [16]: UnsignedByteType, [22]: UnsignedByteType, [100]: FloatType, [76]: HalfFloatType, [15]: UnsignedByteType, [9]: UnsignedByteType, [166]: UnsignedByteType, [165]: 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 === 2) { 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 === 0) levelData = level.levelData; else if (container.supercompressionScheme === 2) levelData = zstd.decode(level.levelData, level.uncompressedByteLength); else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme."); let data; if (TYPE_MAP[vkFormat] === 1015) data = new Float32Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Float32Array.BYTES_PER_ELEMENT); else if (TYPE_MAP[vkFormat] === 1016) 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 === SRGBColorSpace ? sRGBEncoding : LinearEncoding; return Promise.resolve(texture); } function parseColorSpace(container) { const dfd = container.dataFormatDescriptor[0]; if (dfd.colorPrimaries === 1) return dfd.transferFunction === 2 ? SRGBColorSpace : LinearSRGBColorSpace; else if (dfd.colorPrimaries === 10) return dfd.transferFunction === 2 ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace; else if (dfd.colorPrimaries === 0) return NoColorSpace; else { console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${dfd.colorPrimaries}"`); return NoColorSpace; } } //#endregion //#region node_modules/three-stdlib/libs/lottie.js var lottie = /* @__PURE__ */ (() => { 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 i; var len = sources.length; var sourcePrototype; for (i = 0; i < len; i += 1) { sourcePrototype = sources[i].prototype; for (var attr in sourcePrototype) if (Object.prototype.hasOwnProperty.call(sourcePrototype, attr)) destination.prototype[attr] = sourcePrototype[attr]; } } function getDescriptor(object, prop) { return Object.getOwnPropertyDescriptor(object, prop); } function createProxyFunction(prototype) { function ProxyFunction() {} ProxyFunction.prototype = prototype; return ProxyFunction; } const audioControllerFactory = function() { function AudioController(audioFactory) { this.audios = []; this.audioFactory = audioFactory; this._volume = 1; this._isMuted = false; } AudioController.prototype = { addAudio: function(audio) { this.audios.push(audio); }, pause: function() { var i; var len = this.audios.length; for (i = 0; i < len; i += 1) this.audios[i].pause(); }, resume: function() { var i; var len = this.audios.length; for (i = 0; i < len; i += 1) this.audios[i].resume(); }, setRate: function(rateValue) { var i; var len = this.audios.length; for (i = 0; i < len; i += 1) this.audios[i].setRate(rateValue); }, createAudio: function(assetPath) { if (this.audioFactory) return this.audioFactory(assetPath); if (window.Howl) return new window.Howl({ src: [assetPath] }); return { isPlaying: false, play: function() { this.isPlaying = true; }, seek: function() { this.isPlaying = false; }, playing: function() {}, rate: function() {}, setVolume: function() {} }; }, setAudioFactory: function(audioFactory) { this.audioFactory = audioFactory; }, setVolume: function(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 i; var len = this.audios.length; for (i = 0; i < len; i += 1) this.audios[i].volume(this._volume * (this._isMuted ? 0 : 1)); } }; return function() { return new AudioController(); }; }(); const createTypedArray = function() { function createRegularArray(type, len) { var i = 0; var arr = []; var value; switch (type) { case "int16": case "uint8c": value = 1; break; default: value = 1.1; break; } for (i = 0; i < len; i += 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 i; var len = propertyNames.length; for (i = 0; i < len; i += 1) BMMath[propertyNames[i]] = Math[propertyNames[i]]; })(); BMMath.random = Math.random; BMMath.abs = function(val) { if (typeof val === "object" && val.length) { var absArr = createSizedArray(val.length); var i; var len = val.length; for (i = 0; i < len; i += 1) absArr[i] = Math.abs(val[i]); return absArr; } return Math.abs(val); }; let defaultCurveSegments = 150; const degToRads = Math.PI / 180; const roundCorner = .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, target) { this.type = type; this.target = target; } function BMRenderFrameErrorEvent(nativeError, currentTime) { this.type = "renderFrameError"; this.nativeError = nativeError; this.currentTime = currentTime; } function BMConfigErrorEvent(nativeError) { this.type = "configError"; this.nativeError = nativeError; } const createElementID = function() { var _count = 0; return function createID() { _count += 1; return idPrefix$1 + "__lottie_element_" + _count; }; }(); function HSVtoRGB(h, s, v) { var r; var g; var b; var i; var f; var p; var q; var t; i = Math.floor(h * 6); f = h * 6 - i; p = v * (1 - s); q = v * (1 - f * s); t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; case 5: r = v; g = p; b = q; break; } return [ r, g, b ]; } function RGBtoHSV(r, g, b) { var max = Math.max(r, g, b); var min = Math.min(r, g, b); var d = max - min; var h; var s = max === 0 ? 0 : d / max; var v = max / 255; switch (max) { case min: h = 0; break; case r: h = g - b + d * (g < b ? 6 : 0); h /= 6 * d; break; case g: h = b - r + d * 2; h /= 6 * d; break; case b: h = r - g + d * 4; h /= 6 * d; break; } return [ h, s, v ]; } function addSaturationToRGB(color, offset) { var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); hsv[1] += offset; if (hsv[1] > 1) hsv[1] = 1; else if (hsv[1] <= 0) hsv[1] = 0; return HSVtoRGB(hsv[0], hsv[1], hsv[2]); } function addBrightnessToRGB(color, offset) { var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); hsv[2] += offset; if (hsv[2] > 1) hsv[2] = 1; else if (hsv[2] < 0) hsv[2] = 0; return HSVtoRGB(hsv[0], hsv[1], hsv[2]); } function addHueToRGB(color, offset) { var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); hsv[0] += offset / 360; if (hsv[0] > 1) hsv[0] -= 1; else if (hsv[0] < 0) hsv[0] += 1; return HSVtoRGB(hsv[0], hsv[1], hsv[2]); } (function() { var colorMap = []; var i; var hex; for (i = 0; i < 256; i += 1) { hex = i.toString(16); colorMap[i] = hex.length === 1 ? "0" + hex : hex; } return function(r, g, b) { if (r < 0) r = 0; if (g < 0) g = 0; if (b < 0) b = 0; return "#" + colorMap[r] + colorMap[g] + colorMap[b]; }; })(); 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 = 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 createWorker(fn) { if (window.Worker && window.Blob && getWebWorker()) { var blob = new Blob(["var _workerSelf = self; self.onmessage = ", fn.toString()], { type: "text/javascript" }); var url = URL.createObjectURL(blob); return new Worker(url); } workerFn = fn; return workerProxy; } function setupWorker() { if (!workerInstance) { workerInstance = createWorker(function workerStart(e) { function dataFunctionManager() { function completeLayers(layers, comps) { var layerData; var i; var len = layers.length; var j; var jLen; var k; var kLen; for (i = 0; i < len; i += 1) { layerData = layers[i]; if ("ks" in layerData && !layerData.completed) { layerData.completed = true; if (layerData.tt) layers[i - 1].td = layerData.tt; if (layerData.hasMask) { var maskProps = layerData.masksProperties; jLen = maskProps.length; for (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 i = 0; var len = chars.length; for (i = 0; i < len; i += 1) if (chars[i].t === 1) { chars[i].data.layers = findCompLayers(chars[i].data.refId, assets); completeLayers(chars[i].data.layers, assets); } } } function findComp(id, comps) { var i = 0; var len = comps.length; while (i < len) { if (comps[i].id === id) return comps[i]; i += 1; } return null; } function findCompLayers(id, comps) { var 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 i; var len = arr.length; var j; var jLen; for (i = len - 1; i >= 0; i -= 1) if (arr[i].ty === "sh") if (arr[i].ks.k.i) convertPathsToAbsoluteValues(arr[i].ks.k); else { jLen = arr[i].ks.k.length; for (j = 0; j < jLen; j += 1) { if (arr[i].ks.k[j].s) convertPathsToAbsoluteValues(arr[i].ks.k[j].s[0]); if (arr[i].ks.k[j].e) convertPathsToAbsoluteValues(arr[i].ks.k[j].e[0]); } } else if (arr[i].ty === "gr") completeShapes(arr[i].it); } function convertPathsToAbsoluteValues(path) { var i; var len = path.i.length; for (i = 0; i < len; i += 1) { path.i[i][0] += path.v[i][0]; path.i[i][1] += path.v[i][1]; path.o[i][0] += path.v[i][0]; path.o[i][1] += path.v[i][1]; } } function checkVersion(minimum, animVersionString) { var animVersion = animVersionString ? animVersionString.split(".") : [ 100, 100, 100 ]; if (minimum[0] > animVersion[0]) return true; if (animVersion[0] > minimum[0]) return false; if (minimum[1] > animVersion[1]) return true; if (animVersion[1] > minimum[1]) return false; if (minimum[2] > animVersion[2]) return true; if (animVersion[2] > minimum[2]) return false; return null; } var checkText = function() { var minimumVersion = [ 4, 4, 14 ]; function updateTextLayer(textLayer) { var documentData = textLayer.t.d; textLayer.t.d = { k: [{ s: documentData, t: 0 }] }; } function iterateLayers(layers) { var i; var len = layers.length; for (i = 0; i < len; i += 1) if (layers[i].ty === 5) updateTextLayer(layers[i]); } return function(animationData) { if (checkVersion(minimumVersion, animationData.v)) { iterateLayers(animationData.layers); if (animationData.assets) { var i; var len = animationData.assets.length; for (i = 0; i < len; i += 1) if (animationData.assets[i].layers) iterateLayers(animationData.assets[i].layers); } } }; }(); var checkChars = function() { var minimumVersion = [ 4, 7, 99 ]; return function(animationData) { if (animationData.chars && !checkVersion(minimumVersion, animationData.v)) { var i; var len = animationData.chars.length; for (i = 0; i < len; i += 1) { var charData = animationData.chars[i]; if (charData.data && charData.data.shapes) { completeShapes(charData.data.shapes); charData.data.ip = 0; charData.data.op = 99999; charData.data.st = 0; charData.data.sr = 1; charData.data.ks = { p: { k: [0, 0], a: 0 }, s: { k: [100, 100], a: 0 }, a: { k: [0, 0], a: 0 }, r: { k: 0, a: 0 }, o: { k: 100, a: 0 } }; if (!animationData.chars[i].t) { charData.data.shapes.push({ ty: "no" }); charData.data.shapes[0].it.push({ p: { k: [0, 0], a: 0 }, s: { k: [100, 100], a: 0 }, a: { k: [0, 0], a: 0 }, r: { k: 0, a: 0 }, o: { k: 100, a: 0 }, sk: { k: 0, a: 0 }, sa: { k: 0, a: 0 }, ty: "tr" }); } } } } }; }(); var checkPathProperties = function() { var minimumVersion = [ 5, 7, 15 ]; function updateTextLayer(textLayer) { var pathData = textLayer.t.p; if (typeof pathData.a === "number") pathData.a = { a: 0, k: pathData.a }; if (typeof pathData.p === "number") pathData.p = { a: 0, k: pathData.p }; if (typeof pathData.r === "number") pathData.r = { a: 0, k: pathData.r }; } function iterateLayers(layers) { var i; var len = layers.length; for (i = 0; i < len; i += 1) if (layers[i].ty === 5) updateTextLayer(layers[i]); } return function(animationData) { if (checkVersion(minimumVersion, animationData.v)) { iterateLayers(animationData.layers); if (animationData.assets) { var i; var len = animationData.assets.length; for (i = 0; i < len; i += 1) if (animationData.assets[i].layers) iterateLayers(animationData.assets[i].layers); } } }; }(); var checkColors = function() { var minimumVersion = [ 4, 1, 9 ]; function iterateShapes(shapes) { var i; var len = shapes.length; var j; var jLen; for (i = 0; i < len; i += 1) if (shapes[i].ty === "gr") iterateShapes(shapes[i].it); else if (shapes[i].ty === "fl" || shapes[i].ty === "st") if (shapes[i].c.k && shapes[i].c.k[0].i) { jLen = shapes[i].c.k.length; for (j = 0; j < jLen; j += 1) { if (shapes[i].c.k[j].s) { shapes[i].c.k[j].s[0] /= 255; shapes[i].c.k[j].s[1] /= 255; shapes[i].c.k[j].s[2] /= 255; shapes[i].c.k[j].s[3] /= 255; } if (shapes[i].c.k[j].e) { shapes[i].c.k[j].e[0] /= 255; shapes[i].c.k[j].e[1] /= 255; shapes[i].c.k[j].e[2] /= 255; shapes[i].c.k[j].e[3] /= 255; } } } else { shapes[i].c.k[0] /= 255; shapes[i].c.k[1] /= 255; shapes[i].c.k[2] /= 255; shapes[i].c.k[3] /= 255; } } function iterateLayers(layers) { var i; var len = layers.length; for (i = 0; i < len; i += 1) if (layers[i].ty === 4) iterateShapes(layers[i].shapes); } return function(animationData) { if (checkVersion(minimumVersion, animationData.v)) { iterateLayers(animationData.layers); if (animationData.assets) { var i; var len = animationData.assets.length; for (i = 0; i < len; i += 1) if (animationData.assets[i].layers) iterateLayers(animationData.assets[i].layers); } } }; }(); var checkShapes = function() { var minimumVersion = [ 4, 4, 18 ]; function completeClosingShapes(arr) { var i; var len = arr.length; var j; var jLen; for (i = len - 1; i >= 0; i -= 1) if (arr[i].ty === "sh") if (arr[i].ks.k.i) arr[i].ks.k.c = arr[i].closed; else { jLen = arr[i].ks.k.length; for (j = 0; j < jLen; j += 1) { if (arr[i].ks.k[j].s) arr[i].ks.k[j].s[0].c = arr[i].closed; if (arr[i].ks.k[j].e) arr[i].ks.k[j].e[0].c = arr[i].closed; } } else if (arr[i].ty === "gr") completeClosingShapes(arr[i].it); } function iterateLayers(layers) { var layerData; var i; var len = layers.length; var j; var jLen; var k; var kLen; for (i = 0; i < len; i += 1) { layerData = layers[i]; 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 i; var len = animationData.assets.length; for (i = 0; i < len; i += 1) if (animationData.assets[i].layers) iterateLayers(animationData.assets[i].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 = 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 (e.data.type === "loadAnimation") _workerSelf.assetLoader.load(e.data.path, e.data.fullPath, function(data) { _workerSelf.dataManager.completeData(data); _workerSelf.postMessage({ id: e.data.id, payload: data, status: "success" }); }, function() { _workerSelf.postMessage({ id: e.data.id, status: "error" }); }); else if (e.data.type === "complete") { var animation = e.data.animation; _workerSelf.dataManager.completeData(animation); _workerSelf.postMessage({ id: e.data.id, payload: animation, status: "success" }); } else if (e.data.type === "loadData") _workerSelf.assetLoader.load(e.data.path, e.data.fullPath, function(data) { _workerSelf.postMessage({ id: e.data.id, payload: data, status: "success" }); }, function() { _workerSelf.postMessage({ id: e.data.id, status: "error" }); }); }); workerInstance.onmessage = function(event) { var data = event.data; var id = data.id; var process = processes[id]; processes[id] = null; if (data.status === "success") process.onComplete(data.payload); else if (process.onError) process.onError(); }; } } function createProcess(onComplete, onError) { _counterId += 1; var id = "processId_" + _counterId; processes[id] = { onComplete, onError }; return id; } function loadAnimation2(path, onComplete, onError) { setupWorker(); var processId = createProcess(onComplete, onError); workerInstance.postMessage({ type: "loadAnimation", path, fullPath: window.location.origin + window.location.pathname, id: processId }); } function loadData(path, onComplete, onError) { setupWorker(); var processId = createProcess(onComplete, onError); workerInstance.postMessage({ type: "loadData", path, fullPath: window.location.origin + window.location.pathname, id: processId }); } function completeAnimation(anim, onComplete, onError) { setupWorker(); var processId = createProcess(onComplete, onError); workerInstance.postMessage({ type: "complete", animation: anim, id: processId }); } return { loadAnimation: loadAnimation2, loadData, completeAnimation }; }(); const ImagePreloader = function() { var proxyImage = function() { var canvas = createTag("canvas"); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgba(0,0,0,0)"; ctx.fillRect(0, 0, 1, 1); return canvas; }(); function imageLoaded() { this.loadedAssets += 1; if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { if (this.imagesLoadedCb) this.imagesLoadedCb(null); } } function footageLoaded() { this.loadedFootagesCount += 1; if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { if (this.imagesLoadedCb) this.imagesLoadedCb(null); } } function getAssetsPath(assetData, assetsPath, originalPath) { var path = ""; if (assetData.e) path = assetData.p; else if (assetsPath) { var imagePath = assetData.p; if (imagePath.indexOf("images/") !== -1) imagePath = imagePath.split("/")[1]; path = assetsPath + imagePath; } else { path = originalPath; path += assetData.u ? assetData.u : ""; path += assetData.p; } return path; } function testImageLoaded(img) { var _count = 0; var intervalId = setInterval(function() { if (img.getBBox().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, cb) { this.imagesLoadedCb = cb; var i; var len = assets.length; for (i = 0; i < len; i += 1) if (!assets[i].layers) { if (!assets[i].t || assets[i].t === "seq") { this.totalImages += 1; this.images.push(this._createImageData(assets[i])); } else if (assets[i].t === 3) { this.totalFootages += 1; this.images.push(this.createFootageData(assets[i])); } } } function setPath(path) { this.path = path || ""; } function setAssetsPath(path) { this.assetsPath = path || ""; } function getAsset(assetData) { var i = 0; var len = this.images.length; while (i < len) { if (this.images[i].assetData === assetData) return this.images[i].img; i += 1; } return null; } function destroy() { this.imagesLoadedCb = null; this.images.length = 0; } function loadedImages() { return this.totalImages === this.loadedAssets; } function loadedFootages() { return this.totalFootages === this.loadedFootagesCount; } function setCacheType(type, elementHelper) { if (type === "svg") { this._elementHelper = elementHelper; this._createImageData = this.createImageData.bind(this); } else this._createImageData = this.createImgData.bind(this); } function ImagePreloaderFactory() { this._imageLoaded = imageLoaded.bind(this); this._footageLoaded = footageLoaded.bind(this); this.testImageLoaded = testImageLoaded.bind(this); this.createFootageData = createFootageData.bind(this); this.assetsPath = ""; this.path = ""; this.totalImages = 0; this.totalFootages = 0; this.loadedAssets = 0; this.loadedFootagesCount = 0; this.imagesLoadedCb = null; this.images = []; } ImagePreloaderFactory.prototype = { loadAssets, setAssetsPath, setPath, loadedImages, loadedFootages, destroy, getAsset, createImgData, createImageData, imageLoaded, footageLoaded, setCacheType }; return ImagePreloaderFactory; }(); function BaseEvent() {} BaseEvent.prototype = { triggerEvent: function(eventName, args) { if (this._cbs[eventName]) { var callbacks = this._cbs[eventName]; for (var i = 0; i < callbacks.length; i += 1) callbacks[i](args); } }, addEventListener: function(eventName, callback) { if (!this._cbs[eventName]) this._cbs[eventName] = []; this._cbs[eventName].push(callback); return function() { this.removeEventListener(eventName, callback); }.bind(this); }, removeEventListener: function(eventName, callback) { if (!callback) this._cbs[eventName] = null; else if (this._cbs[eventName]) { var i = 0; var len = this._cbs[eventName].length; while (i < len) { if (this._cbs[eventName][i] === callback) { this._cbs[eventName].splice(i, 1); i -= 1; len -= 1; } i += 1; } if (!this._cbs[eventName].length) this._cbs[eventName] = null; } } }; const markerParser = function() { function parsePayloadLines(payload) { var lines = payload.split("\r\n"); var keys = {}; var line; var keysCount = 0; for (var i = 0; i < lines.length; i += 1) { line = lines[i].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 i = 0; i < _markers.length; i += 1) { var _marker = _markers[i]; var markerData = { time: _marker.tm, duration: _marker.dr }; try { markerData.payload = JSON.parse(_markers[i].cm); } catch (_) { try { markerData.payload = parsePayloadLines(_markers[i].cm); } catch (__) { markerData.payload = { name: _markers[i].cm }; } } markers.push(markerData); } return markers; }; }(); const ProjectInterface = function() { function registerComposition(comp) { this.compositions.push(comp); } return function() { function _thisProjectFunction(name) { var i = 0; var len = this.compositions.length; while (i < len) { if (this.compositions[i].data && this.compositions[i].data.nm === name) { if (this.compositions[i].prepareFrame && this.compositions[i].data.xt) this.compositions[i].prepareFrame(this.currentFrame); return this.compositions[i].compInterface; } i += 1; } return null; } _thisProjectFunction.compositions = []; _thisProjectFunction.currentFrame = 0; _thisProjectFunction.registerComposition = registerComposition; return _thisProjectFunction; }; }(); const renderers = {}; const registerRenderer = (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); params.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) !== "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 : ""; if ((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 : "") === "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 i; var len = layers.length; var newLayers = data.layers; var j; var jLen = newLayers.length; for (j = 0; j < jLen; j += 1) { i = 0; while (i < len) { if (layers[i].id === newLayers[j].id) { layers[i] = newLayers[j]; break; } i += 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 (i = 0; i < len; i += 1) this.animationData.assets.push(data.assets[i]); } 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() { if (!this.animationData.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 i = 0; i < this.markers.length; i += 1) { marker = this.markers[i]; if (marker.payload && marker.payload.name === markerName) return marker; } return null; }; AnimationItem.prototype.goToAndStop = function(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 - .001 - 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(.001 + offset); } this.trigger("segmentStart"); }; AnimationItem.prototype.setSegment = function(init, end) { var pendingFrame = -1; if (this.isPaused) { if (this.currentRawFrame + this.firstFrame < init) pendingFrame = init; else if (this.currentRawFrame + this.firstFrame > end) pendingFrame = end - init; } this.firstFrame = init; this.totalFrames = end - init; this.timeCompleted = this.totalFrames; if (pendingFrame !== -1) this.goToAndStop(pendingFrame, true); }; AnimationItem.prototype.playSegments = function(arr, forceFlag) { if (forceFlag) this.segments.length = 0; if (typeof arr[0] === "object") { var i; var len = arr.length; for (i = 0; i < len; i += 1) this.segments.push(arr[i]); } else this.segments.push(arr); if (this.segments.length && forceFlag) this.adjustSegment(this.segments.shift(), 0); if (this.isPaused) this.play(); }; AnimationItem.prototype.resetSegments = function(forceFlag) { this.segments.length = 0; this.segments.push([this.animationData.ip, this.animationData.op]); if (forceFlag) this.checkSegments(0); }; AnimationItem.prototype.checkSegments = function(offset) { if (this.segments.length) { this.adjustSegment(this.segments.shift(), offset); return true; } return false; }; AnimationItem.prototype.destroy = function(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 i = 0; var len = this.assets.length; while (i < len) { if (id === this.assets[i].id) return this.assets[i]; i += 1; } return null; }; AnimationItem.prototype.hide = function() { this.renderer.hide(); }; AnimationItem.prototype.show = function() { this.renderer.show(); }; AnimationItem.prototype.getDuration = function(isFrame) { return isFrame ? this.totalFrames : this.totalFrames / this.frameRate; }; AnimationItem.prototype.updateDocumentData = function(path, documentData, index2) { try { this.renderer.getElementByPath(path).updateDocumentData(documentData, index2); } 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 i = 0; var animItem = ev.target; while (i < len) { if (registeredAnimations[i].animation === animItem) { registeredAnimations.splice(i, 1); i -= 1; len -= 1; if (!animItem.isPaused) subtractPlayingCount(); } i += 1; } } function registerAnimation(element, animationData) { if (!element) return null; var i = 0; while (i < len) { if (registeredAnimations[i].elem === element && registeredAnimations[i].elem !== null) return registeredAnimations[i].animation; i += 1; } var animItem = new AnimationItem(); setupAnimation(animItem, element); animItem.setData(element, animationData); return animItem; } function getRegisteredAnimations() { var i; var lenAnims = registeredAnimations.length; var animations = []; for (i = 0; i < lenAnims; i += 1) animations.push(registeredAnimations[i].animation); return animations; } function addPlayingCount() { playingAnimationsNum += 1; activate(); } function subtractPlayingCount() { playingAnimationsNum -= 1; } function setupAnimation(animItem, element) { animItem.addEventListener("destroy", removeElement); animItem.addEventListener("_active", addPlayingCount); animItem.addEventListener("_idle", subtractPlayingCount); registeredAnimations.push({ elem: element, animation: animItem }); len += 1; } function loadAnimation2(params) { var animItem = new AnimationItem(); setupAnimation(animItem, null); animItem.setParams(params); return animItem; } function setSpeed(val, animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.setSpeed(val, animation); } function setDirection(val, animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.setDirection(val, animation); } function play(animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.play(animation); } function resume(nowTime) { var elapsedTime = nowTime - initTime; var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.advanceTime(elapsedTime); initTime = nowTime; if (playingAnimationsNum && !_isFrozen) window.requestAnimationFrame(resume); else _stopped = true; } function first(nowTime) { initTime = nowTime; window.requestAnimationFrame(resume); } function pause(animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.pause(animation); } function goToAndStop(value, isFrame, animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.goToAndStop(value, isFrame, animation); } function stop(animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.stop(animation); } function togglePause(animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.togglePause(animation); } function destroy(animation) { var i; for (i = len - 1; i >= 0; i -= 1) registeredAnimations[i].animation.destroy(animation); } function searchAnimations2(animationData, standalone, renderer) { var animElements = [].concat([].slice.call(document.getElementsByClassName("lottie")), [].slice.call(document.getElementsByClassName("bodymovin"))); var i; var lenAnims = animElements.length; for (i = 0; i < lenAnims; i += 1) { if (renderer) animElements[i].setAttribute("data-bm-type", renderer); registerAnimation(animElements[i], 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 i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.resize(); } function activate() { if (!_isFrozen && playingAnimationsNum) { if (_stopped) { window.requestAnimationFrame(first); _stopped = false; } } } function freeze() { _isFrozen = true; } function unfreeze() { _isFrozen = false; activate(); } function setVolume(val, animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.setVolume(val, animation); } function mute(animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.mute(animation); } function unmute(animation) { var i; for (i = 0; i < len; i += 1) registeredAnimations[i].animation.unmute(animation); } moduleOb.registerAnimation = registerAnimation; moduleOb.loadAnimation = loadAnimation2; moduleOb.setSpeed = setSpeed; moduleOb.setDirection = setDirection; moduleOb.play = play; moduleOb.pause = pause; moduleOb.stop = stop; moduleOb.togglePause = togglePause; moduleOb.searchAnimations = searchAnimations2; moduleOb.resize = resize; moduleOb.goToAndStop = goToAndStop; moduleOb.destroy = destroy; moduleOb.freeze = freeze; moduleOb.unfreeze = unfreeze; moduleOb.setVolume = setVolume; moduleOb.mute = mute; moduleOb.unmute = unmute; moduleOb.getRegisteredAnimations = getRegisteredAnimations; return moduleOb; }(); const BezierFactory = function() { var ob = {}; ob.getBezierEasing = getBezierEasing; var beziers = {}; function getBezierEasing(a, b, c, d, nm) { var str = nm || ("bez_" + a + "_" + b + "_" + c + "_" + d).replace(/\./g, "p"); if (beziers[str]) return beziers[str]; var bezEasing = new BezierEasing([ a, b, c, d ]); beziers[str] = bezEasing; return bezEasing; } var NEWTON_ITERATIONS = 4; var NEWTON_MIN_SLOPE = .001; 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, i = 0; do { currentT = aA + (aB - aA) / 2; currentX = calcBezier(currentT, mX1, mX2) - aX; if (currentX > 0) aB = currentT; else aA = currentT; } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS); return currentT; } function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { for (var i = 0; i < NEWTON_ITERATIONS; ++i) { var currentSlope = getSlope(aGuessT, mX1, mX2); if (currentSlope === 0) return aGuessT; var currentX = calcBezier(aGuessT, mX1, mX2) - aX; aGuessT -= currentX / currentSlope; } return aGuessT; } function BezierEasing(points) { this._p = points; this._mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize); this._precomputed = false; this.get = this.get.bind(this); } BezierEasing.prototype = { get: function(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); }, _precompute: function() { var mX1 = this._p[0], mY1 = this._p[1], mX2 = this._p[2], mY2 = this._p[3]; this._precomputed = true; if (mX1 !== mY1 || mX2 !== mY2) this._calcSampleValues(); }, _calcSampleValues: function() { var mX1 = this._p[0], mX2 = this._p[2]; for (var i = 0; i < kSplineTableSize; ++i) this._mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); }, /** * getTForX chose the fastest heuristic to determine the percentage value precisely from a given X projection. */ _getTForX: function(aX) { var mX1 = this._p[0], mX2 = this._p[2], mSampleValues = this._mSampleValues; var intervalStart = 0; var currentSample = 1; var lastSample = kSplineTableSize - 1; for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) intervalStart += kSampleStepSize; --currentSample; var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]); var guessForT = intervalStart + dist * kSampleStepSize; var initialSlope = getSlope(guessForT, mX1, mX2); if (initialSlope >= NEWTON_MIN_SLOPE) return newtonRaphsonIterate(aX, guessForT, mX1, mX2); if (initialSlope === 0) return guessForT; return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); } }; return ob; }(); const pooling = function() { function double(arr) { return arr.concat(createSizedArray(arr.length)); } return { double }; }(); const poolFactory = 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 create() { return { addedLength: 0, percents: createTypedArray("float32", getDefaultCurveSegments()), lengths: createTypedArray("float32", getDefaultCurveSegments()) }; } return poolFactory(8, create); }(); const segmentsLengthPool = function() { function create() { return { lengths: [], totalLength: 0 }; } function release(element) { var i; var len = element.lengths.length; for (i = 0; i < len; i += 1) bezierLengthPool.release(element.lengths[i]); element.lengths.length = 0; } return poolFactory(8, create, release); }(); 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 > -.001 && det1 < .001; } 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 = function() { return function(pt1, pt2, pt3, pt4) { var curveSegments = getDefaultCurveSegments(); var k; var i; var len; var ptCoord; var perc; var addedLength = 0; var ptDistance; var point = []; var lastPoint = []; var lengthData = bezierLengthPool.newElement(); len = pt3.length; for (k = 0; k < curveSegments; k += 1) { perc = k / (curveSegments - 1); ptDistance = 0; for (i = 0; i < len; i += 1) { ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * pt3[i] + 3 * (1 - perc) * bmPow(perc, 2) * pt4[i] + bmPow(perc, 3) * pt2[i]; point[i] = ptCoord; if (lastPoint[i] !== null) ptDistance += bmPow(point[i] - lastPoint[i], 2); lastPoint[i] = point[i]; } if (ptDistance) { ptDistance = bmSqrt(ptDistance); addedLength += ptDistance; } lengthData.percents[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 i; var len = shapeData._length; var lengths = segmentsLength.lengths; var totalLength = 0; for (i = 0; i < len - 1; i += 1) { lengths[i] = getBezierLength(pathV[i], pathV[i + 1], pathO[i], pathI[i + 1]); totalLength += lengths[i].addedLength; } if (closed && len) { lengths[i] = getBezierLength(pathV[i], pathV[0], pathO[i], pathI[0]); totalLength += lengths[i].addedLength; } segmentsLength.totalLength = totalLength; return segmentsLength; } function BezierData(length) { this.segmentLength = 0; this.points = new Array(length); } function PointData(partial, point) { this.partialLength = partial; this.point = point; } var buildBezierData = 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 i; var len; var ptCoord; var perc; var addedLength = 0; var ptDistance; var point; var lastPoint = null; if (pt1.length === 2 && (pt1[0] !== pt2[0] || pt1[1] !== pt2[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt1[0] + pt3[0], pt1[1] + pt3[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt2[0] + pt4[0], pt2[1] + pt4[1])) curveSegments = 2; var bezierData = new BezierData(curveSegments); len = pt3.length; for (k = 0; k < curveSegments; k += 1) { point = createSizedArray(len); perc = k / (curveSegments - 1); ptDistance = 0; for (i = 0; i < len; i += 1) { ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * (pt1[i] + pt3[i]) + 3 * (1 - perc) * bmPow(perc, 2) * (pt2[i] + pt4[i]) + bmPow(perc, 3) * pt2[i]; point[i] = ptCoord; if (lastPoint !== null) ptDistance += bmPow(point[i] - lastPoint[i], 2); } ptDistance = bmSqrt(ptDistance); addedLength += ptDistance; bezierData.points[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; return [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, 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]; } var bezierSegmentPoints = createTypedArray("float32", 8); function getNewSegment(pt1, pt2, pt3, pt4, startPerc, endPerc, bezierData) { if (startPerc < 0) startPerc = 0; else if (startPerc > 1) startPerc = 1; var t0 = getDistancePerc(startPerc, bezierData); endPerc = endPerc > 1 ? 1 : endPerc; var t1 = getDistancePerc(endPerc, bezierData); var i; var len = pt1.length; var u0 = 1 - t0; var u1 = 1 - t1; var u0u0u0 = u0 * u0 * u0; var t0u0u0_3 = t0 * u0 * u0 * 3; var t0t0u0_3 = t0 * t0 * u0 * 3; var t0t0t0 = t0 * t0 * t0; var u0u0u1 = u0 * u0 * u1; var t0u0u1_3 = t0 * u0 * u1 + u0 * t0 * u1 + u0 * u0 * t1; var t0t0u1_3 = t0 * t0 * u1 + u0 * t0 * t1 + t0 * u0 * t1; var t0t0t1 = t0 * t0 * t1; var u0u1u1 = u0 * u1 * u1; var t0u1u1_3 = t0 * u1 * u1 + u0 * t1 * u1 + u0 * u1 * t1; var t0t1u1_3 = t0 * t1 * u1 + u0 * t1 * t1 + t0 * u1 * t1; var t0t1t1 = t0 * t1 * t1; var u1u1u1 = u1 * u1 * u1; var t1u1u1_3 = t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1; var t1t1u1_3 = t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1; var t1t1t1 = t1 * t1 * t1; for (i = 0; i < len; i += 1) { bezierSegmentPoints[i * 4] = math.round((u0u0u0 * pt1[i] + t0u0u0_3 * pt3[i] + t0t0u0_3 * pt4[i] + t0t0t0 * pt2[i]) * 1e3) / 1e3; bezierSegmentPoints[i * 4 + 1] = math.round((u0u0u1 * pt1[i] + t0u0u1_3 * pt3[i] + t0t0u1_3 * pt4[i] + t0t0t1 * pt2[i]) * 1e3) / 1e3; bezierSegmentPoints[i * 4 + 2] = math.round((u0u1u1 * pt1[i] + t0u1u1_3 * pt3[i] + t0t1u1_3 * pt4[i] + t0t1t1 * pt2[i]) * 1e3) / 1e3; bezierSegmentPoints[i * 4 + 3] = math.round((u1u1u1 * pt1[i] + t1u1u1_3 * pt3[i] + t1t1u1_3 * pt4[i] + t1t1t1 * pt2[i]) * 1e3) / 1e3; } return bezierSegmentPoints; } return { getSegmentsLength, getNewSegment, getPointInSegment, buildBezierData, pointOnLine2D, pointOnLine3D }; } const bez = bezFunction(); const PropertyFactory = function() { var initFrame = initialDefaultFrame; var mathAbs = Math.abs; function interpolateValue(frameNum, caching) { var offsetTime = this.offsetTime; var newValue; if (this.propType === "multidimensional") newValue = createTypedArray("float32", this.pv.length); var iterationIndex = caching.lastIndex; var i = iterationIndex; var len = this.keyframes.length - 1; var flag = true; var keyData; var nextKeyData; var keyframeMetadata; while (flag) { keyData = this.keyframes[i]; nextKeyData = this.keyframes[i + 1]; if (i === len - 1 && frameNum >= nextKeyData.t - offsetTime) { if (keyData.h) keyData = nextKeyData; iterationIndex = 0; break; } if (nextKeyData.t - offsetTime > frameNum) { iterationIndex = i; break; } if (i < len - 1) i += 1; else { iterationIndex = 0; flag = false; } } keyframeMetadata = this.keyframesMetadata[i] || {}; var 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 === i ? caching._lastAddedLength : 0; j = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i ? 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 = i; } } else { var outX; var outY; var inX; var inY; var keyValue; len = keyData.s.length; endValue = nextKeyData.s || keyData.e; if (this.sh && keyData.h !== 1) if (frameNum >= nextKeyTime) { newValue[0] = endValue[0]; newValue[1] = endValue[1]; newValue[2] = endValue[2]; } else if (frameNum <= keyTime) { newValue[0] = keyData.s[0]; newValue[1] = keyData.s[1]; newValue[2] = keyData.s[2]; } else { var quatStart = createQuaternion(keyData.s); var quatEnd = createQuaternion(endValue); var time = (frameNum - keyTime) / (nextKeyTime - keyTime); quaternionToEuler(newValue, slerp(quatStart, quatEnd, time)); } else for (i = 0; i < len; i += 1) { if (keyData.h !== 1) if (frameNum >= nextKeyTime) perc = 1; else if (frameNum < keyTime) perc = 0; else { if (keyData.o.x.constructor === Array) { if (!keyframeMetadata.__fnct) keyframeMetadata.__fnct = []; if (!keyframeMetadata.__fnct[i]) { outX = keyData.o.x[i] === void 0 ? keyData.o.x[0] : keyData.o.x[i]; outY = keyData.o.y[i] === void 0 ? keyData.o.y[0] : keyData.o.y[i]; inX = keyData.i.x[i] === void 0 ? keyData.i.x[0] : keyData.i.x[i]; inY = keyData.i.y[i] === void 0 ? keyData.i.y[0] : keyData.i.y[i]; fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; keyframeMetadata.__fnct[i] = fnc; } else fnc = keyframeMetadata.__fnct[i]; } else if (!keyframeMetadata.__fnct) { outX = keyData.o.x; outY = keyData.o.y; inX = keyData.i.x; inY = keyData.i.y; fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; keyData.keyframeMetadata = fnc; } else fnc = keyframeMetadata.__fnct; perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime)); } endValue = nextKeyData.s || keyData.e; keyValue = keyData.h === 1 ? keyData.s[i] : keyData.s[i] + (endValue[i] - keyData.s[i]) * perc; if (this.propType === "multidimensional") newValue[i] = keyValue; else newValue = keyValue; } } caching.lastIndex = iterationIndex; return newValue; } function slerp(a, b, t) { var out = []; var ax = a[0]; var ay = a[1]; var az = a[2]; var aw = a[3]; var bx = b[0]; var by = b[1]; var bz = b[2]; var bw = b[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 - t) * omega) / sinom; scale1 = Math.sin(t * omega) / sinom; } else { scale0 = 1 - t; scale1 = t; } out[0] = scale0 * ax + scale1 * bx; out[1] = scale0 * ay + scale1 * by; out[2] = scale0 * az + scale1 * bz; out[3] = scale0 * aw + scale1 * bw; return out; } function quaternionToEuler(out, quat) { var qx = quat[0]; var qy = quat[1]; var qz = quat[2]; var qw = quat[3]; var heading = Math.atan2(2 * qy * qw - 2 * qx * qz, 1 - 2 * qy * qy - 2 * qz * qz); var attitude = Math.asin(2 * qx * qy + 2 * qz * qw); var bank = Math.atan2(2 * qx * qw - 2 * qy * qz, 1 - 2 * qx * qx - 2 * qz * qz); out[0] = heading / degToRads; out[1] = attitude / degToRads; out[2] = bank / degToRads; } function createQuaternion(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 c3 = Math.cos(bank / 2); var s1 = Math.sin(heading / 2); var s2 = Math.sin(attitude / 2); var s3 = Math.sin(bank / 2); var w = c1 * c2 * c3 - s1 * s2 * s3; return [ s1 * s2 * c3 + c1 * c2 * s3, s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, 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 i = 0; var len = this.v.length; while (i < len) { multipliedValue = val[i] * this.mult; if (mathAbs(this.v[i] - multipliedValue) > 1e-5) { this.v[i] = multipliedValue; this._mdf = true; } i += 1; } } } function processEffectsSequence() { if (this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) return; if (this.lock) { this.setVValue(this.pv); return; } this.lock = true; this._mdf = this._isFirstFrame; var i; var len = this.effectsSequence.length; var finalValue = this.kf ? this.pv : this.data.k; for (i = 0; i < len; i += 1) finalValue = this.effectsSequence[i](finalValue); this.setVValue(finalValue); this._isFirstFrame = false; this.lock = false; this.frameId = this.elem.globalData.frameId; } function addEffect(effectFunction) { this.effectsSequence.push(effectFunction); this.container.addDynamicProperty(this); } function ValueProperty(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 = addEffect; } 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 i; var len = data.k.length; this.v = createTypedArray("float32", len); this.pv = createTypedArray("float32", len); this.vel = createTypedArray("float32", len); for (i = 0; i < len; i += 1) { this.v[i] = data.k[i] * this.mult; this.pv[i] = data.k[i]; } this._isFirstFrame = true; this.effectsSequence = []; this.getValue = processEffectsSequence; this.setVValue = setVValue; this.addEffect = addEffect; } 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 = addEffect; } function KeyframedMultidimensionalProperty(elem, data, mult, container) { this.propType = "multidimensional"; var i; var len = data.k.length; var s; var e; var to; var ti; for (i = 0; i < len - 1; i += 1) if (data.k[i].to && data.k[i].s && data.k[i + 1] && data.k[i + 1].s) { s = data.k[i].s; e = data.k[i + 1].s; to = data.k[i].to; ti = data.k[i].ti; if (s.length === 2 && !(s[0] === e[0] && s[1] === e[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], s[0] + to[0], s[1] + to[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], e[0] + ti[0], e[1] + ti[1]) || s.length === 3 && !(s[0] === e[0] && s[1] === e[1] && s[2] === e[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], s[0] + to[0], s[1] + to[1], s[2] + to[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], e[0] + ti[0], e[1] + ti[1], e[2] + ti[2])) { data.k[i].to = null; data.k[i].ti = null; } if (s[0] === e[0] && s[1] === e[1] && to[0] === 0 && to[1] === 0 && ti[0] === 0 && ti[1] === 0) { if (s.length === 2 || s[2] === e[2] && to[2] === 0 && ti[2] === 0) { data.k[i].to = null; data.k[i].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 (i = 0; i < arrLen; i += 1) { this.v[i] = initFrame; this.pv[i] = initFrame; } this._caching = { lastFrame: initFrame, lastIndex: 0, value: createTypedArray("float32", arrLen) }; this.addEffect = addEffect; } function getProp(elem, data, type, mult, container) { var p; if (!data.k.length) p = new ValueProperty(elem, data, mult, container); else if (typeof data.k[0] === "number") p = new MultiDimensionalProperty(elem, data, mult, container); else switch (type) { case 0: p = new KeyframedValueProperty(elem, data, mult, container); break; case 1: p = new KeyframedMultidimensionalProperty(elem, data, mult, container); break; } if (p.effectsSequence.length) container.addDynamicProperty(p); return p; } return { getProp }; }(); 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 i; var len = this.dynamicProperties.length; for (i = 0; i < len; i += 1) { this.dynamicProperties[i].getValue(); if (this.dynamicProperties[i]._mdf) this._mdf = true; } }, initDynamicPropertyContainer: function(container) { this.container = container; this.dynamicProperties = []; this._mdf = false; this._isAnimated = false; } }; const pointPool = function() { function create() { return createTypedArray("float32", 2); } return poolFactory(8, create); }(); function ShapePath() { this.c = false; this._length = 0; this._maxLength = 8; this.v = createSizedArray(this._maxLength); this.o = createSizedArray(this._maxLength); this.i = createSizedArray(this._maxLength); } ShapePath.prototype.setPathData = function(closed, len) { this.c = closed; this.setLength(len); var i = 0; while (i < len) { this.v[i] = pointPool.newElement(); this.o[i] = pointPool.newElement(); this.i[i] = pointPool.newElement(); i += 1; } }; ShapePath.prototype.setLength = function(len) { while (this._maxLength < len) this.doubleArrayLength(); this._length = len; }; ShapePath.prototype.doubleArrayLength = function() { this.v = this.v.concat(createSizedArray(this._maxLength)); this.i = this.i.concat(createSizedArray(this._maxLength)); this.o = this.o.concat(createSizedArray(this._maxLength)); this._maxLength *= 2; }; ShapePath.prototype.setXYAt = function(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; }; ShapePath.prototype.setTripleAt = function(vX, vY, oX, oY, iX, iY, pos, replace) { this.setXYAt(vX, vY, "v", pos, replace); this.setXYAt(oX, oY, "o", pos, replace); this.setXYAt(iX, iY, "i", pos, replace); }; ShapePath.prototype.reverse = function() { var newPath = new ShapePath(); newPath.setPathData(this.c, this._length); var vertices = this.v; var outPoints = this.o; var inPoints = this.i; var init = 0; if (this.c) { newPath.setTripleAt(vertices[0][0], vertices[0][1], inPoints[0][0], inPoints[0][1], outPoints[0][0], outPoints[0][1], 0, false); init = 1; } var cnt = this._length - 1; var len = this._length; var i; for (i = init; i < len; i += 1) { newPath.setTripleAt(vertices[cnt][0], vertices[cnt][1], inPoints[cnt][0], inPoints[cnt][1], outPoints[cnt][0], outPoints[cnt][1], i, false); cnt -= 1; } return newPath; }; const shapePool = function() { function create() { return new ShapePath(); } function release(shapePath) { var len = shapePath._length; var i; for (i = 0; i < len; i += 1) { pointPool.release(shapePath.v[i]); pointPool.release(shapePath.i[i]); pointPool.release(shapePath.o[i]); shapePath.v[i] = null; shapePath.i[i] = null; shapePath.o[i] = null; } shapePath._length = 0; shapePath.c = false; } function clone(shape) { var cloned = factory.newElement(); var i; var len = shape._length === void 0 ? shape.v.length : shape._length; cloned.setLength(len); cloned.c = shape.c; for (i = 0; i < len; i += 1) cloned.setTripleAt(shape.v[i][0], shape.v[i][1], shape.o[i][0], shape.o[i][1], shape.i[i][0], shape.i[i][1], i); return cloned; } var factory = poolFactory(4, create, release); factory.clone = clone; 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 i; for (i = 0; i < this._length; i += 1) shapePool.release(this.shapes[i]); 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 i; var len = shapeCollection._length; for (i = 0; i < len; i += 1) shapePool.release(shapeCollection.shapes[i]); shapeCollection._length = 0; if (_length === _maxLength) { pool = pooling.double(pool); _maxLength *= 2; } pool[_length] = shapeCollection; _length += 1; } return 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 i = iterationIndex; var len = kf.length - 1; var flag = true; var keyData; var nextKeyData; var keyframeMetadata; while (flag) { keyData = kf[i]; nextKeyData = kf[i + 1]; if (nextKeyData.t - this.offsetTime > frameNum) break; if (i < len - 1) i += 1; else flag = false; } keyframeMetadata = this.keyframesMetadata[i] || {}; isHold = keyData.h === 1; iterationIndex = i; if (!isHold) { if (frameNum >= nextKeyData.t - this.offsetTime) perc = 1; else if (frameNum < keyData.t - this.offsetTime) perc = 0; else { var fnc; if (keyframeMetadata.__fnct) fnc = keyframeMetadata.__fnct; else { fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y).get; keyframeMetadata.__fnct = fnc; } perc = fnc((frameNum - (keyData.t - this.offsetTime)) / (nextKeyData.t - this.offsetTime - (keyData.t - this.offsetTime))); } keyPropE = nextKeyData.s ? nextKeyData.s[0] : keyData.e[0]; } keyPropS = keyData.s[0]; } jLen = previousValue._length; kLen = keyPropS.i[0].length; caching.lastIndex = iterationIndex; for (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 i; var len = shape1._length; for (i = 0; i < len; i += 1) if (shape1.v[i][0] !== shape2.v[i][0] || shape1.v[i][1] !== shape2.v[i][1] || shape1.o[i][0] !== shape2.o[i][0] || shape1.o[i][1] !== shape2.o[i][1] || shape1.i[i][0] !== shape2.i[i][0] || shape1.i[i][1] !== shape2.i[i][1]) return false; return true; } function setVValue(newPath) { if (!shapesEqual(this.v, newPath)) { this.v = shapePool.clone(newPath); this.localShapeCollection.releaseShapes(); this.localShapeCollection.addShape(this.v); this._mdf = true; this.paths = this.localShapeCollection; } } function processEffectsSequence() { if (this.elem.globalData.frameId === this.frameId) return; if (!this.effectsSequence.length) { this._mdf = false; return; } if (this.lock) { this.setVValue(this.pv); return; } this.lock = true; this._mdf = false; var finalValue; if (this.kf) finalValue = this.pv; else if (this.data.ks) finalValue = this.data.ks.k; else finalValue = this.data.pt.k; var i; var len = this.effectsSequence.length; for (i = 0; i < len; i += 1) finalValue = this.effectsSequence[i](finalValue); this.setVValue(finalValue); this.lock = false; this.frameId = this.elem.globalData.frameId; } function ShapeProperty(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 addEffect(effectFunction) { this.effectsSequence.push(effectFunction); this.container.addDynamicProperty(this); } ShapeProperty.prototype.interpolateShape = interpolateShape; ShapeProperty.prototype.getValue = processEffectsSequence; ShapeProperty.prototype.setVValue = setVValue; ShapeProperty.prototype.addEffect = addEffect; function KeyframedShapeProperty(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 = addEffect; 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 _v = this.v; _v.v[0][0] = p0; _v.v[0][1] = p1 - s1; _v.v[1][0] = _cw ? p0 + s0 : p0 - s0; _v.v[1][1] = p1; _v.v[2][0] = p0; _v.v[2][1] = p1 + s1; _v.v[3][0] = _cw ? p0 - s0 : p0 + s0; _v.v[3][1] = p1; _v.i[0][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint; _v.i[0][1] = p1 - s1; _v.i[1][0] = _cw ? p0 + s0 : p0 - s0; _v.i[1][1] = p1 - s1 * cPoint; _v.i[2][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint; _v.i[2][1] = p1 + s1; _v.i[3][0] = _cw ? p0 - s0 : p0 + s0; _v.i[3][1] = p1 + s1 * cPoint; _v.o[0][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint; _v.o[0][1] = p1 - s1; _v.o[1][0] = _cw ? p0 + s0 : p0 - s0; _v.o[1][1] = p1 + s1 * cPoint; _v.o[2][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint; _v.o[2][1] = p1 + s1; _v.o[3][0] = _cw ? p0 - s0 : p0 + s0; _v.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, .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, .01, this); this.localShapeCollection = shapeCollectionPool.newShapeCollection(); this.localShapeCollection.addShape(this.v); this.paths = this.localShapeCollection; if (this.dynamicProperties.length) this.k = true; else { this.k = false; this.convertToPath(); } } StarShapePropertyFactory.prototype = { reset: resetShape, getValue: function() { if (this.elem.globalData.frameId === this.frameId) return; this.frameId = this.elem.globalData.frameId; this.iterateDynamicProperties(); if (this._mdf) this.convertToPath(); }, convertStarToPath: function() { var numPts = Math.floor(this.pt.v) * 2; var angle = Math.PI * 2 / numPts; var longFlag = true; var longRad = this.or.v; var shortRad = this.ir.v; var longRound = this.os.v; var shortRound = this.is.v; var longPerimSegment = 2 * Math.PI * longRad / (numPts * 2); var shortPerimSegment = 2 * Math.PI * shortRad / (numPts * 2); var i; var rad; var roundness; var perimSegment; var currentAng = -Math.PI / 2; currentAng += this.r.v; var dir = this.data.d === 3 ? -1 : 1; this.v._length = 0; for (i = 0; i < numPts; i += 1) { rad = longFlag ? longRad : shortRad; roundness = longFlag ? longRound : shortRound; perimSegment = longFlag ? longPerimSegment : shortPerimSegment; var 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, i, true); longFlag = !longFlag; currentAng += angle * dir; } }, convertPolygonToPath: function() { var numPts = Math.floor(this.pt.v); var angle = Math.PI * 2 / numPts; var rad = this.or.v; var roundness = this.os.v; var perimSegment = 2 * Math.PI * rad / (numPts * 4); var i; var currentAng = -Math.PI * .5; var dir = this.data.d === 3 ? -1 : 1; currentAng += this.r.v; this.v._length = 0; for (i = 0; i < numPts; i += 1) { var 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, i, 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 v1 = this.s.v[1] / 2; var round = bmMin(v0, v1, 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 - v1 + round, p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + cPoint, 0, true); this.v.setTripleAt(p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - cPoint, p0 + v0, p1 + v1 - round, 1, true); if (round !== 0) { this.v.setTripleAt(p0 + v0 - round, p1 + v1, p0 + v0 - round, p1 + v1, p0 + v0 - cPoint, p1 + v1, 2, true); this.v.setTripleAt(p0 - v0 + round, p1 + v1, p0 - v0 + cPoint, p1 + v1, p0 - v0 + round, p1 + v1, 3, true); this.v.setTripleAt(p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - cPoint, 4, true); this.v.setTripleAt(p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + cPoint, p0 - v0, p1 - v1 + round, 5, true); this.v.setTripleAt(p0 - v0 + round, p1 - v1, p0 - v0 + round, p1 - v1, p0 - v0 + cPoint, p1 - v1, 6, true); this.v.setTripleAt(p0 + v0 - round, p1 - v1, p0 + v0 - cPoint, p1 - v1, p0 + v0 - round, p1 - v1, 7, true); } else { this.v.setTripleAt(p0 - v0, p1 + v1, p0 - v0 + cPoint, p1 + v1, p0 - v0, p1 + v1, 2); this.v.setTripleAt(p0 - v0, p1 - v1, p0 - v0, p1 - v1 + cPoint, p0 - v0, p1 - v1, 3); } } else { this.v.setTripleAt(p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + cPoint, p0 + v0, p1 - v1 + round, 0, true); if (round !== 0) { this.v.setTripleAt(p0 + v0 - round, p1 - v1, p0 + v0 - round, p1 - v1, p0 + v0 - cPoint, p1 - v1, 1, true); this.v.setTripleAt(p0 - v0 + round, p1 - v1, p0 - v0 + cPoint, p1 - v1, p0 - v0 + round, p1 - v1, 2, true); this.v.setTripleAt(p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + cPoint, 3, true); this.v.setTripleAt(p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - cPoint, p0 - v0, p1 + v1 - round, 4, true); this.v.setTripleAt(p0 - v0 + round, p1 + v1, p0 - v0 + round, p1 + v1, p0 - v0 + cPoint, p1 + v1, 5, true); this.v.setTripleAt(p0 + v0 - round, p1 + v1, p0 + v0 - cPoint, p1 + v1, p0 + v0 - round, p1 + v1, 6, true); this.v.setTripleAt(p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - cPoint, 7, true); } else { this.v.setTripleAt(p0 - v0, p1 - v1, p0 - v0 + cPoint, p1 - v1, p0 - v0, p1 - v1, 1, true); this.v.setTripleAt(p0 - v0, p1 + v1, p0 - v0, p1 + v1 - cPoint, p0 - v0, p1 + v1, 2, true); this.v.setTripleAt(p0 + v0, p1 + v1, p0 + v0 - cPoint, p1 + v1, p0 + v0, p1 + v1, 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) if ((type === 3 ? data.pt : data.ks).k.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; }(); /*! Transformation Matrix v2.0 (c) Epistemex 2014-2015 www.epistemex.com By Ken Fyrstenberg Contributions by leeoniya. License: MIT, header required. */ const Matrix = function() { var _cos = Math.cos; var _sin = Math.sin; var _tan = Math.tan; var _rnd = Math.round; function reset() { this.props[0] = 1; this.props[1] = 0; this.props[2] = 0; this.props[3] = 0; this.props[4] = 0; this.props[5] = 1; this.props[6] = 0; this.props[7] = 0; this.props[8] = 0; this.props[9] = 0; this.props[10] = 1; this.props[11] = 0; this.props[12] = 0; this.props[13] = 0; this.props[14] = 0; this.props[15] = 1; return this; } function rotate(angle) { if (angle === 0) return this; var mCos = _cos(angle); var mSin = _sin(angle); return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } function rotateX(angle) { if (angle === 0) return this; var mCos = _cos(angle); var mSin = _sin(angle); return this._t(1, 0, 0, 0, 0, mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1); } function rotateY(angle) { if (angle === 0) return this; var mCos = _cos(angle); var mSin = _sin(angle); return this._t(mCos, 0, mSin, 0, 0, 1, 0, 0, -mSin, 0, mCos, 0, 0, 0, 0, 1); } function rotateZ(angle) { if (angle === 0) return this; var mCos = _cos(angle); var mSin = _sin(angle); return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } function shear(sx, sy) { return this._t(1, sy, sx, 1, 0, 0); } function skew(ax, ay) { return this.shear(_tan(ax), _tan(ay)); } function skewFromAxis(ax, angle) { var mCos = _cos(angle); var mSin = _sin(angle); return this._t(mCos, mSin, 0, 0, -mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(1, 0, 0, 0, _tan(ax), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } function scale(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(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) { this.props[0] = a; this.props[1] = b; this.props[2] = c; this.props[3] = d; this.props[4] = e; this.props[5] = f; this.props[6] = g; this.props[7] = h; this.props[8] = i; this.props[9] = j; this.props[10] = k; this.props[11] = l; this.props[12] = m; this.props[13] = n; this.props[14] = o; this.props[15] = p; return this; } function translate(tx, ty, tz) { tz = tz || 0; if (tx !== 0 || ty !== 0 || tz !== 0) return this._t(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tx, ty, tz, 1); return this; } function transform(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2, p2) { var _p = this.props; if (a2 === 1 && b2 === 0 && c2 === 0 && d2 === 0 && e2 === 0 && f2 === 1 && g2 === 0 && h2 === 0 && i2 === 0 && j2 === 0 && k2 === 1 && l2 === 0) { _p[12] = _p[12] * a2 + _p[15] * m2; _p[13] = _p[13] * f2 + _p[15] * n2; _p[14] = _p[14] * k2 + _p[15] * o2; _p[15] *= p2; this._identityCalculated = false; return this; } var a1 = _p[0]; var b1 = _p[1]; var c1 = _p[2]; var d1 = _p[3]; var e1 = _p[4]; var f1 = _p[5]; var g1 = _p[6]; var h1 = _p[7]; var i1 = _p[8]; var j1 = _p[9]; var k1 = _p[10]; var l1 = _p[11]; var m1 = _p[12]; var n1 = _p[13]; var o1 = _p[14]; var p1 = _p[15]; _p[0] = a1 * a2 + b1 * e2 + c1 * i2 + d1 * m2; _p[1] = a1 * b2 + b1 * f2 + c1 * j2 + d1 * n2; _p[2] = a1 * c2 + b1 * g2 + c1 * k2 + d1 * o2; _p[3] = a1 * d2 + b1 * h2 + c1 * l2 + d1 * p2; _p[4] = e1 * a2 + f1 * e2 + g1 * i2 + h1 * m2; _p[5] = e1 * b2 + f1 * f2 + g1 * j2 + h1 * n2; _p[6] = e1 * c2 + f1 * g2 + g1 * k2 + h1 * o2; _p[7] = e1 * d2 + f1 * h2 + g1 * l2 + h1 * p2; _p[8] = i1 * a2 + j1 * e2 + k1 * i2 + l1 * m2; _p[9] = i1 * b2 + j1 * f2 + k1 * j2 + l1 * n2; _p[10] = i1 * c2 + j1 * g2 + k1 * k2 + l1 * o2; _p[11] = i1 * d2 + j1 * h2 + k1 * l2 + l1 * p2; _p[12] = m1 * a2 + n1 * e2 + o1 * i2 + p1 * m2; _p[13] = m1 * b2 + n1 * f2 + o1 * j2 + p1 * n2; _p[14] = m1 * c2 + n1 * g2 + o1 * k2 + p1 * o2; _p[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 i = 0; while (i < 16) { if (matr.props[i] !== this.props[i]) return false; i += 1; } return true; } function clone(matr) { var i; for (i = 0; i < 16; i += 1) matr.props[i] = this.props[i]; return matr; } function cloneFromProps(props) { var i; for (i = 0; i < 16; i += 1) this.props[i] = props[i]; } function applyToPoint(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 a = this.props[5] / determinant; var b = -this.props[1] / determinant; var c = -this.props[4] / determinant; var d = this.props[0] / determinant; var e = (this.props[4] * this.props[13] - this.props[5] * this.props[12]) / determinant; var f = -(this.props[0] * this.props[13] - this.props[1] * this.props[12]) / determinant; var inverseMatrix = new Matrix(); inverseMatrix.props[0] = a; inverseMatrix.props[1] = b; inverseMatrix.props[4] = c; inverseMatrix.props[5] = d; inverseMatrix.props[12] = e; inverseMatrix.props[13] = f; return inverseMatrix; } function inversePoint(pt) { return this.getInverseMatrix().applyToPointArray(pt[0], pt[1], pt[2] || 0); } function inversePoints(pts) { var i; var len = pts.length; var retPts = []; for (i = 0; i < len; i += 1) retPts[i] = inversePoint(pts[i]); return retPts; } function applyToTriplePoints(pt1, pt2, pt3) { var arr = createTypedArray("float32", 6); if (this.isIdentity()) { arr[0] = pt1[0]; arr[1] = pt1[1]; arr[2] = pt2[0]; arr[3] = pt2[1]; arr[4] = pt3[0]; arr[5] = pt3[1]; } else { var p0 = this.props[0]; var p1 = this.props[1]; var p4 = this.props[4]; var p5 = this.props[5]; var p12 = this.props[12]; var p13 = this.props[13]; arr[0] = pt1[0] * p0 + pt1[1] * p4 + p12; arr[1] = pt1[0] * p1 + pt1[1] * p5 + p13; arr[2] = pt2[0] * p0 + pt2[1] * p4 + p12; arr[3] = pt2[0] * p1 + pt2[1] * p5 + p13; arr[4] = pt3[0] * p0 + pt3[1] * p4 + p12; arr[5] = pt3[0] * p1 + pt3[1] * p5 + p13; } return arr; } function applyToPointArray(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 _p = this.props; return Math.round((x * _p[0] + y * _p[4] + _p[12]) * 100) / 100 + "," + Math.round((x * _p[1] + y * _p[5] + _p[13]) * 100) / 100; } function toCSS() { var i = 0; var props = this.props; var cssValue = "matrix3d("; var v = 1e4; while (i < 16) { cssValue += _rnd(props[i] * v) / v; cssValue += i === 15 ? ")" : ","; i += 1; } return cssValue; } function roundMatrixProperty(val) { var v = 1e4; if (val < 1e-6 && val > 0 || val > -1e-6 && val < 0) return _rnd(val * v) / v; return val; } function to2dCSS() { var props = this.props; var _a = roundMatrixProperty(props[0]); var _b = 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(" + _a + "," + _b + "," + _c + "," + _d + "," + _e + "," + _f + ")"; } return function() { this.reset = reset; this.rotate = rotate; this.rotateX = rotateX; this.rotateY = rotateY; this.rotateZ = rotateZ; this.skew = skew; this.skewFromAxis = skewFromAxis; this.shear = shear; this.scale = scale; this.setTransform = setTransform; this.translate = translate; 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 = clone; 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 i = 0; i < vars.length; i += 1) { var pair = vars[i].split("="); if (decodeURIComponent(pair[0]) == variable) return decodeURIComponent(pair[1]); } return null; } var queryString = ""; var scripts = document.getElementsByTagName("script"); var myScript = scripts[scripts.length - 1] || { 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, .01, this); this.e = PropertyFactory.getProp(elem, data.e, 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(s, e, shapeLength, addedLength, totalModifierLength) { var segments = []; if (e <= 1) segments.push({ s, e }); else if (s >= 1) segments.push({ s: s - 1, e: e - 1 }); else { segments.push({ s, e: 1 }); segments.push({ s: 0, e: e - 1 }); } var shapeSegments = []; var i; var len = segments.length; var segmentOb; for (i = 0; i < len; i += 1) { segmentOb = segments[i]; if (!(segmentOb.e * totalModifierLength < addedLength || segmentOb.s * totalModifierLength > addedLength + shapeLength)) { var shapeS; var shapeE; if (segmentOb.s * totalModifierLength <= addedLength) shapeS = 0; else shapeS = (segmentOb.s * totalModifierLength - addedLength) / shapeLength; if (segmentOb.e * totalModifierLength >= addedLength + shapeLength) shapeE = 1; else shapeE = (segmentOb.e * totalModifierLength - addedLength) / shapeLength; shapeSegments.push([shapeS, shapeE]); } } if (!shapeSegments.length) shapeSegments.push([0, 0]); return shapeSegments; }; TrimModifier.prototype.releasePathsData = function(pathsData) { var i; var len = pathsData.length; for (i = 0; i < len; i += 1) segmentsLengthPool.release(pathsData[i]); pathsData.length = 0; return pathsData; }; TrimModifier.prototype.processShapes = function(_isFirstFrame) { var s; var e; if (this._mdf || _isFirstFrame) { var o = this.o.v % 360 / 360; if (o < 0) o += 1; if (this.s.v > 1) s = 1 + o; else if (this.s.v < 0) s = 0 + o; else s = this.s.v + o; if (this.e.v > 1) e = 1 + o; else if (this.e.v < 0) e = 0 + o; else e = this.e.v + o; if (s > e) { var _s = s; s = e; e = _s; } s = Math.round(s * 1e4) * 1e-4; e = Math.round(e * 1e4) * 1e-4; this.sValue = s; this.eValue = e; } else { s = this.sValue; e = this.eValue; } var shapePaths; var i; var len = this.shapes.length; var j; var jLen; var pathsData; var pathData; var totalShapeLength; var totalModifierLength = 0; if (e === s) for (i = 0; i < len; i += 1) { this.shapes[i].localShapeCollection.releaseShapes(); this.shapes[i].shape._mdf = true; this.shapes[i].shape.paths = this.shapes[i].localShapeCollection; if (this._mdf) this.shapes[i].pathsData.length = 0; } else if (!(e === 1 && s === 0 || e === 0 && s === 1)) { var segments = []; var shapeData; var localShapeCollection; for (i = 0; i < len; i += 1) { shapeData = this.shapes[i]; if (!shapeData.shape._mdf && !this._mdf && !_isFirstFrame && this.m !== 2) shapeData.shape.paths = shapeData.localShapeCollection; else { shapePaths = shapeData.shape.paths; jLen = shapePaths._length; totalShapeLength = 0; if (!shapeData.shape._mdf && shapeData.pathsData.length) totalShapeLength = shapeData.totalShapeLength; else { pathsData = this.releasePathsData(shapeData.pathsData); for (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 = s; var shapeE = e; var addedLength = 0; var edges; for (i = len - 1; i >= 0; i -= 1) { shapeData = this.shapes[i]; if (shapeData.shape._mdf) { localShapeCollection = shapeData.localShapeCollection; localShapeCollection.releaseShapes(); if (this.m === 2 && len > 1) { edges = this.calculateShapeEdges(s, e, shapeData.totalShapeLength, addedLength, totalModifierLength); addedLength += shapeData.totalShapeLength; } else edges = [[shapeS, shapeE]]; jLen = edges.length; for (j = 0; j < jLen; j += 1) { shapeS = edges[j][0]; shapeE = edges[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) if (shapeData.shape.paths.shapes[shapeData.shape.paths._length - 1].c) { var lastShape = newShapesData.pop(); this.addPaths(newShapesData, localShapeCollection); newShapesData = this.addShapes(shapeData, segments[1], lastShape); } else { this.addPaths(newShapesData, localShapeCollection); newShapesData = this.addShapes(shapeData, segments[1]); } this.addPaths(newShapesData, localShapeCollection); } } shapeData.shape.paths = localShapeCollection; } } } else if (this._mdf) for (i = 0; i < len; i += 1) { this.shapes[i].pathsData.length = 0; this.shapes[i].shape._mdf = true; } }; TrimModifier.prototype.addPaths = function(newPaths, localShapeCollection) { var i; var len = newPaths.length; for (i = 0; i < len; i += 1) localShapeCollection.addShape(newPaths[i]); }; TrimModifier.prototype.addSegment = function(pt1, pt2, pt3, pt4, shapePath, pos, newShape) { shapePath.setXYAt(pt2[0], pt2[1], "o", pos); shapePath.setXYAt(pt3[0], pt3[1], "i", pos + 1); if (newShape) shapePath.setXYAt(pt1[0], pt1[1], "v", pos); shapePath.setXYAt(pt4[0], pt4[1], "v", pos + 1); }; TrimModifier.prototype.addSegmentFromArray = function(points, shapePath, pos, newShape) { shapePath.setXYAt(points[1], points[5], "o", pos); shapePath.setXYAt(points[2], points[6], "i", pos + 1); if (newShape) shapePath.setXYAt(points[0], points[4], "v", pos); shapePath.setXYAt(points[3], points[7], "v", pos + 1); }; TrimModifier.prototype.addShapes = function(shapeData, shapeSegment, shapePath) { var pathsData = shapeData.pathsData; var shapePaths = shapeData.shape.paths.shapes; var i; var len = shapeData.shape.paths._length; var 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 (i = 0; i < len; i += 1) { lengths = pathsData[i].lengths; shapePath.c = shapePaths[i].c; jLen = shapePaths[i].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[i].v[j - 1], shapePaths[i].o[j - 1], shapePaths[i].i[j], shapePaths[i].v[j], shapePath, segmentCount, newShape); newShape = false; } else { segment = bez.getNewSegment(shapePaths[i].v[j - 1], shapePaths[i].v[j], shapePaths[i].o[j - 1], shapePaths[i].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[i].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[i].v[j - 1], shapePaths[i].o[j - 1], shapePaths[i].i[0], shapePaths[i].v[0], shapePath, segmentCount, newShape); newShape = false; } else { segment = bez.getNewSegment(shapePaths[i].v[j - 1], shapePaths[i].v[0], shapePaths[i].o[j - 1], shapePaths[i].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 (i < 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 i = 0; for (i = 0; i < pathLength; i += 1) { centerPoint[0] += path.v[i][0]; centerPoint[1] += path.v[i][1]; } centerPoint[0] /= pathLength; centerPoint[1] /= pathLength; var clonedPath = shapePool.newElement(); clonedPath.c = path.c; var vX; var vY; var oX; var oY; var iX; var iY; for (i = 0; i < pathLength; i += 1) { vX = path.v[i][0] + (centerPoint[0] - path.v[i][0]) * percent; vY = path.v[i][1] + (centerPoint[1] - path.v[i][1]) * percent; oX = path.o[i][0] + (centerPoint[0] - path.o[i][0]) * -percent; oY = path.o[i][1] + (centerPoint[1] - path.o[i][1]) * -percent; iX = path.i[i][0] + (centerPoint[0] - path.i[i][0]) * -percent; iY = path.i[i][1] + (centerPoint[1] - path.i[i][1]) * -percent; clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, i); } return clonedPath; }; PuckerAndBloatModifier.prototype.processShapes = function(_isFirstFrame) { var shapePaths; var i; var len = this.shapes.length; var j; var jLen; var amount = this.amount.v; if (amount !== 0) { var shapeData; var localShapeCollection; for (i = 0; i < len; i += 1) { shapeData = this.shapes[i]; localShapeCollection = shapeData.localShapeCollection; if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) { localShapeCollection.releaseShapes(); shapeData.shape._mdf = true; shapePaths = shapeData.shape.paths.shapes; jLen = shapeData.shape.paths._length; for (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(mat) { var _mdf = this._mdf; this.iterateDynamicProperties(); this._mdf = this._mdf || _mdf; if (this.a) mat.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); if (this.s) mat.scale(this.s.v[0], this.s.v[1], this.s.v[2]); if (this.sk) mat.skewFromAxis(-this.sk.v, this.sa.v); if (this.r) mat.rotate(-this.r.v); else mat.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); if (this.data.p.s) if (this.data.p.z) mat.translate(this.px.v, this.py.v, -this.pz.v); else mat.translate(this.px.v, this.py.v, 0); else mat.translate(this.p.v[0], this.p.v[1], -this.p.v[2]); } function processKeys(forceRender) { if (this.elem.globalData.frameId === this.frameId) return; if (this._isDirty) { this.precalculateMatrix(); this._isDirty = false; } this.iterateDynamicProperties(); if (this._mdf || forceRender) { var 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 v1; var v2; 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) { v1 = this.p.getValueAtTime((this.p.keyframes[0].t + .01) / frameRate, 0); v2 = 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) { v1 = this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length - 1].t / frameRate, 0); v2 = this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length - 1].t - .05) / frameRate, 0); } else { v1 = this.p.pv; v2 = this.p.getValueAtTime((this.p._caching.lastFrame + this.p.offsetTime - .01) / frameRate, this.p.offsetTime); } else if (this.px && this.px.keyframes && this.py.keyframes && this.px.getValueAtTime && this.py.getValueAtTime) { v1 = []; v2 = []; var px = this.px; var py = this.py; if (px._caching.lastFrame + px.offsetTime <= px.keyframes[0].t) { v1[0] = px.getValueAtTime((px.keyframes[0].t + .01) / frameRate, 0); v1[1] = py.getValueAtTime((py.keyframes[0].t + .01) / frameRate, 0); v2[0] = px.getValueAtTime(px.keyframes[0].t / frameRate, 0); v2[1] = py.getValueAtTime(py.keyframes[0].t / frameRate, 0); } else if (px._caching.lastFrame + px.offsetTime >= px.keyframes[px.keyframes.length - 1].t) { v1[0] = px.getValueAtTime(px.keyframes[px.keyframes.length - 1].t / frameRate, 0); v1[1] = py.getValueAtTime(py.keyframes[py.keyframes.length - 1].t / frameRate, 0); v2[0] = px.getValueAtTime((px.keyframes[px.keyframes.length - 1].t - .01) / frameRate, 0); v2[1] = py.getValueAtTime((py.keyframes[py.keyframes.length - 1].t - .01) / frameRate, 0); } else { v1 = [px.pv, py.pv]; v2[0] = px.getValueAtTime((px._caching.lastFrame + px.offsetTime - .01) / frameRate, px.offsetTime); v2[1] = py.getValueAtTime((py._caching.lastFrame + py.offsetTime - .01) / frameRate, py.offsetTime); } } else { v2 = defaultVector; v1 = v2; } this.v.rotate(-Math.atan2(v1[1] - v2[1], v1[0] - v2[0])); } if (this.data.p && this.data.p.s) if (this.data.p.z) this.v.translate(this.px.v, this.py.v, -this.pz.v); else this.v.translate(this.px.v, this.py.v, 0); else this.v.translate(this.p.v[0], this.p.v[1], -this.p.v[2]); } this.frameId = this.elem.globalData.frameId; } function precalculateMatrix() { if (!this.a.k) { this.pre.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); this.appliedTransformations = 1; } else return; if (!this.s.effectsSequence.length) { this.pre.scale(this.s.v[0], this.s.v[1], this.s.v[2]); this.appliedTransformations = 2; } else return; if (this.sk) if (!this.sk.effectsSequence.length && !this.sa.effectsSequence.length) { this.pre.skewFromAxis(-this.sk.v, this.sa.v); this.appliedTransformations = 3; } else return; if (this.r) { if (!this.r.effectsSequence.length) { this.pre.rotate(-this.r.v); this.appliedTransformations = 4; } } else if (!this.rz.effectsSequence.length && !this.ry.effectsSequence.length && !this.rx.effectsSequence.length && !this.or.effectsSequence.length) { this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); this.appliedTransformations = 4; } } function autoOrient() {} function addDynamicProperty(prop) { this._addDynamicProperty(prop); this.elem.addDynamicProperty(prop); this._isDirty = true; } function TransformProperty(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 i; var len = data.or.k.length; for (i = 0; i < len; i += 1) { data.or.k[i].to = null; data.or.k[i].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, .01, this); if (data.o) this.o = PropertyFactory.getProp(elem, data.o, 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, .01, this); this.eo = PropertyFactory.getProp(elem, data.tr.eo, 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 i; var len = elements.length; for (i = 0; i < len; i += 1) { elements[i]._processed = false; if (elements[i].ty === "gr") this.resetElements(elements[i].it); } }; RepeaterModifier.prototype.cloneElements = function(elements) { var newElements = JSON.parse(JSON.stringify(elements)); this.resetElements(newElements); return newElements; }; RepeaterModifier.prototype.changeGroupRender = function(elements, renderFlag) { var i; var len = elements.length; for (i = 0; i < len; i += 1) { elements[i]._render = renderFlag; if (elements[i].ty === "gr") this.changeGroupRender(elements[i].it, renderFlag); } }; RepeaterModifier.prototype.processShapes = function(_isFirstFrame) { var items; var itemsTransform; var i; var dir; var cont; var hasReloaded = false; if (this._mdf || _isFirstFrame) { var copies = Math.ceil(this.c.v); if (this._groups.length < copies) { while (this._groups.length < copies) { var group = { it: this.cloneElements(this._elements), ty: "gr" }; group.it.push({ a: { a: 0, ix: 1, k: [0, 0] }, nm: "Transform", o: { a: 0, ix: 7, k: 100 }, p: { a: 0, ix: 2, k: [0, 0] }, r: { a: 1, ix: 6, k: [{ s: 0, e: 0, t: 0 }, { s: 0, e: 0, t: 1 }] }, s: { a: 0, ix: 3, k: [100, 100] }, sa: { a: 0, ix: 5, k: 0 }, sk: { a: 0, ix: 4, k: 0 }, ty: "tr" }); this.arr.splice(0, 0, group); this._groups.splice(0, 0, group); this._currentCopies += 1; } this.elem.reloadShapes(); hasReloaded = true; } cont = 0; var renderFlag; for (i = 0; i <= this._groups.length - 1; i += 1) { renderFlag = cont < copies; this._groups[i]._render = renderFlag; this.changeGroupRender(this._groups[i].it, renderFlag); if (!renderFlag) { var elems = this.elemsData[i].it; var transformData = elems[elems.length - 1]; if (transformData.transform.op.v !== 0) { transformData.transform.op._mdf = true; transformData.transform.op.v = 0; } else transformData.transform.op._mdf = false; } cont += 1; } this._currentCopies = copies; var offset = this.o.v; var offsetModulo = offset % 1; var roundOffset = offset > 0 ? Math.floor(offset) : Math.ceil(offset); var pProps = this.pMatrix.props; var rProps = this.rMatrix.props; var sProps = this.sMatrix.props; this.pMatrix.reset(); this.rMatrix.reset(); this.sMatrix.reset(); this.tMatrix.reset(); this.matrix.reset(); var iteration = 0; if (offset > 0) { while (iteration < roundOffset) { this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false); iteration += 1; } if (offsetModulo) { this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, offsetModulo, false); iteration += offsetModulo; } } else if (offset < 0) { while (iteration > roundOffset) { this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, true); iteration -= 1; } if (offsetModulo) { this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, -offsetModulo, true); iteration -= offsetModulo; } } i = this.data.m === 1 ? 0 : this._currentCopies - 1; dir = this.data.m === 1 ? 1 : -1; cont = this._currentCopies; var j; var jLen; while (cont) { items = this.elemsData[i].it; itemsTransform = items[items.length - 1].transform.mProps.v.props; jLen = itemsTransform.length; items[items.length - 1].transform.mProps._mdf = true; items[items.length - 1].transform.op._mdf = true; items[items.length - 1].transform.op.v = this._currentCopies === 1 ? this.so.v : this.so.v + (this.eo.v - this.so.v) * (i / (this._currentCopies - 1)); if (iteration !== 0) { if (i !== 0 && dir === 1 || i !== this._currentCopies - 1 && dir === -1) this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false); this.matrix.transform(rProps[0], rProps[1], rProps[2], rProps[3], rProps[4], rProps[5], rProps[6], rProps[7], rProps[8], rProps[9], rProps[10], rProps[11], rProps[12], rProps[13], rProps[14], rProps[15]); this.matrix.transform(sProps[0], sProps[1], sProps[2], sProps[3], sProps[4], sProps[5], sProps[6], sProps[7], sProps[8], sProps[9], sProps[10], sProps[11], sProps[12], sProps[13], sProps[14], sProps[15]); this.matrix.transform(pProps[0], pProps[1], pProps[2], pProps[3], pProps[4], pProps[5], pProps[6], pProps[7], pProps[8], pProps[9], pProps[10], pProps[11], pProps[12], pProps[13], pProps[14], pProps[15]); for (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; i += dir; } } else { cont = this._currentCopies; i = 0; dir = 1; while (cont) { items = this.elemsData[i].it; itemsTransform = items[items.length - 1].transform.mProps.v.props; items[items.length - 1].transform.mProps._mdf = false; items[items.length - 1].transform.op._mdf = false; cont -= 1; i += dir; } } return hasReloaded; }; RepeaterModifier.prototype.addShape = function() {}; 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 i; var len = path._length; var currentV; var currentI; var currentO; var closerV; var distance; var newPosPerc; var index2 = 0; var vX; var vY; var oX; var oY; var iX; var iY; for (i = 0; i < len; i += 1) { currentV = path.v[i]; currentO = path.o[i]; currentI = path.i[i]; if (currentV[0] === currentO[0] && currentV[1] === currentO[1] && currentV[0] === currentI[0] && currentV[1] === currentI[1]) if ((i === 0 || i === len - 1) && !path.c) { clonedPath.setTripleAt(currentV[0], currentV[1], currentO[0], currentO[1], currentI[0], currentI[1], index2); index2 += 1; } else { if (i === 0) closerV = path.v[len - 1]; else closerV = path.v[i - 1]; distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0; iX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; vX = iX; iY = currentV[1] - (currentV[1] - closerV[1]) * newPosPerc; vY = iY; oX = vX - (vX - currentV[0]) * roundCorner; oY = vY - (vY - currentV[1]) * roundCorner; clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2); index2 += 1; if (i === len - 1) closerV = path.v[0]; else closerV = path.v[i + 1]; distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0; oX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; vX = oX; oY = currentV[1] + (closerV[1] - currentV[1]) * newPosPerc; vY = oY; iX = vX - (vX - currentV[0]) * roundCorner; iY = vY - (vY - currentV[1]) * roundCorner; clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2); index2 += 1; } else { clonedPath.setTripleAt(path.v[i][0], path.v[i][1], path.o[i][0], path.o[i][1], path.i[i][0], path.i[i][1], index2); index2 += 1; } } return clonedPath; }; RoundCornersModifier.prototype.processShapes = function(_isFirstFrame) { var shapePaths; var i; var len = this.shapes.length; var j; var jLen; var rd = this.rd.v; if (rd !== 0) { var shapeData; var localShapeCollection; for (i = 0; i < len; i += 1) { shapeData = this.shapes[i]; localShapeCollection = shapeData.localShapeCollection; if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) { localShapeCollection.releaseShapes(); shapeData.shape._mdf = true; shapePaths = shapeData.shape.paths.shapes; jLen = shapeData.shape.paths._length; for (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 styles = fontData.fStyle ? fontData.fStyle.split(" ") : []; var fWeight = "normal"; var fStyle = "normal"; var len = styles.length; var styleName; for (var i = 0; i < len; i += 1) { styleName = styles[i].toLowerCase(); switch (styleName) { case "italic": fStyle = "italic"; break; case "bold": fWeight = "700"; break; case "black": fWeight = "900"; break; case "medium": fWeight = "500"; break; case "regular": case "normal": fWeight = "400"; break; case "light": case "thin": fWeight = "200"; break; } } 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 i; var len = familyArray.length; var enabledFamilies = []; for (i = 0; i < len; i += 1) if (familyArray[i] !== "sans-serif" && familyArray[i] !== "monospace") enabledFamilies.push(familyArray[i]); return enabledFamilies.join(","); } function setUpNode(font, family) { var parentNode = createTag("span"); parentNode.setAttribute("aria-hidden", true); parentNode.style.fontFamily = family; var node = createTag("span"); node.innerText = "giItT1WQy@!-/#"; parentNode.style.position = "absolute"; parentNode.style.left = "-10000px"; parentNode.style.top = "-10000px"; parentNode.style.fontSize = "300px"; parentNode.style.fontVariant = "normal"; parentNode.style.fontStyle = "normal"; parentNode.style.fontWeight = "normal"; parentNode.style.letterSpacing = "0"; parentNode.appendChild(node); document.body.appendChild(parentNode); var width = node.offsetWidth; node.style.fontFamily = trimFontOptions(font) + ", " + family; return { node, w: width, parent: parentNode }; } function checkLoadedFonts() { var i; var len = this.fonts.length; var node; var w; var loadedCount = len; for (i = 0; i < len; i += 1) if (this.fonts[i].loaded) loadedCount -= 1; else if (this.fonts[i].fOrigin === "n" || this.fonts[i].origin === 0) this.fonts[i].loaded = true; else { node = this.fonts[i].monoCase.node; w = this.fonts[i].monoCase.w; if (node.offsetWidth !== w) { loadedCount -= 1; this.fonts[i].loaded = true; } else { node = this.fonts[i].sansCase.node; w = this.fonts[i].sansCase.w; if (node.offsetWidth !== w) { loadedCount -= 1; this.fonts[i].loaded = true; } } if (this.fonts[i].loaded) { this.fonts[i].sansCase.parent.parentNode.removeChild(this.fonts[i].sansCase.parent); this.fonts[i].monoCase.parent.parentNode.removeChild(this.fonts[i].monoCase.parent); } } if (loadedCount !== 0 && Date.now() - this.initTime < maxWaitingTime) setTimeout(this.checkLoadedFontsBinded, 20); else setTimeout(this.setIsLoadedBinded, 10); } function createHelper(fontData, def) { var engine = document.body && def ? "svg" : "canvas"; var helper; var fontProps = getFontProperties(fontData); if (engine === "svg") { var tHelper = createNS("text"); tHelper.style.fontSize = "100px"; tHelper.setAttribute("font-family", fontData.fFamily); tHelper.setAttribute("font-style", fontProps.style); tHelper.setAttribute("font-weight", fontProps.weight); tHelper.textContent = "1"; if (fontData.fClass) { tHelper.style.fontFamily = "inherit"; tHelper.setAttribute("class", fontData.fClass); } else tHelper.style.fontFamily = fontData.fFamily; def.appendChild(tHelper); helper = tHelper; } else { var tCanvasHelper = new OffscreenCanvas(500, 500).getContext("2d"); tCanvasHelper.font = fontProps.style + " " + fontProps.weight + " 100px " + fontData.fFamily; helper = tCanvasHelper; } function measure(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 i; var len = fontArr.length; var _pendingFonts = len; for (i = 0; i < len; i += 1) { var shouldLoadFont = true; var loadedSelector; var j; fontArr[i].loaded = false; fontArr[i].monoCase = setUpNode(fontArr[i].fFamily, "monospace"); fontArr[i].sansCase = setUpNode(fontArr[i].fFamily, "sans-serif"); if (!fontArr[i].fPath) { fontArr[i].loaded = true; _pendingFonts -= 1; } else if (fontArr[i].fOrigin === "p" || fontArr[i].origin === 3) { loadedSelector = document.querySelectorAll("style[f-forigin=\"p\"][f-family=\"" + fontArr[i].fFamily + "\"], style[f-origin=\"3\"][f-family=\"" + fontArr[i].fFamily + "\"]"); if (loadedSelector.length > 0) shouldLoadFont = false; if (shouldLoadFont) { var s = createTag("style"); s.setAttribute("f-forigin", fontArr[i].fOrigin); s.setAttribute("f-origin", fontArr[i].origin); s.setAttribute("f-family", fontArr[i].fFamily); s.type = "text/css"; s.innerText = "@font-face {font-family: " + fontArr[i].fFamily + "; font-style: normal; src: url('" + fontArr[i].fPath + "');}"; defs.appendChild(s); } } else if (fontArr[i].fOrigin === "g" || fontArr[i].origin === 1) { loadedSelector = document.querySelectorAll("link[f-forigin=\"g\"], link[f-origin=\"1\"]"); for (j = 0; j < loadedSelector.length; j += 1) if (loadedSelector[j].href.indexOf(fontArr[i].fPath) !== -1) shouldLoadFont = false; if (shouldLoadFont) { var l = createTag("link"); l.setAttribute("f-forigin", fontArr[i].fOrigin); l.setAttribute("f-origin", fontArr[i].origin); l.type = "text/css"; l.rel = "stylesheet"; l.href = fontArr[i].fPath; document.body.appendChild(l); } } else if (fontArr[i].fOrigin === "t" || fontArr[i].origin === 2) { loadedSelector = document.querySelectorAll("script[f-forigin=\"t\"], script[f-origin=\"2\"]"); for (j = 0; j < loadedSelector.length; j += 1) if (fontArr[i].fPath === loadedSelector[j].src) shouldLoadFont = false; if (shouldLoadFont) { var sc = createTag("link"); sc.setAttribute("f-forigin", fontArr[i].fOrigin); sc.setAttribute("f-origin", fontArr[i].origin); sc.setAttribute("rel", "stylesheet"); sc.setAttribute("href", fontArr[i].fPath); defs.appendChild(sc); } } fontArr[i].helper = createHelper(fontArr[i], defs); fontArr[i].cache = {}; this.fonts.push(fontArr[i]); } if (_pendingFonts === 0) this.isLoaded = true; else setTimeout(this.checkLoadedFonts.bind(this), 100); } function addChars(chars) { if (!chars) return; if (!this.chars) this.chars = []; var i; var len = chars.length; var j; var jLen = this.chars.length; var found; for (i = 0; i < len; i += 1) { j = 0; found = false; while (j < jLen) { if (this.chars[j].style === chars[i].style && this.chars[j].fFamily === chars[i].fFamily && this.chars[j].ch === chars[i].ch) found = true; j += 1; } if (!found) { this.chars.push(chars[i]); jLen += 1; } } } function getCharData(char, style, font) { var i = 0; var len = this.chars.length; while (i < len) { if (this.chars[i].ch === char && this.chars[i].style === style && this.chars[i].fFamily === font) return this.chars[i]; i += 1; } if ((typeof char === "string" && char.charCodeAt(0) !== 13 || !char) && console && console.warn && !this._warned) { this._warned = true; console.warn("Missing character from exported characters list: ", char, style, font); } return emptyChar; } function measureText(char, fontName, size) { var fontData = this.getFontByName(fontName); var index2 = char.charCodeAt(0); if (!fontData.cache[index2 + 1]) { var tHelper = fontData.helper; if (char === " ") { var doubleSize = tHelper.measureText("|" + char + "|"); var singleSize = tHelper.measureText("||"); fontData.cache[index2 + 1] = (doubleSize - singleSize) / 100; } else fontData.cache[index2 + 1] = tHelper.measureText(char) / 100; } return fontData.cache[index2 + 1] * size; } function getFontByName(name) { var i = 0; var len = this.fonts.length; while (i < len) { if (this.fonts[i].fName === name) return this.fonts[i]; i += 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 Font = 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); }; Font.isModifier = isModifier; Font.isZeroWidthJoiner = isZeroWidthJoiner; Font.isCombinedCharacter = isCombinedCharacter; Font.prototype = { addChars, addFonts, getCharData, getFontByName, measureText, checkLoadedFonts, setIsLoaded }; return Font; }(); 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 i; var len = this.renderableComponents.length; for (i = 0; i < len; i += 1) this.renderableComponents[i].renderFrame(this._isFirstFrame); }, sourceRectAtTime: function() { return { top: 0, left: 0, width: 100, height: 100 }; }, getLayerSize: function() { if (this.data.ty === 5) return { w: this.data.textData.width, h: this.data.textData.height }; return { w: this.data.width, h: this.data.height }; } }; const MaskManagerInterface = function() { function MaskInterface(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 i; var len = maskManager.viewData.length; for (i = 0; i < len; i += 1) _masksInterfaces[i] = new MaskInterface(maskManager.viewData[i], maskManager.masksProperties[i]); var maskFunction = function(name) { i = 0; while (i < len) { if (maskManager.masksProperties[i].nm === name) return _masksInterfaces[i]; i += 1; } return null; }; return maskFunction; }; return MaskManager; }(); const ExpressionPropertyInterface = 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 i = 0; i < len; i += 1) { arrValue[i] = property.v[i] * mult; expressionValue[i] = arrValue[i]; } 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 = 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 = function() { function getMatrix(time) { var toWorldMat = new Matrix(); if (time !== void 0) this._elem.finalTransform.mProp.getValueAtTime(time).clone(toWorldMat); else this._elem.finalTransform.mProp.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(matrix, arr) { if (this._elem.hierarchy && this._elem.hierarchy.length) { var i; var len = this._elem.hierarchy.length; for (i = 0; i < len; i += 1) this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); } return matrix.applyToPointArray(arr[0], arr[1], arr[2] || 0); } function invertPoint(matrix, arr) { if (this._elem.hierarchy && this._elem.hierarchy.length) { var i; var len = this._elem.hierarchy.length; for (i = 0; i < len; i += 1) this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); } return matrix.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 i; var len = this._elem.hierarchy.length; for (i = 0; i < len; i += 1) this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(toWorldMat); return toWorldMat.inversePoint(arr); } return toWorldMat.inversePoint(arr); } function sampleImage() { return [ 1, 1, 1, 1 ]; } return function(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 = 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 = 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 = function() { var ob = { createEffectsInterface }; function createEffectsInterface(elem, propertyGroup) { if (elem.effectsManager) { var effectElements = []; var effectsData = elem.data.ef; var i; var len = elem.effectsManager.effectElements.length; for (i = 0; i < len; i += 1) effectElements.push(createGroupInterface(effectsData[i], elem.effectsManager.effectElements[i], propertyGroup, elem)); var effects = elem.data.ef || []; var groupInterface = function(name) { i = 0; len = effects.length; while (i < len) { if (name === effects[i].nm || name === effects[i].mn || name === effects[i].ix) return effectElements[i]; i += 1; } return null; }; Object.defineProperty(groupInterface, "numProperties", { get: function() { return effects.length; } }); return groupInterface; } return null; } function createGroupInterface(data, elements, propertyGroup, elem) { function groupInterface(name) { var effects = data.ef; var i2 = 0; var len2 = effects.length; while (i2 < len2) { if (name === effects[i2].nm || name === effects[i2].mn || name === effects[i2].ix) { if (effects[i2].ty === 5) return effectElements[i2]; return effectElements[i2](); } i2 += 1; } throw new Error(); } var _propertyGroup = propertyGroupFactory(groupInterface, propertyGroup); var effectElements = []; var i; var len = data.ef.length; for (i = 0; i < len; i += 1) if (data.ef[i].ty === 5) effectElements.push(createGroupInterface(data.ef[i], elements.effectElements[i], elements.effectElements[i].propertyGroup, elem)); else effectElements.push(createValueInterface(elements.effectElements[i], data.ef[i].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 = function() { return function(comp) { function _thisLayerFunction(name) { var i = 0; var len = comp.layers.length; while (i < len) { if (comp.layers[i].nm === name || comp.layers[i].ind === name) return comp.elements[i].layerInterface; i += 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 = 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 = function() { function iterateElements(shapes, view, propertyGroup) { var arr = []; var i; var len = shapes ? shapes.length : 0; for (i = 0; i < len; i += 1) if (shapes[i].ty === "gr") arr.push(groupInterfaceFactory(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "fl") arr.push(fillInterfaceFactory(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "st") arr.push(strokeInterfaceFactory(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "tm") arr.push(trimInterfaceFactory(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "tr"); else if (shapes[i].ty === "el") arr.push(ellipseInterfaceFactory(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "sr") arr.push(starInterfaceFactory(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "sh") arr.push(ShapePathInterface(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "rc") arr.push(rectInterfaceFactory(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "rd") arr.push(roundedInterfaceFactory(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "rp") arr.push(repeaterInterfaceFactory(shapes[i], view[i], propertyGroup)); else if (shapes[i].ty === "gf") arr.push(gradientFillInterfaceFactory(shapes[i], view[i], propertyGroup)); else arr.push(defaultInterfaceFactory(shapes[i], view[i])); return arr; } function contentsInterfaceFactory(shape, view, propertyGroup) { var interfaces; var interfaceFunction = function _interfaceFunction(value) { var i = 0; var len = interfaces.length; while (i < len) { if (interfaces[i]._name === value || interfaces[i].mn === value || interfaces[i].propertyIndex === value || interfaces[i].ix === value || interfaces[i].ind === value) return interfaces[i]; i += 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; interfaceFunction.transform = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup); 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(i2) { Object.defineProperty(dashOb, shape.d[i2].nm, { get: ExpressionPropertyInterface(view.d.dataProps[i2].p) }); } var i; var len = shape.d ? shape.d.length : 0; var dashOb = {}; for (i = 0; i < len; i += 1) { addPropertyToDashOb(i); view.d.dataProps[i].p.setGroupProperty(_dashPropertyGroup); } function interfaceFunction(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 i = 0; var len = interfaces.length; while (i < len) { if (interfaces[i]._name === value) return interfaces[i]; i += 1; } return null; } function parentGroupWrapper() { return propertyGroup; } _interfaceFunction.propertyGroup = propertyGroupFactory(_interfaceFunction, parentGroupWrapper); interfaces = iterateElements(shapes, view, _interfaceFunction.propertyGroup); _interfaceFunction.numProperties = interfaces.length; _interfaceFunction._name = "Contents"; return _interfaceFunction; }; }(); const TextExpressionInterface = 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 = 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 i; var len = effects.length; var effectItem; for (i = 0; i < len; i += 1) { effectItem = new GroupEffect(effects[i], element); this.effectElements.push(effectItem); } } function GroupEffect(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 i; var len = this.data.ef.length; var eff; var effects = this.data.ef; for (i = 0; i < len; i += 1) { eff = null; switch (effects[i].ty) { case 0: eff = new SliderEffect(effects[i], element, this); break; case 1: eff = new AngleEffect(effects[i], element, this); break; case 2: eff = new ColorEffect(effects[i], element, this); break; case 3: eff = new PointEffect(effects[i], element, this); break; case 4: case 7: eff = new CheckboxEffect(effects[i], element, this); break; case 10: eff = new LayerIndexEffect(effects[i], element, this); break; case 11: eff = new MaskIndexEffect(effects[i], element, this); break; case 5: eff = new EffectsManager(effects[i], element); break; default: eff = new NoValueEffect(effects[i]); break; } if (eff) this.effectElements.push(eff); } }; function BaseElement() {} BaseElement.prototype = { checkMasks: function() { if (!this.data.hasMask) return false; var i = 0; var len = this.data.masksProperties.length; while (i < len) { if (this.data.masksProperties[i].mode !== "n" && this.data.masksProperties[i].cl !== false) return true; i += 1; } return false; }, initExpressions: function() { this.layerInterface = LayerExpressionInterface(this); if (this.data.hasMask && this.maskManager) this.layerInterface.registerMaskInterface(this.maskManager); var effectsInterface = EffectsExpressionInterface.createEffectsInterface(this, this.layerInterface); this.layerInterface.registerEffectsInterface(effectsInterface); if (this.data.ty === 0 || this.data.xt) this.compInterface = CompExpressionInterface(this); else if (this.data.ty === 4) { this.layerInterface.shapeInterface = ShapeExpressionInterface(this.shapesData, this.itemsData, this.layerInterface); this.layerInterface.content = this.layerInterface.shapeInterface; } else if (this.data.ty === 5) { this.layerInterface.textInterface = TextExpressionInterface(this); this.layerInterface.text = this.layerInterface.textInterface; } }, setBlendMode: function() { var blendModeValue = getBlendMode(this.data.bm); var 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 i; var len = this.dynamicProperties.length; for (i = 0; i < len; i += 1) if (isVisible || this._isParent && this.dynamicProperties[i].propType === "transform") { this.dynamicProperties[i].getValue(); if (this.dynamicProperties[i]._mdf) { this.globalData._mdf = true; this._mdf = true; } } }, addDynamicProperty: function(prop) { if (this.dynamicProperties.indexOf(prop) === -1) this.dynamicProperties.push(prop); } }; const FootageInterface = function() { var outlineInterfaceFactory = function(elem) { var currentPropertyName = ""; var currentProperty = elem.getFootageData(); function init() { 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 index2 = parseInt(value.substr(propertyNameIndex + currentPropertyName.length), 10); currentProperty = currentProperty[index2]; if (typeof currentProperty === "object") return searchProperty; return currentProperty; } return ""; } return init; }; 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, .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()) > .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 i; var len = this.layers.length; var data; this.completeLayers = true; for (i = len - 1; i >= 0; i -= 1) { if (!this.elements[i]) { data = this.layers[i]; if (data.ip - data.st <= num - this.layers[i].st && data.op - data.st > num - this.layers[i].st) this.buildItem(i); } this.completeLayers = this.elements[i] ? this.completeLayers : false; } this.checkPendingElements(); }; BaseRenderer.prototype.createItem = function(layer) { switch (layer.ty) { case 2: return this.createImage(layer); case 0: return this.createComp(layer); case 1: return this.createSolid(layer); case 3: return this.createNull(layer); case 4: return this.createShape(layer); case 5: return this.createText(layer); case 6: return this.createAudio(layer); case 13: return this.createCamera(layer); case 15: return this.createFootage(layer); default: return this.createNull(layer); } }; BaseRenderer.prototype.createCamera = function() { throw new Error("You're using a 3d camera. Try the html renderer."); }; BaseRenderer.prototype.createAudio = function(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 i; var len = this.layers.length; for (i = 0; i < len; i += 1) this.buildItem(i); this.checkPendingElements(); }; BaseRenderer.prototype.includeLayers = function(newLayers) { this.completeLayers = false; var i; var len = newLayers.length; var j; var jLen = this.layers.length; for (i = 0; i < len; i += 1) { j = 0; while (j < jLen) { if (this.layers[j].id === newLayers[i].id) { this.layers[j] = newLayers[i]; 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 i = 0; var len = layers.length; while (i < len) { if (layers[i].ind == parentName) if (!elements[i] || elements[i] === true) { this.buildItem(i); this.addPendingElement(element); } else { hierarchy.push(elements[i]); elements[i].setAsParent(); if (layers[i].parent !== void 0) this.buildElementParenting(element, layers[i].parent, hierarchy); else element.setHierarchy(hierarchy); } i += 1; } }; BaseRenderer.prototype.addPendingElement = function(element) { this.pendingElements.push(element); }; BaseRenderer.prototype.searchExtraCompositions = function(assets) { var i; var len = assets.length; for (i = 0; i < len; i += 1) if (assets[i].xt) { var comp = this.createComp(assets[i]); 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 i; var len = this.elements.length; for (i = 0; i < len; i += 1) if (this.elements[i].data.nm === pathValue) { element = this.elements[i]; break; } } if (path.length === 0) return element; return element.getElementByPath(path); }; BaseRenderer.prototype.setupGlobalData = function(animData, fontsContainer) { this.globalData.fontManager = new FontManager(); this.globalData.fontManager.addChars(animData.chars); this.globalData.fontManager.addFonts(animData.fonts, fontsContainer); this.globalData.getAssetData = this.animationItem.getAssetData.bind(this.animationItem); this.globalData.getAssetsPath = this.animationItem.getAssetsPath.bind(this.animationItem); this.globalData.imageLoader = this.animationItem.imagePreloader; this.globalData.audioController = this.animationItem.audioController; this.globalData.frameId = 0; this.globalData.frameRate = animData.fr; this.globalData.nm = animData.nm; this.globalData.compSize = { w: animData.w, h: animData.h }; }; 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 mat; var finalMat = this.finalTransform.mat; var i = 0; var len = this.hierarchy.length; if (!this.finalTransform._matMdf) while (i < len) { if (this.hierarchy[i].finalTransform.mProp._mdf) { this.finalTransform._matMdf = true; break; } i += 1; } if (this.finalTransform._matMdf) { mat = this.finalTransform.mProp.v.props; finalMat.cloneFromProps(mat); for (i = 0; i < len; i += 1) { mat = this.hierarchy[i].finalTransform.mProp.v.props; finalMat.transform(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6], mat[7], mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15]); } } } }, globalToLocal: function(pt) { var transforms = []; transforms.push(this.finalTransform); var flag = true; var 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 i; var len = transforms.length; var ptNew; for (i = 0; i < len; i += 1) { ptNew = transforms[i].mat.applyToPointArray(0, 0, 0); pt = [ pt[0] - ptNew[0], pt[1] - ptNew[1], 0 ]; } return pt; }, mHelper: new Matrix() }; 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 i; var len = this.masksProperties ? this.masksProperties.length : 0; this.viewData = createSizedArray(len); this.solidPath = ""; var path; var properties = this.masksProperties; var count = 0; var currentMasks = []; var j; var jLen; var layerId = createElementID(); var rect; var expansor; var feMorph; var x; var maskType = "clipPath"; var maskRef = "clip-path"; for (i = 0; i < len; i += 1) { if (properties[i].mode !== "a" && properties[i].mode !== "n" || properties[i].inv || properties[i].o.k !== 100 || properties[i].o.x) { maskType = "mask"; maskRef = "mask"; } if ((properties[i].mode === "s" || properties[i].mode === "i") && count === 0) { rect = createNS("rect"); rect.setAttribute("fill", "#ffffff"); rect.setAttribute("width", this.element.comp.data.w || 0); rect.setAttribute("height", this.element.comp.data.h || 0); currentMasks.push(rect); } else rect = null; path = createNS("path"); if (properties[i].mode === "n") { this.viewData[i] = { op: PropertyFactory.getProp(this.element, properties[i].o, 0, .01, this.element), prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3), elem: path, lastPath: "" }; defs.appendChild(path); } else { count += 1; path.setAttribute("fill", properties[i].mode === "s" ? "#000000" : "#ffffff"); path.setAttribute("clip-rule", "nonzero"); var filterID; if (properties[i].x.k !== 0) { maskType = "mask"; maskRef = "mask"; x = PropertyFactory.getProp(this.element, properties[i].x, 0, null, this.element); filterID = createElementID(); expansor = createNS("filter"); expansor.setAttribute("id", filterID); feMorph = createNS("feMorphology"); feMorph.setAttribute("operator", "erode"); feMorph.setAttribute("in", "SourceGraphic"); feMorph.setAttribute("radius", "0"); expansor.appendChild(feMorph); defs.appendChild(expansor); path.setAttribute("stroke", properties[i].mode === "s" ? "#000000" : "#ffffff"); } else { feMorph = null; x = null; } this.storedData[i] = { elem: path, x, expan: feMorph, lastPath: "", lastOperator: "", filterId: filterID, lastRadius: 0 }; if (properties[i].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[i].inv && !this.solidPath) this.solidPath = this.createLayerSolidPath(); this.viewData[i] = { elem: path, lastPath: "", op: PropertyFactory.getProp(this.element, properties[i].o, 0, .01, this.element), prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3), invRect: rect }; if (!this.viewData[i].prop.k) this.drawPath(properties[i], this.viewData[i].prop.v, this.viewData[i]); } } this.maskElement = createNS(maskType); len = currentMasks.length; for (i = 0; i < len; i += 1) this.maskElement.appendChild(currentMasks[i]); if (count > 0) { this.maskElement.setAttribute("id", layerId); this.element.maskedElement.setAttribute(maskRef, "url(" + getLocationHref() + "#" + layerId + ")"); defs.appendChild(this.maskElement); } if (this.viewData.length) this.element.addRenderableComponent(this); } MaskElement.prototype.getMaskProperty = function(pos) { return this.viewData[pos].prop; }; MaskElement.prototype.renderFrame = function(isFirstFrame) { var finalMat = this.element.finalTransform.mat; var i; var len = this.masksProperties.length; for (i = 0; i < len; i += 1) { if (this.viewData[i].prop._mdf || isFirstFrame) this.drawPath(this.masksProperties[i], this.viewData[i].prop.v, this.viewData[i]); if (this.viewData[i].op._mdf || isFirstFrame) this.viewData[i].elem.setAttribute("fill-opacity", this.viewData[i].op.v); if (this.masksProperties[i].mode !== "n") { if (this.viewData[i].invRect && (this.element.finalTransform.mProp._mdf || isFirstFrame)) this.viewData[i].invRect.setAttribute("transform", finalMat.getInverseMatrix().to2dCSS()); if (this.storedData[i].x && (this.storedData[i].x._mdf || isFirstFrame)) { var feMorph = this.storedData[i].expan; if (this.storedData[i].x.v < 0) { if (this.storedData[i].lastOperator !== "erode") { this.storedData[i].lastOperator = "erode"; this.storedData[i].elem.setAttribute("filter", "url(" + getLocationHref() + "#" + this.storedData[i].filterId + ")"); } feMorph.setAttribute("radius", -this.storedData[i].x.v); } else { if (this.storedData[i].lastOperator !== "dilate") { this.storedData[i].lastOperator = "dilate"; this.storedData[i].elem.setAttribute("filter", null); } this.storedData[i].elem.setAttribute("stroke-width", this.storedData[i].x.v * 2); } } } } }; MaskElement.prototype.getMaskelement = function() { return this.maskElement; }; MaskElement.prototype.createLayerSolidPath = function() { var path = "M0,0 "; path += " h" + this.globalData.compSize.w; path += " v" + this.globalData.compSize.h; path += " h-" + this.globalData.compSize.w; path += " v-" + this.globalData.compSize.h + " "; return path; }; MaskElement.prototype.drawPath = function(pathData, pathNodes, viewData) { var pathString = " M" + pathNodes.v[0][0] + "," + pathNodes.v[0][1]; var i; var len = pathNodes._length; for (i = 1; i < len; i += 1) pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[i][0] + "," + pathNodes.i[i][1] + " " + pathNodes.v[i][0] + "," + pathNodes.v[i][1]; if (pathNodes.c && len > 1) pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[0][0] + "," + pathNodes.i[0][1] + " " + pathNodes.v[0][0] + "," + pathNodes.v[0][1]; if (viewData.lastPath !== pathString) { var pathShapeValue = ""; if (viewData.elem) { if (pathNodes.c) pathShapeValue = pathData.inv ? this.solidPath + pathString : pathString; viewData.elem.setAttribute("d", pathShapeValue); } viewData.lastPath = pathString; } }; MaskElement.prototype.destroy = function() { this.element = null; this.globalData = null; this.maskElement = null; this.data = null; this.masksProperties = null; }; const filtersFactory = function() { var 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 i; 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 (i = 0; i < len; i += 1) { filterManager = null; var type = elem.data.ef[i].ty; if (registeredEffects[type]) { var Effect = registeredEffects[type].effect; filterManager = new Effect(fil, elem.effectsManager.effectElements[i], 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 i; var len = this.filters.length; for (i = 0; i < len; i += 1) this.filters[i].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() { extendPrototype([RenderableElement, createProxyFunction({ 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(); } })], 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, position) { this.elem = element; this.pos = position; } function IShapeElement() {} IShapeElement.prototype = { addShapeToModifiers: function(data) { var i; var len = this.shapeModifiers.length; for (i = 0; i < len; i += 1) this.shapeModifiers[i].addShape(data); }, isShapeInAnimatedModifiers: function(data) { var i = 0; var len = this.shapeModifiers.length; while (i < len) if (this.shapeModifiers[i].isAnimatedWithShape(data)) return true; return false; }, renderModifiers: function() { if (!this.shapeModifiers.length) return; var i; var len = this.shapes.length; for (i = 0; i < len; i += 1) this.shapes[i].sh.reset(); len = this.shapeModifiers.length; var shouldBreakProcess; for (i = len - 1; i >= 0; i -= 1) { shouldBreakProcess = this.shapeModifiers[i].processShapes(this._isFirstFrame); if (shouldBreakProcess) break; } }, searchProcessedElement: function(elem) { var elements = this.processedElements; var i = 0; var len = elements.length; while (i < len) { if (elements[i].elem === elem) return elements[i].pos; i += 1; } return 0; }, addProcessedElement: function(elem, pos) { var elements = this.processedElements; var i = elements.length; while (i) { i -= 1; if (elements[i].elem === elem) { elements[i].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 i = 0; var len = transformers.length; while (i < len) { if (transformers[i].mProps.dynamicProperties.length) { this._isAnimated = true; break; } i += 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 i; var len = data.length || 0; var prop; for (i = 0; i < len; i += 1) { prop = PropertyFactory.getProp(elem, data[i].v, 0, 0, this); this.k = prop.k || this.k; this.dataProps[i] = { n: data[i].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 i = 0; var len = this.dataProps.length; if (this.renderer === "svg") this.dashStr = ""; for (i = 0; i < len; i += 1) if (this.dataProps[i].n !== "o") if (this.renderer === "svg") this.dashStr += " " + this.dataProps[i].p.v; else this.dashArray[i] = this.dataProps[i].p.v; else this.dashoffset[0] = this.dataProps[i].p.v; } }; extendPrototype([DynamicPropertyContainer], DashProperty); function SVGStrokeStyleData(elem, data, styleOb) { this.initDynamicPropertyContainer(elem); this.getValue = this.iterateDynamicProperties; this.o = PropertyFactory.getProp(elem, data.o, 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, .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 i = 0; var len = this.o.length / 2; var diff; while (i < len) { diff = Math.abs(values[i * 4] - values[points * 4 + i * 2]); if (diff > .01) return false; i += 1; } return true; }; GradientProperty.prototype.checkCollapsable = function() { if (this.o.length / 2 !== this.c.length / 4) return false; if (this.data.k.k[0].s) { var i = 0; var len = this.data.k.k.length; while (i < len) { if (!this.comparePoints(this.data.k.k[i].s, this.data.p)) return false; i += 1; } } else if (!this.comparePoints(this.data.k.k, this.data.p)) return false; return true; }; GradientProperty.prototype.getValue = function(forceRender) { this.prop.getValue(); this._mdf = false; this._cmdf = false; this._omdf = false; if (this.prop._mdf || forceRender) { var i; var len = this.data.p * 4; var mult; var val; for (i = 0; i < len; i += 1) { mult = i % 4 === 0 ? 100 : 255; val = Math.round(this.prop.v[i] * mult); if (this.c[i] !== val) { this.c[i] = val; this._cmdf = !forceRender; } } if (this.o.length) { len = this.prop.v.length; for (i = this.data.p * 4; i < len; i += 1) { mult = i % 2 === 0 ? 100 : 1; val = i % 2 === 0 ? Math.round(this.prop.v[i] * 100) : this.prop.v[i]; if (this.o[i - this.data.p * 4] !== val) { this.o[i - 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, .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, .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 = 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, length, closed, mat) { if (length === 0) return ""; var _o = pathNodes.o; var _i = pathNodes.i; var _v = pathNodes.v; var i; var shapeString = " M" + mat.applyToPointStringified(_v[0][0], _v[0][1]); for (i = 1; i < length; i += 1) shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[i][0], _i[i][1]) + " " + mat.applyToPointStringified(_v[i][0], _v[i][1]); if (closed && length) { shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[0][0], _i[0][1]) + " " + mat.applyToPointStringified(_v[0][0], _v[0][1]); shapeString += "z"; } return shapeString; }; const SVGElementsRenderer = function() { var _identityMatrix = 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 l; var lLen = itemData.styles.length; var lvl = itemData.lvl; var paths; var mat; var props; var iterations; var k; for (l = 0; l < lLen; l += 1) { redraw = itemData.sh._mdf || isFirstFrame; if (itemData.styles[l].lvl < lvl) { mat = _matrixHelper.reset(); iterations = lvl - itemData.styles[l].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[l].lvl; k = itemData.transformers.length - 1; while (iterations > 0) { props = itemData.transformers[k].mProps.v.props; mat.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]); iterations -= 1; k -= 1; } } } else mat = _identityMatrix; 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, mat); } itemData.caches[l] = pathStringTransformed; } else pathStringTransformed = itemData.caches[l]; itemData.styles[l].d += styleData.hd === true ? "" : pathStringTransformed; itemData.styles[l]._mdf = redraw || itemData.styles[l]._mdf; } } function renderFill(styleData, itemData, isFirstFrame) { var styleElem = itemData.style; if (itemData.c._mdf || isFirstFrame) styleElem.pElem.setAttribute("fill", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"); if (itemData.o._mdf || isFirstFrame) styleElem.pElem.setAttribute("fill-opacity", itemData.o.v); } function renderGradientStroke(styleData, itemData, isFirstFrame) { renderGradient(styleData, itemData, isFirstFrame); renderStroke(styleData, itemData, isFirstFrame); } function renderGradient(styleData, itemData, isFirstFrame) { var gfill = itemData.gf; var hasOpacity = itemData.g._hasOpacity; var pt1 = itemData.s.v; var pt2 = itemData.e.v; if (itemData.o._mdf || isFirstFrame) { var attr = styleData.ty === "gf" ? "fill-opacity" : "stroke-opacity"; itemData.style.pElem.setAttribute(attr, itemData.o.v); } if (itemData.s._mdf || isFirstFrame) { var attr1 = styleData.t === 1 ? "x1" : "cx"; var attr2 = attr1 === "x1" ? "y1" : "cy"; gfill.setAttribute(attr1, pt1[0]); gfill.setAttribute(attr2, pt1[1]); if (hasOpacity && !itemData.g._collapsable) { itemData.of.setAttribute(attr1, pt1[0]); itemData.of.setAttribute(attr2, pt1[1]); } } var stops; var i; var len; var stop; if (itemData.g._cmdf || isFirstFrame) { stops = itemData.cst; var cValues = itemData.g.c; len = stops.length; for (i = 0; i < len; i += 1) { stop = stops[i]; stop.setAttribute("offset", cValues[i * 4] + "%"); stop.setAttribute("stop-color", "rgb(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + ")"); } } if (hasOpacity && (itemData.g._omdf || isFirstFrame)) { var oValues = itemData.g.o; if (itemData.g._collapsable) stops = itemData.cst; else stops = itemData.ost; len = stops.length; for (i = 0; i < len; i += 1) { stop = stops[i]; if (!itemData.g._collapsable) stop.setAttribute("offset", oValues[i * 2] + "%"); stop.setAttribute("stop-opacity", oValues[i * 2 + 1]); } } if (styleData.t === 1) { if (itemData.e._mdf || isFirstFrame) { gfill.setAttribute("x2", pt2[0]); gfill.setAttribute("y2", pt2[1]); if (hasOpacity && !itemData.g._collapsable) { itemData.of.setAttribute("x2", pt2[0]); itemData.of.setAttribute("y2", pt2[1]); } } } else { var rad; if (itemData.s._mdf || itemData.e._mdf || isFirstFrame) { rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); gfill.setAttribute("r", rad); if (hasOpacity && !itemData.g._collapsable) itemData.of.setAttribute("r", rad); } if (itemData.e._mdf || itemData.h._mdf || itemData.a._mdf || isFirstFrame) { if (!rad) rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]); var percent = itemData.h.v; if (percent >= 1) percent = .99; else if (percent <= -1) percent = -.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 d = itemData.d; if (d && (d._mdf || isFirstFrame) && d.dashStr) { styleElem.pElem.setAttribute("stroke-dasharray", d.dashStr); styleElem.pElem.setAttribute("stroke-dashoffset", d.dashoffset[0]); } if (itemData.c && (itemData.c._mdf || isFirstFrame)) styleElem.pElem.setAttribute("stroke", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"); if (itemData.o._mdf || isFirstFrame) styleElem.pElem.setAttribute("stroke-opacity", itemData.o.v); if (itemData.w._mdf || isFirstFrame) { styleElem.pElem.setAttribute("stroke-width", itemData.w.v); if (styleElem.msElem) styleElem.msElem.setAttribute("stroke-width", itemData.w.v); } } return 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 i; 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 (i = 0; i < len; i += 1) { shape = this.shapes[i]; if (shape.styles.indexOf(style) !== -1) { tempShapes.push(shape); areAnimated = shape._isAnimated || areAnimated; } } if (tempShapes.length > 1 && areAnimated) this.setShapesAsAnimated(tempShapes); } }; SVGShapeElement.prototype.setShapesAsAnimated = function(shapes) { var i; var len = shapes.length; for (i = 0; i < len; i += 1) shapes[i].setAsAnimated(); }; SVGShapeElement.prototype.createStyleElement = function(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") { elementData = new (data.ty === "gf" ? SVGGradientFillStyleData : SVGGradientStrokeStyleData)(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 elementData = new SVGShapeData(ownTransformers, level, ShapePropertyFactory.getShapeProp(this, data, ty, this)); this.shapes.push(elementData); this.addShapeToModifiers(elementData); this.addToAnimatedContents(data, elementData); return elementData; }; SVGShapeElement.prototype.addToAnimatedContents = function(data, element) { var i = 0; var len = this.animatedContents.length; while (i < len) { if (this.animatedContents[i].element === element) return; i += 1; } this.animatedContents.push({ fn: SVGElementsRenderer.createRenderFunction(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 i; var len = this.itemsData.length; for (i = 0; i < len; i += 1) this.prevViewData[i] = this.itemsData[i]; this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true); this.filterUniqueShapes(); len = this.dynamicProperties.length; for (i = 0; i < len; i += 1) this.dynamicProperties[i].getValue(); this.renderModifiers(); }; SVGShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, container, level, transformers, render) { var ownTransformers = [].concat(transformers); var i; var len = arr.length - 1; var j; var jLen; var ownStyles = []; var ownModifiers = []; var currentTransform; var modifier; var processedPos; for (i = len; i >= 0; i -= 1) { processedPos = this.searchProcessedElement(arr[i]); if (!processedPos) arr[i]._render = render; else itemsData[i] = prevViewData[processedPos - 1]; if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs" || arr[i].ty === "no") { if (!processedPos) itemsData[i] = this.createStyleElement(arr[i], level); else itemsData[i].style.closed = false; if (arr[i]._render) { if (itemsData[i].style.pElem.parentNode !== container) container.appendChild(itemsData[i].style.pElem); } ownStyles.push(itemsData[i].style); } else if (arr[i].ty === "gr") { if (!processedPos) itemsData[i] = this.createGroupElement(arr[i]); else { jLen = itemsData[i].it.length; for (j = 0; j < jLen; j += 1) itemsData[i].prevViewData[j] = itemsData[i].it[j]; } this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, itemsData[i].gr, level + 1, ownTransformers, render); if (arr[i]._render) { if (itemsData[i].gr.parentNode !== container) container.appendChild(itemsData[i].gr); } } else if (arr[i].ty === "tr") { if (!processedPos) itemsData[i] = this.createTransformElement(arr[i], container); currentTransform = itemsData[i].transform; ownTransformers.push(currentTransform); } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") { if (!processedPos) itemsData[i] = this.createShapeElement(arr[i], ownTransformers, level); this.setElementStyles(itemsData[i]); } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "ms" || arr[i].ty === "pb") { if (!processedPos) { modifier = ShapeModifiers.getModifier(arr[i].ty); modifier.init(this, arr[i]); itemsData[i] = modifier; this.shapeModifiers.push(modifier); } else { modifier = itemsData[i]; modifier.closed = false; } ownModifiers.push(modifier); } else if (arr[i].ty === "rp") { if (!processedPos) { modifier = ShapeModifiers.getModifier(arr[i].ty); itemsData[i] = modifier; modifier.init(this, arr, i, itemsData); this.shapeModifiers.push(modifier); render = false; } else { modifier = itemsData[i]; modifier.closed = true; } ownModifiers.push(modifier); } this.addProcessedElement(arr[i], i + 1); } len = ownStyles.length; for (i = 0; i < len; i += 1) ownStyles[i].closed = true; len = ownModifiers.length; for (i = 0; i < len; i += 1) ownModifiers[i].closed = true; }; SVGShapeElement.prototype.renderInnerContent = function() { this.renderModifiers(); var i; var len = this.stylesList.length; for (i = 0; i < len; i += 1) this.stylesList[i].reset(); this.renderShape(); for (i = 0; i < len; i += 1) if (this.stylesList[i]._mdf || this._isFirstFrame) { if (this.stylesList[i].msElem) { this.stylesList[i].msElem.setAttribute("d", this.stylesList[i].d); this.stylesList[i].d = "M0 0" + this.stylesList[i].d; } this.stylesList[i].pElem.setAttribute("d", this.stylesList[i].d || "M0 0"); } }; SVGShapeElement.prototype.renderShape = function() { var i; var len = this.animatedContents.length; var animatedContent; for (i = 0; i < len; i += 1) { animatedContent = this.animatedContents[i]; if ((this._isFirstFrame || animatedContent.element._isAnimated) && animatedContent.data !== true) animatedContent.fn(animatedContent.data, animatedContent.element, this._isFirstFrame); } }; SVGShapeElement.prototype.destroy = function() { this.destroyBaseElement(); this.shapesData = null; this.itemsData = null; }; function LetterProps(o, sw, sc, fc, m, p) { this.o = o; this.sw = sw; this.sc = sc; this.fc = fc; this.m = m; this.p = p; this._mdf = { o: true, sw: !!sw, sc: !!sc, fc: !!fc, m: true, p: true }; } LetterProps.prototype.update = function(o, sw, sc, fc, m, p) { this._mdf.o = false; this._mdf.sw = false; this._mdf.sc = false; this._mdf.fc = false; this._mdf.m = false; this._mdf.p = false; var updated = false; if (this.o !== o) { this.o = o; this._mdf.o = true; updated = true; } if (this.sw !== sw) { this.sw = sw; this._mdf.sw = true; updated = true; } if (this.sc !== sc) { this.sc = sc; this._mdf.sc = true; updated = true; } if (this.fc !== fc) { this.fc = fc; this._mdf.fc = true; updated = true; } if (this.m !== m) { this.m = m; this._mdf.m = true; updated = true; } if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) { this.p = p; this._mdf.p = true; updated = true; } return updated; }; 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 s in data) if (Object.prototype.hasOwnProperty.call(data, s)) obj[s] = data[s]; 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 i; var len = this.effectsSequence.length; var finalValue = _finalValue || this.data.d.k[this.keysIndex].s; for (i = 0; i < len; i += 1) if (currentIndex !== this.keysIndex) finalValue = this.effectsSequence[i](finalValue, finalValue.t); else finalValue = this.effectsSequence[i](this.currentData, finalValue.t); if (currentValue !== finalValue) this.setCurrentData(finalValue); this.v = this.currentData; this.pv = this.v; this.lock = false; this.frameId = this.elem.globalData.frameId; }; TextProperty.prototype.getKeyframeValue = function() { var textKeys = this.data.d.k; var frameNum = this.elem.comp.renderedFrame; var i = 0; var len = textKeys.length; while (i <= len - 1) { if (i === len - 1 || textKeys[i + 1].t > frameNum) break; i += 1; } if (this.keysIndex !== i) this.keysIndex = i; return this.data.d.k[this.keysIndex].s; }; TextProperty.prototype.buildFinalText = function(text) { var charactersArray = []; var i = 0; var len = text.length; var charCode; var secondCharCode; var shouldCombine = false; while (i < len) { charCode = text.charCodeAt(i); if (FontManager.isCombinedCharacter(charCode)) charactersArray[charactersArray.length - 1] += text.charAt(i); else if (charCode >= 55296 && charCode <= 56319) { secondCharCode = text.charCodeAt(i + 1); if (secondCharCode >= 56320 && secondCharCode <= 57343) { if (shouldCombine || FontManager.isModifier(charCode, secondCharCode)) { charactersArray[charactersArray.length - 1] += text.substr(i, 2); shouldCombine = false; } else charactersArray.push(text.substr(i, 2)); i += 1; } else charactersArray.push(text.charAt(i)); } else if (charCode > 56319) { secondCharCode = text.charCodeAt(i + 1); if (FontManager.isZeroWidthJoiner(charCode, secondCharCode)) { shouldCombine = true; charactersArray[charactersArray.length - 1] += text.substr(i, 2); i += 1; } else charactersArray.push(text.charAt(i)); } else if (FontManager.isZeroWidthJoiner(charCode)) { charactersArray[charactersArray.length - 1] += text.charAt(i); shouldCombine = true; } else charactersArray.push(text.charAt(i)); i += 1; } return charactersArray; }; TextProperty.prototype.completeTextData = function(documentData) { documentData.__complete = true; var fontManager = this.elem.globalData.fontManager; var data = this.data; var letters = []; var i; var len; var newLineFlag; var index2 = 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 (i = 0; i < len; i += 1) { charCode = finalText[i].charCodeAt(0); newLineFlag = false; if (finalText[i] === " ") lastSpaceIndex = i; else if (charCode === 13 || charCode === 3) { lineWidth = 0; newLineFlag = true; currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; } if (fontManager.chars) { charData = fontManager.getCharData(finalText[i], fontData.fStyle, fontData.fFamily); cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100; } else cLength = fontManager.measureText(finalText[i], documentData.f, documentData.finalSize); if (lineWidth + cLength > boxWidth && finalText[i] !== " ") { if (lastSpaceIndex === -1) len += 1; else i = lastSpaceIndex; currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; finalText.splice(i, lastSpaceIndex === i ? 1 : 0, "\r"); lastSpaceIndex = -1; lineWidth = 0; } else { lineWidth += cLength; lineWidth += trackingOffset; } } currentHeight += fontData.ascent * documentData.finalSize / 100; if (this.canResize && documentData.finalSize > this.minimumFontSize && boxHeight < currentHeight) { documentData.finalSize -= 1; documentData.finalLineHeight = documentData.finalSize * documentData.lh / documentData.s; } else { documentData.finalText = finalText; len = documentData.finalText.length; flag = false; } } } lineWidth = -trackingOffset; cLength = 0; var uncollapsedSpaces = 0; var currentChar; for (i = 0; i < len; i += 1) { newLineFlag = false; currentChar = documentData.finalText[i]; charCode = currentChar.charCodeAt(0); if (charCode === 13 || charCode === 3) { uncollapsedSpaces = 0; lineWidths.push(lineWidth); maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; lineWidth = -2 * trackingOffset; 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 === " " || i === len - 1) { if (val === "" || val === " ") currentSize -= cLength; while (currentPos <= i) { letters[currentPos].an = currentSize; letters[currentPos].ind = index2; letters[currentPos].extra = cLength; currentPos += 1; } index2 += 1; currentSize = 0; } } else if (anchorGrouping == 3) { currentSize += cLength; if (val === "" || i === len - 1) { if (val === "") currentSize -= cLength; while (currentPos <= i) { letters[currentPos].an = currentSize; letters[currentPos].ind = index2; letters[currentPos].extra = cLength; currentPos += 1; } currentSize = 0; index2 += 1; } } else { letters[index2].ind = index2; letters[index2].extra = 0; index2 += 1; } } documentData.l = letters; maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; lineWidths.push(lineWidth); if (documentData.sz) { documentData.boxWidth = documentData.sz[0]; documentData.justifyOffset = 0; } else { documentData.boxWidth = maxLineWidth; switch (documentData.j) { case 1: documentData.justifyOffset = -documentData.boxWidth; break; case 2: documentData.justifyOffset = -documentData.boxWidth / 2; break; default: documentData.justifyOffset = 0; } } documentData.lineWidths = lineWidths; var animators = 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 (i = 0; i < len; i += 1) { letterData = letters[i]; letterData.anIndexes[j] = ind; if (based == 1 && letterData.val !== "" || based == 2 && letterData.val !== "" && letterData.val !== " " || based == 3 && (letterData.n || letterData.val == " " || i == len - 1) || based == 4 && (letterData.n || i == len - 1)) { if (animatorData.s.rn === 1) indexes.push(ind); ind += 1; } } data.a[j].s.totalChars = ind; var currentInd = -1; var newInd; if (animatorData.s.rn === 1) for (i = 0; i < len; i += 1) { letterData = letters[i]; if (currentInd != letterData.anIndexes[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, index2) { index2 = index2 === void 0 ? this.keysIndex : index2; var dData = this.copyData({}, this.data.d.k[index2].s); dData = this.copyData(dData, newData); this.data.d.k[index2].s = dData; this.recalculate(index2); this.elem.addDynamicProperty(this); }; TextProperty.prototype.recalculate = function(index2) { var dData = this.data.d.k[index2].s; dData.__complete = false; this.keysIndex = 0; this._isFirstFrame = true; this.getValue(dData); }; TextProperty.prototype.canResizeFont = function(_canResize) { this.canResize = _canResize; this.recalculate(this.keysIndex); this.elem.addDynamicProperty(this); }; TextProperty.prototype.setMinimumFontSize = function(_fontValue) { this.minimumFontSize = Math.floor(_fontValue) || 1; this.recalculate(this.keysIndex); this.elem.addDynamicProperty(this); }; const TextSelectorProp = function() { var max = 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, .01, this); if (!this.dynamicProperties.length) this.getValue(); } TextSelectorPropFactory.prototype = { getMult: function(ind) { if (this._currentTextLength !== this.elem.textProperty.currentData.l.length) this.getValue(); var x1 = 0; var y1 = 0; var x2 = 1; var y2 = 1; if (this.ne.v > 0) x1 = this.ne.v / 100; else y1 = -this.ne.v / 100; if (this.xe.v > 0) x2 = 1 - this.xe.v / 100; else y2 = 1 + this.xe.v / 100; var easer = BezierFactory.getBezierEasing(x1, y1, x2, y2).get; var mult = 0; var s = this.finalS; var e = this.finalE; var type = this.data.sh; if (type === 2) { if (e === s) mult = ind >= e ? 1 : 0; else mult = max(0, min(.5 / (e - s) + (ind - s) / (e - s), 1)); mult = easer(mult); } else if (type === 3) { if (e === s) mult = ind >= e ? 0 : 1; else mult = 1 - max(0, min(.5 / (e - s) + (ind - s) / (e - s), 1)); mult = easer(mult); } else if (type === 4) { if (e === s) mult = 0; else { mult = max(0, min(.5 / (e - s) + (ind - s) / (e - s), 1)); if (mult < .5) mult *= 2; else mult = 1 - 2 * (mult - .5); } mult = easer(mult); } else if (type === 5) { if (e === s) mult = 0; else { var tot = e - s; ind = min(max(0, ind + .5 - s), e - s); var x = -tot / 2 + ind; var a = tot / 2; mult = Math.sqrt(1 - x * x / (a * a)); } mult = easer(mult); } else if (type === 6) { if (e === s) mult = 0; else { ind = min(max(0, ind + .5 - s), e - s); mult = (1 + Math.cos(Math.PI + Math.PI * 2 * ind / (e - s))) / 2; } mult = easer(mult); } else { if (ind >= floor(s)) if (ind - s < 0) mult = max(0, min(min(e, 1) - (s - ind), 1)); else mult = max(0, min(e - ind, 1)); mult = easer(mult); } if (this.sm.v !== 100) { var smoothness = this.sm.v * .01; if (smoothness === 0) smoothness = 1e-8; var threshold = .5 - smoothness * .5; if (mult < threshold) mult = 0; else { mult = (mult - threshold) / smoothness; if (mult > 1) mult = 1; } } return mult * this.a.v; }, getValue: function(newCharsFlag) { this.iterateDynamicProperties(); this._mdf = newCharsFlag || this._mdf; this._currentTextLength = this.elem.textProperty.currentData.l.length || 0; if (newCharsFlag && this.data.r === 2) this.e.v = this._currentTextLength; var divisor = this.data.r === 2 ? 1 : 100 / this.data.totalChars; var o = this.o.v / divisor; var s = this.s.v / divisor + o; var e = this.e.v / divisor + o; if (s > e) { var _s = s; s = e; e = _s; } this.finalS = s; this.finalE = e; } }; extendPrototype([DynamicPropertyContainer], TextSelectorPropFactory); function getTextSelectorProp(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, .01, container) : defaultData, a: textAnimatorAnimatables.a ? getProp(elem, textAnimatorAnimatables.a, 1, 0, container) : defaultData, o: textAnimatorAnimatables.o ? getProp(elem, textAnimatorAnimatables.o, 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, .01, container) : defaultData, fb: textAnimatorAnimatables.fb ? getProp(elem, textAnimatorAnimatables.fb, 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 i; var len = this._textData.a.length; var animatorProps; var getProp = PropertyFactory.getProp; for (i = 0; i < len; i += 1) { animatorProps = this._textData.a[i]; this._animatorsData[i] = new TextAnimatorDataProperty(this._elem, animatorProps, this); } if (this._textData.p && "m" in this._textData.p) { this._pathData = { a: getProp(this._elem, this._textData.p.a, 0, 0, this), f: getProp(this._elem, this._textData.p.f, 0, 0, this), l: getProp(this._elem, this._textData.p.l, 0, 0, this), r: getProp(this._elem, this._textData.p.r, 0, 0, this), p: getProp(this._elem, this._textData.p.p, 0, 0, this), m: this._elem.maskManager.getMaskProperty(this._textData.p.m) }; this._hasMaskedPath = true; } else this._hasMaskedPath = false; this._moreOptions.alignment = getProp(this._elem, this._textData.m.a, 1, 0, this); }; TextAnimatorProperty.prototype.getMeasures = function(documentData, lettersChangedFlag) { this.lettersChangedFlag = lettersChangedFlag; if (!this._mdf && !this._isFirstFrame && !lettersChangedFlag && (!this._hasMaskedPath || !this._pathData.m._mdf)) return; this._isFirstFrame = false; var alignment = this._moreOptions.alignment.v; var animators = this._animatorsData; var textData = this._textData; var matrixHelper = this.mHelper; var renderType = this._renderType; var renderedLettersCount = this.renderedLetters.length; var xPos; var yPos; var i; var len; var letters = documentData.l; var pathInfo; var currentLength; var currentPoint; var segmentLength; var flag; var pointInd; var segmentInd; var prevPoint; var points; var segments; var partialLength; var totalLength; var perc; var tanAngle; var 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 (i = 0; i < len; i += 1) { bezierData = bez.buildBezierData(paths.v[i], paths.v[i + 1], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[i + 1][0] - paths.v[i + 1][0], paths.i[i + 1][1] - paths.v[i + 1][1]]); pathInfo.tLength += bezierData.segmentLength; pathInfo.segments.push(bezierData); totalLength += bezierData.segmentLength; } i = len; if (mask.v.c) { bezierData = bez.buildBezierData(paths.v[i], paths.v[0], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[0][0] - paths.v[0][0], paths.i[0][1] - paths.v[0][1]]); pathInfo.tLength += bezierData.segmentLength; pathInfo.segments.push(bezierData); totalLength += bezierData.segmentLength; } this._pathData.pi = pathInfo; } pathInfo = this._pathData.pi; currentLength = this._pathData.f.v; segmentInd = 0; pointInd = 1; segmentLength = 0; flag = true; segments = pathInfo.segments; if (currentLength < 0 && 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 * .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 ? -.5 : -1; var lastIndex = 0; var isNewLine = true; for (i = 0; i < len; i += 1) if (letters[i].n) { if (animatorJustifyOffset) animatorJustifyOffset += animatorFirstCharOffset; while (lastIndex < i) { letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; lastIndex += 1; } animatorJustifyOffset = 0; isNewLine = true; } else { for (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[i].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 < i) { letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; lastIndex += 1; } } for (i = 0; i < len; i += 1) { matrixHelper.reset(); elemOpacity = 1; if (letters[i].n) { xPos = 0; yPos += documentData.yOffset; yPos += firstLine ? 1 : 0; currentLength = initPathPos; firstLine = false; if (this._hasMaskedPath) { segmentInd = initSegmentInd; pointInd = initPointInd; points = segments[segmentInd].points; prevPoint = points[pointInd - 1]; currentPoint = points[pointInd]; partialLength = currentPoint.partialLength; segmentLength = 0; } letterM = ""; letterFc = ""; letterSw = ""; letterO = ""; letterP = this.defaultPropsArray; } else { if (this._hasMaskedPath) { if (currentLine !== letters[i].line) { switch (documentData.j) { case 1: currentLength += totalLength - documentData.lineWidths[letters[i].line]; break; case 2: currentLength += (totalLength - documentData.lineWidths[letters[i].line]) / 2; break; } currentLine = letters[i].line; } if (ind !== letters[i].ind) { if (letters[ind]) currentLength += letters[ind].extra; currentLength += letters[i].an / 2; ind = letters[i].ind; } currentLength += alignment[0] * letters[i].an * .005; 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[i].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[i].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 * .5 + (totalLength - this._pathData.f.v - letters[0].an * .5 - letters[letters.length - 1].an * .5) * ind / (len - 1); currentLength += this._pathData.f.v; } while (flag) if (segmentLength + partialLength >= currentLength + animatorOffset || !points) { perc = (currentLength + animatorOffset - segmentLength) / currentPoint.partialLength; xPathPos = prevPoint.point[0] + (currentPoint.point[0] - prevPoint.point[0]) * perc; yPathPos = prevPoint.point[1] + (currentPoint.point[1] - prevPoint.point[1]) * perc; matrixHelper.translate(-alignment[0] * letters[i].an * .005, -(alignment[1] * yOff) * .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[i].an / 2 - letters[i].add; matrixHelper.translate(-offf, 0, 0); } else { offf = letters[i].an / 2 - letters[i].add; matrixHelper.translate(-offf, 0, 0); matrixHelper.translate(-alignment[0] * letters[i].an * .005, -alignment[1] * yOff * .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[i].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[i].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[i].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[i].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[i].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 * .01 + yPos, 0); if (this._pathData.p.v) { tanAngle = (currentPoint.point[1] - prevPoint.point[1]) / (currentPoint.point[0] - prevPoint.point[0]); var rot = Math.atan(tanAngle) * 180 / Math.PI; if (currentPoint.point[0] < prevPoint.point[0]) rot += 180; matrixHelper.rotate(-rot * Math.PI / 180); } matrixHelper.translate(xPathPos, yPathPos, 0); currentLength -= alignment[0] * letters[i].an * .005; if (letters[i + 1] && ind !== letters[i + 1].ind) { currentLength += letters[i].an / 2; currentLength += documentData.tr * .001 * documentData.finalSize; } } else { matrixHelper.translate(xPos, yPos, 0); if (documentData.ps) matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0); switch (documentData.j) { case 1: matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]), 0, 0); break; case 2: matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]) / 2, 0, 0); break; } matrixHelper.translate(0, -documentData.ls); matrixHelper.translate(offf, 0, 0); matrixHelper.translate(alignment[0] * letters[i].an * .005, alignment[1] * yOff * .01, 0); xPos += letters[i].l + documentData.tr * .001 * documentData.finalSize; } if (renderType === "html") letterM = matrixHelper.toCSS(); else if (renderType === "svg") letterM = matrixHelper.to2dCSS(); else letterP = [ matrixHelper.props[0], matrixHelper.props[1], matrixHelper.props[2], matrixHelper.props[3], matrixHelper.props[4], matrixHelper.props[5], matrixHelper.props[6], matrixHelper.props[7], matrixHelper.props[8], matrixHelper.props[9], matrixHelper.props[10], matrixHelper.props[11], matrixHelper.props[12], matrixHelper.props[13], matrixHelper.props[14], matrixHelper.props[15] ]; letterO = elemOpacity; } if (renderedLettersCount <= i) { letterValue = new LetterProps(letterO, letterSw, letterSc, letterFc, letterM, letterP); this.renderedLetters.push(letterValue); renderedLettersCount += 1; this.lettersChangedFlag = true; } else { letterValue = this.renderedLetters[i]; this.lettersChangedFlag = letterValue.update(letterO, letterSw, letterSc, letterFc, letterM, letterP) || this.lettersChangedFlag; } } }; TextAnimatorProperty.prototype.getValue = function() { if (this._elem.globalData.frameId === this._frameId) return; this._frameId = this._elem.globalData.frameId; this.iterateDynamicProperties(); }; TextAnimatorProperty.prototype.mHelper = new Matrix(); TextAnimatorProperty.prototype.defaultPropsArray = []; extendPrototype([DynamicPropertyContainer], TextAnimatorProperty); 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, index2) { this.textProperty.updateDocumentData(newData, index2); }; ITextElement.prototype.canResizeFont = function(_canResize) { this.textProperty.canResizeFont(_canResize); }; ITextElement.prototype.setMinimumFontSize = function(_fontSize) { this.textProperty.setMinimumFontSize(_fontSize); }; ITextElement.prototype.applyTextPropertiesToMatrix = function(documentData, matrixHelper, lineNumber, xPos, yPos) { if (documentData.ps) matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0); matrixHelper.translate(0, -documentData.ls, 0); switch (documentData.j) { case 1: matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]), 0, 0); break; case 2: matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]) / 2, 0, 0); break; } 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 i = 0; var len = textArray.length; var textContents = []; var currentTextContent = ""; while (i < len) { if (textArray[i] === String.fromCharCode(13) || textArray[i] === String.fromCharCode(3)) { textContents.push(currentTextContent); currentTextContent = ""; } else currentTextContent += textArray[i]; i += 1; } textContents.push(currentTextContent); return textContents; }; SVGTextLottieElement.prototype.buildShapeData = function(data, scale) { 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] = scale; shapeItem.s.k[1] = scale; } } } return data; }; SVGTextLottieElement.prototype.buildNewText = function() { this.addDynamicProperty(this); var i; var len; var documentData = this.textProperty.currentData; this.renderedLetters = createSizedArray(documentData ? documentData.l.length : 0); if (documentData.fc) this.layerElement.setAttribute("fill", this.buildColor(documentData.fc)); else this.layerElement.setAttribute("fill", "rgba(0,0,0,0)"); if (documentData.sc) { this.layerElement.setAttribute("stroke", this.buildColor(documentData.sc)); this.layerElement.setAttribute("stroke-width", documentData.sw); } this.layerElement.setAttribute("font-size", documentData.finalSize); var fontData = this.globalData.fontManager.getFontByName(documentData.f); if (fontData.fClass) this.layerElement.setAttribute("class", fontData.fClass); else { this.layerElement.setAttribute("font-family", fontData.fFamily); var fWeight = documentData.fWeight; var fStyle = documentData.fStyle; this.layerElement.setAttribute("font-style", fStyle); this.layerElement.setAttribute("font-weight", fWeight); } this.layerElement.setAttribute("aria-label", documentData.t); var letters = documentData.l || []; var usesGlyphs = !!this.globalData.fontManager.chars; len = letters.length; var tSpan; var matrixHelper = this.mHelper; var shapeStr = ""; var singleShape = this.data.singleShape; var xPos = 0; var yPos = 0; var firstLine = true; var trackingOffset = documentData.tr * .001 * documentData.finalSize; if (singleShape && !usesGlyphs && !documentData.sz) { var tElement = this.textContainer; var justify = "start"; switch (documentData.j) { case 1: justify = "end"; break; case 2: justify = "middle"; break; default: justify = "start"; break; } tElement.setAttribute("text-anchor", justify); tElement.setAttribute("letter-spacing", trackingOffset); var textContent = this.buildTextContents(documentData.finalText); len = textContent.length; yPos = documentData.ps ? documentData.ps[1] + documentData.ascent : 0; for (i = 0; i < len; i += 1) { tSpan = this.textSpans[i].span || createNS("tspan"); tSpan.textContent = textContent[i]; tSpan.setAttribute("x", 0); tSpan.setAttribute("y", yPos); tSpan.style.display = "inherit"; tElement.appendChild(tSpan); if (!this.textSpans[i]) this.textSpans[i] = { span: null, glyph: null }; this.textSpans[i].span = tSpan; yPos += documentData.finalLineHeight; } this.layerElement.appendChild(tElement); } else { var cachedSpansLength = this.textSpans.length; var charData; for (i = 0; i < len; i += 1) { if (!this.textSpans[i]) this.textSpans[i] = { span: null, childSpan: null, glyph: null }; if (!usesGlyphs || !singleShape || i === 0) { tSpan = cachedSpansLength > i ? this.textSpans[i].span : createNS(usesGlyphs ? "g" : "text"); if (cachedSpansLength <= i) { tSpan.setAttribute("stroke-linecap", "butt"); tSpan.setAttribute("stroke-linejoin", "round"); tSpan.setAttribute("stroke-miterlimit", "4"); this.textSpans[i].span = tSpan; if (usesGlyphs) { var childSpan = createNS("g"); tSpan.appendChild(childSpan); this.textSpans[i].childSpan = childSpan; } this.textSpans[i].span = tSpan; this.layerElement.appendChild(tSpan); } tSpan.style.display = "inherit"; } matrixHelper.reset(); if (singleShape) { if (letters[i].n) { xPos = -trackingOffset; yPos += documentData.yOffset; yPos += firstLine ? 1 : 0; firstLine = false; } this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos); xPos += letters[i].l || 0; xPos += trackingOffset; } if (usesGlyphs) { charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily); var glyphElement; if (charData.t === 1) glyphElement = new SVGCompElement(charData.data, this.globalData, this); else { var 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[i].glyph) { var glyph = this.textSpans[i].glyph; this.textSpans[i].childSpan.removeChild(glyph.layerElement); glyph.destroy(); } this.textSpans[i].glyph = glyphElement; glyphElement._debug = true; glyphElement.prepareFrame(0); glyphElement.renderFrame(); this.textSpans[i].childSpan.appendChild(glyphElement.layerElement); if (charData.t === 1) this.textSpans[i].childSpan.setAttribute("transform", "scale(" + documentData.finalSize / 100 + "," + documentData.finalSize / 100 + ")"); } else { if (singleShape) tSpan.setAttribute("transform", "translate(" + matrixHelper.props[12] + "," + matrixHelper.props[13] + ")"); tSpan.textContent = letters[i].val; tSpan.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve"); } } if (singleShape && tSpan) tSpan.setAttribute("d", shapeStr); } while (i < this.textSpans.length) { this.textSpans[i].span.style.display = "none"; i += 1; } this._sizeChanged = true; }; SVGTextLottieElement.prototype.sourceRectAtTime = function() { this.prepareFrame(this.comp.renderedFrame - this.data.st); this.renderInnerContent(); if (this._sizeChanged) { this._sizeChanged = false; var textBox = this.layerElement.getBBox(); this.bbox = { top: textBox.y, left: textBox.x, width: textBox.width, height: textBox.height }; } return this.bbox; }; SVGTextLottieElement.prototype.getValue = function() { var i; var len = this.textSpans.length; var glyphElement; this.renderedFrame = this.comp.renderedFrame; for (i = 0; i < len; i += 1) { glyphElement = this.textSpans[i].glyph; if (glyphElement) { glyphElement.prepareFrame(this.comp.renderedFrame - this.data.st); if (glyphElement._mdf) this._mdf = true; } } }; SVGTextLottieElement.prototype.renderInnerContent = function() { if (!this.data.singleShape || this._mdf) { this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); if (this.lettersChangedFlag || this.textAnimator.lettersChangedFlag) { this._sizeChanged = true; var i; var len; var renderedLetters = this.textAnimator.renderedLetters; var letters = this.textProperty.currentData.l; len = letters.length; var renderedLetter; var textSpan; var glyphElement; for (i = 0; i < len; i += 1) if (!letters[i].n) { renderedLetter = renderedLetters[i]; textSpan = this.textSpans[i].span; glyphElement = this.textSpans[i].glyph; if (glyphElement) glyphElement.renderFrame(); if (renderedLetter._mdf.m) textSpan.setAttribute("transform", renderedLetter.m); if (renderedLetter._mdf.o) textSpan.setAttribute("opacity", renderedLetter.o); if (renderedLetter._mdf.sw) textSpan.setAttribute("stroke-width", renderedLetter.sw); if (renderedLetter._mdf.sc) textSpan.setAttribute("stroke", renderedLetter.sc); if (renderedLetter._mdf.fc) textSpan.setAttribute("fill", renderedLetter.fc); } } } }; 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 i; var len = this.layers ? this.layers.length : 0; for (i = 0; i < len; i += 1) if (this.elements[i]) this.elements[i].destroy(); this.elements.length = 0; this.destroyed = true; this.animationItem = null; }; SVGRendererBase.prototype.updateContainerSize = function() {}; SVGRendererBase.prototype.buildItem = function(pos) { var elements = this.elements; if (elements[pos] || this.layers[pos].ty === 99) return; elements[pos] = true; var element = this.createItem(this.layers[pos]); elements[pos] = element; if (getExpressionsPlugin()) { if (this.layers[pos].ty === 0) this.globalData.projectInterface.registerComposition(element); element.initExpressions(); } this.appendElementInPos(element, pos); if (this.layers[pos].tt) if (!this.elements[pos - 1] || this.elements[pos - 1] === true) { this.buildItem(pos - 1); this.addPendingElement(element); } else element.setMatte(elements[pos - 1].layerId); }; SVGRendererBase.prototype.checkPendingElements = function() { while (this.pendingElements.length) { var element = this.pendingElements.pop(); element.checkParenting(); if (element.data.tt) { var i = 0; var len = this.elements.length; while (i < len) { if (this.elements[i] === element) { element.setMatte(this.elements[i - 1].layerId); break; } i += 1; } } } }; SVGRendererBase.prototype.renderFrame = function(num) { if (this.renderedFrame === num || this.destroyed) return; if (num === null) num = this.renderedFrame; else this.renderedFrame = num; this.globalData.frameNum = num; this.globalData.frameId += 1; this.globalData.projectInterface.currentFrame = num; this.globalData._mdf = false; var i; var len = this.layers.length; if (!this.completeLayers) this.checkLayers(num); for (i = len - 1; i >= 0; i -= 1) if (this.completeLayers || this.elements[i]) this.elements[i].prepareFrame(num - this.layers[i].st); if (this.globalData._mdf) { for (i = 0; i < len; i += 1) if (this.completeLayers || this.elements[i]) this.elements[i].renderFrame(); } }; SVGRendererBase.prototype.appendElementInPos = function(element, pos) { var newElement = element.getBaseElement(); if (!newElement) return; var i = 0; var nextElement; while (i < pos) { if (this.elements[i] && this.elements[i] !== true && this.elements[i].getBaseElement()) nextElement = this.elements[i].getBaseElement(); i += 1; } if (nextElement) this.layerElement.insertBefore(newElement, nextElement); else this.layerElement.appendChild(newElement); }; SVGRendererBase.prototype.hide = function() { this.layerElement.style.display = "none"; }; SVGRendererBase.prototype.show = function() { this.layerElement.style.display = "block"; }; 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 i; var len = this.elements.length; if (!this.completeLayers) this.checkLayers(this.renderedFrame); for (i = len - 1; i >= 0; i -= 1) if (this.completeLayers || this.elements[i]) { this.elements[i].prepareFrame(this.renderedFrame - this.layers[i].st); if (this.elements[i]._mdf) this._mdf = true; } }; ICompElement.prototype.renderInnerContent = function() { var i; var len = this.layers.length; for (i = 0; i < len; i += 1) if (this.completeLayers || this.elements[i]) this.elements[i].renderFrame(); }; ICompElement.prototype.setElements = function(elems) { this.elements = elems; }; ICompElement.prototype.getElements = function() { return this.elements; }; ICompElement.prototype.destroyElements = function() { var i; var len = this.layers.length; for (i = 0; i < len; i += 1) if (this.elements[i]) this.elements[i].destroy(); }; ICompElement.prototype.destroy = function() { this.destroyElements(); this.destroyBaseElement(); }; 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 SVGRenderer(animationItem, config) { this.animationItem = animationItem; this.layers = null; this.renderedFrame = -1; this.svgElement = createNS("svg"); var ariaLabel = ""; if (config && config.title) { var titleElement = createNS("title"); var titleId = createElementID(); titleElement.setAttribute("id", titleId); titleElement.textContent = config.title; this.svgElement.appendChild(titleElement); ariaLabel += titleId; } if (config && config.description) { var descElement = createNS("desc"); var descId = createElementID(); descElement.setAttribute("id", descId); descElement.textContent = config.description; this.svgElement.appendChild(descElement); ariaLabel += " " + descId; } if (ariaLabel) this.svgElement.setAttribute("aria-labelledby", ariaLabel); var defs = createNS("defs"); this.svgElement.appendChild(defs); var maskElement = createNS("g"); this.svgElement.appendChild(maskElement); this.layerElement = maskElement; this.renderConfig = { preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", contentVisibility: config && config.contentVisibility || "visible", progressiveLoad: config && config.progressiveLoad || false, hideOnTransparent: !(config && config.hideOnTransparent === false), viewBoxOnly: config && config.viewBoxOnly || false, viewBoxSize: config && config.viewBoxSize || false, className: config && config.className || "", id: config && config.id || "", focusable: config && config.focusable, filterSize: { width: config && config.filterSize && config.filterSize.width || "100%", height: config && config.filterSize && config.filterSize.height || "100%", x: config && config.filterSize && config.filterSize.x || "0%", y: config && config.filterSize && config.filterSize.y || "0%" }, width: config && config.width, height: config && config.height }; this.globalData = { _mdf: false, frameNum: -1, defs, renderConfig: this.renderConfig }; this.elements = []; this.pendingElements = []; this.destroyed = false; this.rendererType = "svg"; } extendPrototype([SVGRendererBase], SVGRenderer); SVGRenderer.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 i; var len = 15; this.savedOp = createTypedArray("float32", len); for (i = 0; i < len; i += 1) this.saved[i] = createTypedArray("float32", 16); this._length = len; } CVContextData.prototype.duplicate = function() { var newLength = this._length * 2; var currentSavedOp = this.savedOp; this.savedOp = createTypedArray("float32", newLength); this.savedOp.set(currentSavedOp); var i = 0; for (i = this._length; i < newLength; i += 1) this.saved[i] = createTypedArray("float32", 16); this._length = newLength; }; CVContextData.prototype.reset = function() { this.cArrPos = 0; this.cTr.reset(); this.cO = 1; }; function ShapeTransformManager() { this.sequences = {}; this.sequenceList = []; this.transform_key_count = 0; } ShapeTransformManager.prototype = { addTransformSequence: function(transforms) { var i; var len = transforms.length; var key = "_"; for (i = 0; i < len; i += 1) key += transforms[i].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 i = 0; var len = sequence.transforms.length; var _mdf = isFirstFrame; while (i < len && !isFirstFrame) { if (sequence.transforms[i].transform.mProps._mdf) { _mdf = true; break; } i += 1; } if (_mdf) { var props; sequence.finalTransform.reset(); for (i = len - 1; i >= 0; i -= 1) { props = sequence.transforms[i].transform.mProps.v.props; sequence.finalTransform.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]); } } sequence._mdf = _mdf; }, processSequences: function(isFirstFrame) { var i; var len = this.sequenceList.length; for (i = 0; i < len; i += 1) this.processSequence(this.sequenceList[i], isFirstFrame); }, getNewKey: function() { this.transform_key_count += 1; return "_" + this.transform_key_count; } }; 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 i; var len = this.masksProperties.length; var hasMasks = false; for (i = 0; i < len; i += 1) { if (this.masksProperties[i].mode !== "n") hasMasks = true; this.viewData[i] = ShapePropertyFactory.getShapeProp(this.element, this.masksProperties[i], 3); } this.hasMasks = hasMasks; if (hasMasks) this.element.addRenderableComponent(this); } CVMaskElement.prototype.renderFrame = function() { if (!this.hasMasks) return; var transform = this.element.finalTransform.mat; var ctx = this.element.canvasContext; var i; var len = this.masksProperties.length; var pt; var pts; var data; ctx.beginPath(); for (i = 0; i < len; i += 1) if (this.masksProperties[i].mode !== "n") { if (this.masksProperties[i].inv) { ctx.moveTo(0, 0); ctx.lineTo(this.element.globalData.compSize.w, 0); ctx.lineTo(this.element.globalData.compSize.w, this.element.globalData.compSize.h); ctx.lineTo(0, this.element.globalData.compSize.h); ctx.lineTo(0, 0); } data = this.viewData[i].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, styles, 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 i; var len = styles.length; var styledShape; for (i = 0; i < len; i += 1) if (!styles[i].closed) { styledShape = { transforms: transformsManager.addTransformSequence(styles[i].transforms), trNodes: [] }; this.styledShapes.push(styledShape); styles[i].elements.push(styledShape); } } 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, .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, .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) { elementData.d = new DashProperty(this, data.d, "canvas", this); 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() { return { it: [], prevViewData: [] }; }; CVShapeElement.prototype.createTransformElement = function(data) { return { transform: { opacity: 1, _opMdf: false, key: this.transformsManager.getNewKey(), op: PropertyFactory.getProp(this, data.o, 0, .01, this), mProps: TransformPropertyFactory.getTransformProperty(this, data, this) } }; }; 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 i; var len = this.itemsData.length; for (i = 0; i < len; i += 1) this.prevViewData[i] = this.itemsData[i]; this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []); len = this.dynamicProperties.length; for (i = 0; i < len; i += 1) this.dynamicProperties[i].getValue(); this.renderModifiers(); this.transformsManager.processSequences(this._isFirstFrame); }; CVShapeElement.prototype.addTransformToStyleList = function(transform) { var i; var len = this.stylesList.length; for (i = 0; i < len; i += 1) if (!this.stylesList[i].closed) this.stylesList[i].transforms.push(transform); }; CVShapeElement.prototype.removeTransformFromStyleList = function() { var i; var len = this.stylesList.length; for (i = 0; i < len; i += 1) if (!this.stylesList[i].closed) this.stylesList[i].transforms.pop(); }; CVShapeElement.prototype.closeStyles = function(styles) { var i; var len = styles.length; for (i = 0; i < len; i += 1) styles[i].closed = true; }; CVShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, shouldRender, transforms) { var i; var len = arr.length - 1; var j; var jLen; var ownStyles = []; var ownModifiers = []; var processedPos; var modifier; var currentTransform; var ownTransforms = [].concat(transforms); for (i = len; i >= 0; i -= 1) { processedPos = this.searchProcessedElement(arr[i]); if (!processedPos) arr[i]._shouldRender = shouldRender; else itemsData[i] = prevViewData[processedPos - 1]; if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs") { if (!processedPos) itemsData[i] = this.createStyleElement(arr[i], ownTransforms); else itemsData[i].style.closed = false; ownStyles.push(itemsData[i].style); } else if (arr[i].ty === "gr") { if (!processedPos) itemsData[i] = this.createGroupElement(arr[i]); else { jLen = itemsData[i].it.length; for (j = 0; j < jLen; j += 1) itemsData[i].prevViewData[j] = itemsData[i].it[j]; } this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, shouldRender, ownTransforms); } else if (arr[i].ty === "tr") { if (!processedPos) { currentTransform = this.createTransformElement(arr[i]); itemsData[i] = currentTransform; } ownTransforms.push(itemsData[i]); this.addTransformToStyleList(itemsData[i]); } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") { if (!processedPos) itemsData[i] = this.createShapeElement(arr[i]); } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "pb") { if (!processedPos) { modifier = ShapeModifiers.getModifier(arr[i].ty); modifier.init(this, arr[i]); itemsData[i] = modifier; this.shapeModifiers.push(modifier); } else { modifier = itemsData[i]; modifier.closed = false; } ownModifiers.push(modifier); } else if (arr[i].ty === "rp") { if (!processedPos) { modifier = ShapeModifiers.getModifier(arr[i].ty); itemsData[i] = modifier; modifier.init(this, arr, i, itemsData); this.shapeModifiers.push(modifier); shouldRender = false; } else { modifier = itemsData[i]; modifier.closed = true; } ownModifiers.push(modifier); } this.addProcessedElement(arr[i], i + 1); } this.removeTransformFromStyleList(); this.closeStyles(ownStyles); len = ownModifiers.length; for (i = 0; i < len; i += 1) ownModifiers[i].closed = true; }; CVShapeElement.prototype.renderInnerContent = function() { this.transformHelper.opacity = 1; this.transformHelper._opMdf = false; this.renderModifiers(); this.transformsManager.processSequences(this._isFirstFrame); this.renderShape(this.transformHelper, this.shapesData, this.itemsData, true); }; CVShapeElement.prototype.renderShapeTransform = function(parentTransform, groupTransform) { if (parentTransform._opMdf || groupTransform.op._mdf || this._isFirstFrame) { groupTransform.opacity = parentTransform.opacity; groupTransform.opacity *= groupTransform.op.v; groupTransform._opMdf = true; } }; CVShapeElement.prototype.drawLayer = function() { var i; var len = this.stylesList.length; var 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 (i = 0; i < len; i += 1) { currentStyle = this.stylesList[i]; type = currentStyle.type; if (!((type === "st" || type === "gs") && currentStyle.wi === 0 || !currentStyle.data._shouldRender || currentStyle.coOp === 0 || this.globalData.currentGlobalAlpha === 0)) { 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 i; var len = items.length - 1; var groupTransform = parentTransform; for (i = len; i >= 0; i -= 1) if (items[i].ty === "tr") { groupTransform = data[i].transform; this.renderShapeTransform(parentTransform, groupTransform); } else if (items[i].ty === "sh" || items[i].ty === "el" || items[i].ty === "rc" || items[i].ty === "sr") this.renderPath(items[i], data[i]); else if (items[i].ty === "fl") this.renderFill(items[i], data[i], groupTransform); else if (items[i].ty === "st") this.renderStroke(items[i], data[i], groupTransform); else if (items[i].ty === "gf" || items[i].ty === "gs") this.renderGradientFill(items[i], data[i], groupTransform); else if (items[i].ty === "gr") this.renderShape(groupTransform, items[i].it, data[i].it); else if (items[i].ty === "tm"); if (isMain) this.drawLayer(); }; CVShapeElement.prototype.renderStyledShape = function(styledShape, shape) { if (this._isFirstFrame || shape._mdf || styledShape.transforms._mdf) { var shapeNodes = styledShape.trNodes; var paths = shape.paths; var i; var len; var 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 (i = 1; i < len; i += 1) { if (i === 1) shapeNodes.push({ t: "m", p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) }); shapeNodes.push({ t: "c", pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[i], pathNodes.v[i]) }); } if (len === 1) shapeNodes.push({ t: "m", p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) }); if (pathNodes.c && len) { shapeNodes.push({ t: "c", pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[0], pathNodes.v[0]) }); shapeNodes.push({ t: "z" }); } } } styledShape.trNodes = shapeNodes; } }; CVShapeElement.prototype.renderPath = function(pathData, itemData) { if (pathData.hd !== true && pathData._shouldRender) { var i; var len = itemData.styledShapes.length; for (i = 0; i < len; i += 1) this.renderStyledShape(itemData.styledShapes[i], itemData.sh); } }; CVShapeElement.prototype.renderFill = function(styleData, itemData, groupTransform) { var styleElem = itemData.style; if (itemData.c._mdf || this._isFirstFrame) styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"; if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) styleElem.coOp = itemData.o.v * groupTransform.opacity; }; CVShapeElement.prototype.renderGradientFill = function(styleData, itemData, groupTransform) { var styleElem = itemData.style; var grd; if (!styleElem.grd || itemData.g._mdf || itemData.s._mdf || itemData.e._mdf || styleData.t !== 1 && (itemData.h._mdf || itemData.a._mdf)) { var ctx = this.globalData.canvasContext; var pt1 = itemData.s.v; var pt2 = itemData.e.v; if (styleData.t === 1) grd = ctx.createLinearGradient(pt1[0], pt1[1], pt2[0], pt2[1]); else { var rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]); var percent = itemData.h.v; if (percent >= 1) percent = .99; else if (percent <= -1) percent = -.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 i; var len = styleData.g.p; var cValues = itemData.g.c; var opacity = 1; for (i = 0; i < len; i += 1) { if (itemData.g._hasOpacity && itemData.g._collapsable) opacity = itemData.g.o[i * 2 + 1]; grd.addColorStop(cValues[i * 4] / 100, "rgba(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + "," + opacity + ")"); } styleElem.grd = grd; } styleElem.coOp = itemData.o.v * groupTransform.opacity; }; CVShapeElement.prototype.renderStroke = function(styleData, itemData, groupTransform) { var styleElem = itemData.style; var d = itemData.d; if (d && (d._mdf || this._isFirstFrame)) { styleElem.da = d.dashArray; styleElem.do = d.dashoffset[0]; } if (itemData.c._mdf || this._isFirstFrame) styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"; if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) styleElem.coOp = itemData.o.v * groupTransform.opacity; if (itemData.w._mdf || this._isFirstFrame) styleElem.wi = itemData.w.v; }; CVShapeElement.prototype.destroy = function() { this.shapesData = null; this.globalData = null; this.canvasContext = null; this.stylesList.length = 0; this.itemsData.length = 0; }; 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 i; var len; var letters = documentData.l; var matrixHelper = this.mHelper; this.stroke = hasStroke; this.values.fValue = documentData.finalSize + "px " + this.globalData.fontManager.getFontByName(documentData.f).fFamily; len = documentData.finalText.length; var charData; var shapeData; var k; var kLen; var shapes; var j; var jLen; var pathNodes; var commands; var pathArr; var singleShape = this.data.singleShape; var trackingOffset = documentData.tr * .001 * documentData.finalSize; var xPos = 0; var yPos = 0; var firstLine = true; var cnt = 0; for (i = 0; i < len; i += 1) { charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily); shapeData = charData && charData.data || {}; matrixHelper.reset(); if (singleShape && letters[i].n) { xPos = -trackingOffset; yPos += documentData.yOffset; yPos += firstLine ? 1 : 0; firstLine = false; } shapes = shapeData.shapes ? shapeData.shapes[0].it : []; jLen = shapes.length; matrixHelper.scale(documentData.finalSize / 100, documentData.finalSize / 100); if (singleShape) this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos); commands = createSizedArray(jLen - 1); var commandsCounter = 0; for (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[i].l; xPos += trackingOffset; } if (this.textSpans[cnt]) this.textSpans[cnt].elem = commands; else this.textSpans[cnt] = { elem: commands }; cnt += 1; } }; CVTextElement.prototype.renderInnerContent = function() { var ctx = this.canvasContext; ctx.font = this.values.fValue; ctx.lineCap = "butt"; ctx.lineJoin = "miter"; ctx.miterLimit = 4; if (!this.data.singleShape) this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); var i; var len; var 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 (i = 0; i < len; i += 1) if (!letters[i].n) { renderedLetter = renderedLetters[i]; if (renderedLetter) { this.globalData.renderer.save(); this.globalData.renderer.ctxTransform(renderedLetter.p); this.globalData.renderer.ctxOpacity(renderedLetter.o); } if (this.fill) { if (renderedLetter && renderedLetter.fc) { if (lastFill !== renderedLetter.fc) { lastFill = renderedLetter.fc; ctx.fillStyle = renderedLetter.fc; } } else if (lastFill !== this.values.fill) { lastFill = this.values.fill; ctx.fillStyle = this.values.fill; } commands = this.textSpans[i].elem; jLen = commands.length; this.globalData.canvasContext.beginPath(); for (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[i].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 = SVGRenderer.prototype.createNull; CanvasRendererBase.prototype.ctxTransform = function(props) { if (props[0] === 1 && props[1] === 0 && props[4] === 0 && props[5] === 1 && props[12] === 0 && props[13] === 0) return; if (!this.renderConfig.clearCanvas) { this.canvasContext.transform(props[0], props[1], props[4], props[5], props[12], props[13]); return; } this.transformMat.cloneFromProps(props); var cProps = this.contextData.cTr.props; this.transformMat.transform(cProps[0], cProps[1], cProps[2], cProps[3], cProps[4], cProps[5], cProps[6], cProps[7], cProps[8], cProps[9], cProps[10], cProps[11], cProps[12], cProps[13], cProps[14], cProps[15]); this.contextData.cTr.cloneFromProps(this.transformMat.props); var trProps = this.contextData.cTr.props; this.canvasContext.setTransform(trProps[0], trProps[1], trProps[4], trProps[5], trProps[12], trProps[13]); }; CanvasRendererBase.prototype.ctxOpacity = function(op) { if (!this.renderConfig.clearCanvas) { this.canvasContext.globalAlpha *= op < 0 ? 0 : op; this.globalData.currentGlobalAlpha = this.contextData.cO; return; } this.contextData.cO *= op < 0 ? 0 : op; if (this.globalData.currentGlobalAlpha !== this.contextData.cO) { this.canvasContext.globalAlpha = this.contextData.cO; this.globalData.currentGlobalAlpha = this.contextData.cO; } }; CanvasRendererBase.prototype.reset = function() { if (!this.renderConfig.clearCanvas) { this.canvasContext.restore(); return; } this.contextData.reset(); }; CanvasRendererBase.prototype.save = function(actionFlag) { if (!this.renderConfig.clearCanvas) { this.canvasContext.save(); return; } if (actionFlag) this.canvasContext.save(); var props = this.contextData.cTr.props; if (this.contextData._length <= this.contextData.cArrPos) this.contextData.duplicate(); var i; var arr = this.contextData.saved[this.contextData.cArrPos]; for (i = 0; i < 16; i += 1) arr[i] = props[i]; this.contextData.savedOp[this.contextData.cArrPos] = this.contextData.cO; this.contextData.cArrPos += 1; }; CanvasRendererBase.prototype.restore = function(actionFlag) { if (!this.renderConfig.clearCanvas) { this.canvasContext.restore(); return; } if (actionFlag) { this.canvasContext.restore(); this.globalData.blendMode = "source-over"; } this.contextData.cArrPos -= 1; var popped = this.contextData.saved[this.contextData.cArrPos]; var i; var arr = this.contextData.cTr.props; for (i = 0; i < 16; i += 1) arr[i] = popped[i]; this.canvasContext.setTransform(popped[0], popped[1], popped[4], popped[5], popped[12], popped[13]); popped = this.contextData.savedOp[this.contextData.cArrPos]; this.contextData.cO = popped; if (this.globalData.currentGlobalAlpha !== popped) { this.canvasContext.globalAlpha = popped; this.globalData.currentGlobalAlpha = popped; } }; CanvasRendererBase.prototype.configAnimation = function(animData) { if (this.animationItem.wrapper) { this.animationItem.container = createTag("canvas"); var containerStyle = this.animationItem.container.style; containerStyle.width = "100%"; containerStyle.height = "100%"; var origin = "0px 0px 0px"; containerStyle.transformOrigin = origin; containerStyle.mozTransformOrigin = origin; containerStyle.webkitTransformOrigin = origin; containerStyle["-webkit-transform"] = origin; containerStyle.contentVisibility = this.renderConfig.contentVisibility; this.animationItem.wrapper.appendChild(this.animationItem.container); this.canvasContext = this.animationItem.container.getContext("2d"); if (this.renderConfig.className) this.animationItem.container.setAttribute("class", this.renderConfig.className); if (this.renderConfig.id) this.animationItem.container.setAttribute("id", this.renderConfig.id); } else this.canvasContext = this.renderConfig.context; this.data = animData; this.layers = animData.layers; this.transformCanvas = { w: animData.w, h: animData.h, sx: 0, sy: 0, tx: 0, ty: 0 }; this.setupGlobalData(animData, document.body); this.globalData.canvasContext = this.canvasContext; this.globalData.renderer = this; this.globalData.isDashed = false; this.globalData.progressiveLoad = this.renderConfig.progressiveLoad; this.globalData.transformCanvas = this.transformCanvas; this.elements = createSizedArray(animData.layers.length); this.updateContainerSize(); }; CanvasRendererBase.prototype.updateContainerSize = function() { this.reset(); var elementWidth; var elementHeight; if (this.animationItem.wrapper && this.animationItem.container) { elementWidth = this.animationItem.wrapper.offsetWidth; elementHeight = this.animationItem.wrapper.offsetHeight; this.animationItem.container.setAttribute("width", elementWidth * this.renderConfig.dpr); this.animationItem.container.setAttribute("height", elementHeight * this.renderConfig.dpr); } else { elementWidth = this.canvasContext.canvas.width * this.renderConfig.dpr; elementHeight = this.canvasContext.canvas.height * this.renderConfig.dpr; } var elementRel; var animationRel; if (this.renderConfig.preserveAspectRatio.indexOf("meet") !== -1 || this.renderConfig.preserveAspectRatio.indexOf("slice") !== -1) { var par = this.renderConfig.preserveAspectRatio.split(" "); var fillType = par[1] || "meet"; var pos = par[0] || "xMidYMid"; var xPos = pos.substr(0, 4); var yPos = pos.substr(4); elementRel = elementWidth / elementHeight; animationRel = this.transformCanvas.w / this.transformCanvas.h; if (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice") { this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); this.transformCanvas.sy = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); } else { this.transformCanvas.sx = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); } if (xPos === "xMid" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) / 2 * this.renderConfig.dpr; else if (xPos === "xMax" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) * this.renderConfig.dpr; else this.transformCanvas.tx = 0; if (yPos === "YMid" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) / 2 * this.renderConfig.dpr; else if (yPos === "YMax" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) * this.renderConfig.dpr; else this.transformCanvas.ty = 0; } else if (this.renderConfig.preserveAspectRatio === "none") { this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); this.transformCanvas.tx = 0; this.transformCanvas.ty = 0; } else { this.transformCanvas.sx = this.renderConfig.dpr; this.transformCanvas.sy = this.renderConfig.dpr; this.transformCanvas.tx = 0; this.transformCanvas.ty = 0; } this.transformCanvas.props = [ this.transformCanvas.sx, 0, 0, 0, 0, this.transformCanvas.sy, 0, 0, 0, 0, 1, 0, this.transformCanvas.tx, this.transformCanvas.ty, 0, 1 ]; this.ctxTransform(this.transformCanvas.props); this.canvasContext.beginPath(); this.canvasContext.rect(0, 0, this.transformCanvas.w, this.transformCanvas.h); this.canvasContext.closePath(); this.canvasContext.clip(); this.renderFrame(this.renderedFrame, true); }; CanvasRendererBase.prototype.destroy = function() { if (this.renderConfig.clearCanvas && this.animationItem.wrapper) this.animationItem.wrapper.innerText = ""; var i; for (i = (this.layers ? this.layers.length : 0) - 1; i >= 0; i -= 1) if (this.elements[i]) this.elements[i].destroy(); this.elements.length = 0; this.globalData.canvasContext = null; this.animationItem.container = null; this.destroyed = true; }; CanvasRendererBase.prototype.renderFrame = function(num, forceRender) { if (this.renderedFrame === num && this.renderConfig.clearCanvas === true && !forceRender || this.destroyed || num === -1) return; this.renderedFrame = num; this.globalData.frameNum = num - this.animationItem._isFirstFrame; this.globalData.frameId += 1; this.globalData._mdf = !this.renderConfig.clearCanvas || forceRender; this.globalData.projectInterface.currentFrame = num; var i; var len = this.layers.length; if (!this.completeLayers) this.checkLayers(num); for (i = 0; i < len; i += 1) if (this.completeLayers || this.elements[i]) this.elements[i].prepareFrame(num - this.layers[i].st); if (this.globalData._mdf) { if (this.renderConfig.clearCanvas === true) this.canvasContext.clearRect(0, 0, this.transformCanvas.w, this.transformCanvas.h); else this.save(); for (i = len - 1; i >= 0; i -= 1) if (this.completeLayers || this.elements[i]) this.elements[i].renderFrame(); if (this.renderConfig.clearCanvas !== true) this.restore(); } }; CanvasRendererBase.prototype.buildItem = function(pos) { var elements = this.elements; if (elements[pos] || this.layers[pos].ty === 99) return; var element = this.createItem(this.layers[pos], this, this.globalData); elements[pos] = element; element.initExpressions(); }; CanvasRendererBase.prototype.checkPendingElements = function() { while (this.pendingElements.length) this.pendingElements.pop().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 i; for (i = this.layers.length - 1; i >= 0; i -= 1) if (this.completeLayers || this.elements[i]) this.elements[i].renderFrame(); }; CVCompElement.prototype.destroy = function() { var i; for (i = this.layers.length - 1; i >= 0; i -= 1) if (this.elements[i]) this.elements[i].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 i; var len = registers.length; for (i = 0; i < len; i += 1) registers[i].release(); registers.length = 0; } animation.renderer.compInterface = CompExpressionInterface(animation.renderer); animation.renderer.globalData.projectInterface.registerComposition(animation.renderer); animation.renderer.globalData.pushExpression = pushExpression; animation.renderer.globalData.popExpression = popExpression; animation.renderer.globalData.registerExpressionProperty = registerExpressionProperty; } return ob; }(); function seedRandom(pool, math) { var global = 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(seed, options, callback) { var key = []; options = options === true ? { entropy: true } : options || {}; var shortseed = mixkey(flatten(options.entropy ? [seed, tostring(pool)] : seed === null ? autoseed() : seed, 3), key); var arc4 = new ARC4(key); var prng = function() { var n = arc4.g(chunks), d = startdenom, x = 0; while (n < significance) { n = (n + x) * width; d *= width; x = arc4.g(1); } while (n >= overflow) { n /= 2; d /= 2; x >>>= 1; } return (n + x) / d; }; prng.int32 = function() { return arc4.g(4) | 0; }; prng.quick = function() { return arc4.g(4) / 4294967296; }; prng.double = prng; mixkey(tostring(arc4.S), pool); return (options.pass || callback || function(prng2, seed2, is_math_call, state) { if (state) { if (state.S) copy(state, arc4); prng2.state = function() { return copy(arc4, {}); }; } if (is_math_call) { math[rngname] = prng2; return seed2; } else return prng2; })(prng, shortseed, "global" in options ? options.global : this == math, options.state); } math["seed" + rngname] = seedrandom; function ARC4(key) { var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; if (!keylen) key = [keylen++]; while (i < width) s[i] = i++; for (i = 0; i < width; i++) { s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])]; s[j] = t; } me.g = function(count) { var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S; while (count--) { t2 = s2[i2 = mask & i2 + 1]; r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)]; } me.i = i2; me.j = j2; return r; }; } function copy(f, t) { t.i = f.i; t.j = f.j; t.S = f.S.slice(); return t; } 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 (e) {} return result.length ? result : typ == "string" ? obj : obj + "\0"; } function mixkey(seed, key) { var stringseed = seed + "", 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 out = new Uint8Array(width); (global.crypto || global.msCrypto).getRandomValues(out); return tostring(out); } catch (e) { var browser = global.navigator, plugins = browser && browser.plugins; return [ +/* @__PURE__ */ new Date(), global, plugins, global.screen, tostring(pool) ]; } } function tostring(a) { return String.fromCharCode.apply(0, a); } 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 fetch = null; var frames = null; initialize$2(BMMath); function $bm_isInstanceOfArray(arr) { return arr.constructor === Array || arr.constructor === Float32Array; } function isNumerable(tOfV, v) { return tOfV === "number" || tOfV === "boolean" || tOfV === "string" || v instanceof Number; } function $bm_neg(a) { var tOfA = typeof a; if (tOfA === "number" || tOfA === "boolean" || a instanceof Number) return -a; if ($bm_isInstanceOfArray(a)) { var i; var lenA = a.length; var retArr = []; for (i = 0; i < lenA; i += 1) retArr[i] = -a[i]; return retArr; } if (a.propType) return a.v; return -a; } BezierFactory.getBezierEasing(.333, 0, .833, .833, "easeIn").get; BezierFactory.getBezierEasing(.167, .167, .667, 1, "easeOut").get; BezierFactory.getBezierEasing(.33, 0, .667, 1, "easeInOut").get; function sum(a, b) { var tOfA = typeof a; var tOfB = typeof b; if (tOfA === "string" || tOfB === "string") return a + b; if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) return a + b; if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { a = a.slice(0); a[0] += b; return a; } if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { b = b.slice(0); b[0] = a + b[0]; return b; } if ($bm_isInstanceOfArray(a) && $bm_isInstanceOfArray(b)) { var i = 0; var lenA = a.length; var lenB = b.length; var retArr = []; while (i < lenA || i < lenB) { if ((typeof a[i] === "number" || a[i] instanceof Number) && (typeof b[i] === "number" || b[i] instanceof Number)) retArr[i] = a[i] + b[i]; else retArr[i] = b[i] === void 0 ? a[i] : a[i] || b[i]; i += 1; } return retArr; } return 0; } var add = sum; function sub(a, b) { var tOfA = typeof a; var tOfB = typeof b; if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { if (tOfA === "string") a = parseInt(a, 10); if (tOfB === "string") b = parseInt(b, 10); return a - b; } if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { a = a.slice(0); a[0] -= b; return a; } if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { b = b.slice(0); b[0] = a - b[0]; return b; } if ($bm_isInstanceOfArray(a) && $bm_isInstanceOfArray(b)) { var i = 0; var lenA = a.length; var lenB = b.length; var retArr = []; while (i < lenA || i < lenB) { if ((typeof a[i] === "number" || a[i] instanceof Number) && (typeof b[i] === "number" || b[i] instanceof Number)) retArr[i] = a[i] - b[i]; else retArr[i] = b[i] === void 0 ? a[i] : a[i] || b[i]; i += 1; } return retArr; } return 0; } function mul(a, b) { var tOfA = typeof a; var tOfB = typeof b; var arr; if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) return a * b; var i; var len; if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { len = a.length; arr = createTypedArray("float32", len); for (i = 0; i < len; i += 1) arr[i] = a[i] * b; return arr; } if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { len = b.length; arr = createTypedArray("float32", len); for (i = 0; i < len; i += 1) arr[i] = a * b[i]; return arr; } return 0; } function div(a, b) { var tOfA = typeof a; var tOfB = typeof b; var arr; if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) return a / b; var i; var len; if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { len = a.length; arr = createTypedArray("float32", len); for (i = 0; i < len; i += 1) arr[i] = a[i] / b; return arr; } if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { len = b.length; arr = createTypedArray("float32", len); for (i = 0; i < len; i += 1) arr[i] = a / b[i]; return arr; } return 0; } function mod(a, b) { if (typeof a === "string") a = parseInt(a, 10); if (typeof b === "string") b = parseInt(b, 10); return a % b; } var $bm_sum = sum; var $bm_sub = sub; var $bm_mul = mul; var $bm_div = div; var $bm_mod = mod; function clamp(num, min, max) { if (min > max) { var mm = max; max = min; min = mm; } return Math2.min(Math2.max(num, min), max); } 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 length(arr1, arr2) { if (typeof arr1 === "number" || arr1 instanceof Number) { arr2 = arr2 || 0; return Math2.abs(arr1 - arr2); } if (!arr2) arr2 = helperLengthArray; var i; var len = Math2.min(arr1.length, arr2.length); var addedLength = 0; for (i = 0; i < len; i += 1) addedLength += Math2.pow(arr2[i] - arr1[i], 2); return Math2.sqrt(addedLength); } function normalize(vec) { return div(vec, length(vec)); } function rgbToHsl(val) { var r = val[0]; var g = val[1]; var b = val[2]; var max = Math2.max(r, g, b); var min = Math2.min(r, g, b); var h; var s; var l = (max + min) / 2; if (max === min) { h = 0; s = 0; } else { var d = max - min; s = l > .5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [ h, s, l, val[3] ]; } function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } function hslToRgb(val) { var h = val[0]; var s = val[1]; var l = val[2]; var r; var g; var b; if (s === 0) { r = l; b = l; g = l; } else { var q = l < .5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return [ r, g, b, val[3] ]; } function linear(t, 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 (t <= tMin) return value1; if (t >= tMax) return value2; var perc = tMax === tMin ? 0 : (t - tMin) / (tMax - tMin); if (!value1.length) return value1 + (value2 - value1) * perc; var i; var len = value1.length; var arr = createTypedArray("float32", len); for (i = 0; i < len; i += 1) arr[i] = value1[i] + (value2[i] - value1[i]) * perc; return arr; } function random(min, max) { if (max === void 0) if (min === void 0) { min = 0; max = 1; } else { max = min; min = void 0; } if (max.length) { var i; var len = max.length; if (!min) min = createTypedArray("float32", len); var arr = createTypedArray("float32", len); var rnd = BMMath.random(); for (i = 0; i < len; i += 1) arr[i] = min[i] + rnd * (max[i] - min[i]); return arr; } if (min === void 0) min = 0; var rndm = BMMath.random(); return min + rndm * (max - min); } function createPath(points, inTangents, outTangents, closed) { var i; var len = points.length; var path = shapePool.newElement(); path.setPathData(!!closed, len); var arrPlaceholder = [0, 0]; var inVertexPoint; var outVertexPoint; for (i = 0; i < len; i += 1) { inVertexPoint = inTangents && inTangents[i] ? inTangents[i] : arrPlaceholder; outVertexPoint = outTangents && outTangents[i] ? outTangents[i] : arrPlaceholder; path.setTripleAt(points[i][0], points[i][1], outVertexPoint[0] + points[i][0], outVertexPoint[1] + points[i][1], inVertexPoint[0] + points[i][0], inVertexPoint[1] + points[i][1], i, true); } return path; } function noOp(_value) { return _value; } function initiateExpression(elem, data, property) { return noOp; } ob.initiateExpression = initiateExpression; ob.__preventDeadCodeRemoval = [ window2, document2, XMLHttpRequest2, fetch, frames, $bm_neg, add, $bm_sum, $bm_sub, $bm_mul, $bm_div, $bm_mod, clamp, radians_to_degrees, degreesToRadians, degrees_to_radians, normalize, rgbToHsl, hslToRgb, linear, random, createPath ]; return ob; }(); const expressionHelpers = 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 = -.01; var v1 = this.getValueAtTime(frameNum); var v2 = this.getValueAtTime(frameNum + delta); var speed = 0; if (v1.length) { var i; for (i = 0; i < v1.length; i += 1) speed += Math.pow(v2[i] - v1[i], 2); speed = Math.sqrt(speed) * 100; } else speed = 0; return speed; } function getVelocityAtTime(frameNum) { if (this.vel !== void 0) return this.vel; var delta = -.001; var v1 = this.getValueAtTime(frameNum); var v2 = this.getValueAtTime(frameNum + delta); var velocity; if (v1.length) { velocity = createTypedArray("float32", v1.length); var i; for (i = 0; i < v1.length; i += 1) velocity[i] = (v2[i] - v1[i]) / delta; } else velocity = (v2 - v1) / 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 i; var len; var ret; if (type === "pingpong") { if (Math.floor((currentFrame - firstKeyFrame) / cycleDuration) % 2 !== 0) return this.getValueAtTime((cycleDuration - (currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); } else if (type === "offset") { var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); var current = this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); var repeats = Math.floor((currentFrame - firstKeyFrame) / cycleDuration); if (this.pv.length) { ret = new Array(initV.length); len = ret.length; for (i = 0; i < len; i += 1) ret[i] = (endV[i] - initV[i]) * repeats + current[i]; return ret; } return (endV - initV) * repeats + current; } else if (type === "continue") { var lastValue = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); var nextLastValue = this.getValueAtTime((lastKeyFrame - .001) / this.comp.globalData.frameRate, 0); if (this.pv.length) { ret = new Array(lastValue.length); len = ret.length; for (i = 0; i < len; i += 1) ret[i] = lastValue[i] + (lastValue[i] - nextLastValue[i]) * ((currentFrame - lastKeyFrame) / this.comp.globalData.frameRate) / 5e-4; return ret; } return lastValue + (lastValue - nextLastValue) * ((currentFrame - lastKeyFrame) / .001); } 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 i; var len; var ret; if (type === "pingpong") { if (Math.floor((firstKeyFrame - currentFrame) / cycleDuration) % 2 === 0) return this.getValueAtTime(((firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); } else if (type === "offset") { var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); var current = this.getValueAtTime((cycleDuration - (firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); var repeats = Math.floor((firstKeyFrame - currentFrame) / cycleDuration) + 1; if (this.pv.length) { ret = new Array(initV.length); len = ret.length; for (i = 0; i < len; i += 1) ret[i] = current[i] - (endV[i] - initV[i]) * repeats; return ret; } return current - (endV - initV) * repeats; } else if (type === "continue") { var firstValue = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); var nextFirstValue = this.getValueAtTime((firstKeyFrame + .001) / this.comp.globalData.frameRate, 0); if (this.pv.length) { ret = new Array(firstValue.length); len = ret.length; for (i = 0; i < len; i += 1) ret[i] = firstValue[i] + (firstValue[i] - nextFirstValue[i]) * (firstKeyFrame - currentFrame) / .001; return ret; } return firstValue + (firstValue - nextFirstValue) * (firstKeyFrame - currentFrame) / .001; } 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 || .4) * .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 i = 0; var j = 0; var value; if (this.pv.length) value = createTypedArray("float32", this.pv.length); else value = 0; var sampleValue; while (i < samples) { sampleValue = this.getValueAtTime(initFrame + i * sampleFrequency); if (this.pv.length) for (j = 0; j < this.pv.length; j += 1) value[j] += sampleValue[j]; else value += sampleValue; i += 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 matrix = this._transformCachingAtTime.v; matrix.cloneFromProps(this.pre.props); if (this.appliedTransformations < 1) { var anchor = this.a.getValueAtTime(time); matrix.translate(-anchor[0] * this.a.mult, -anchor[1] * this.a.mult, anchor[2] * this.a.mult); } if (this.appliedTransformations < 2) { var scale = this.s.getValueAtTime(time); matrix.scale(scale[0] * this.s.mult, scale[1] * this.s.mult, scale[2] * this.s.mult); } if (this.sk && this.appliedTransformations < 3) { var skew = this.sk.getValueAtTime(time); var skewAxis = this.sa.getValueAtTime(time); matrix.skewFromAxis(-skew * this.sk.mult, skewAxis * this.sa.mult); } if (this.r && this.appliedTransformations < 4) { var rotation = this.r.getValueAtTime(time); matrix.rotate(-rotation * 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); matrix.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); matrix.translate(positionX * this.px.mult, positionY * this.py.mult, -positionZ * this.pz.mult); } else matrix.translate(positionX * this.px.mult, positionY * this.py.mult, 0); } else { var position = this.p.getValueAtTime(time); matrix.translate(position[0] * this.p.mult, position[1] * this.p.mult, -position[2] * this.p.mult); } return matrix; } 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 i; var len = shapePath._length; var vertices = shapePath[prop]; var points = shapePath.v; var arr = createSizedArray(len); for (i = 0; i < len; i += 1) if (prop === "i" || prop === "o") arr[i] = [vertices[i][0] - points[i][0], vertices[i][1] - points[i][1]]; else arr[i] = [vertices[i][0], vertices[i][1]]; return arr; }, points: function(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 i = 0; var len = lengths.length; var accumulatedLength = 0; var pt; while (i < len) { if (accumulatedLength + lengths[i].addedLength > lengthPos) { var initIndex = i; var endIndex = shapePath.c && i === len - 1 ? 0 : i + 1; var segmentPerc = (lengthPos - accumulatedLength) / lengths[i].addedLength; pt = bez.getPointInSegment(shapePath.v[initIndex], shapePath.v[endIndex], shapePath.o[initIndex], shapePath.i[endIndex], segmentPerc, lengths[i]); break; } else accumulatedLength += lengths[i].addedLength; i += 1; } if (!pt) pt = shapePath.c ? [shapePath.v[0][0], shapePath.v[0][1]] : [shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1]]; return pt; }, vectorOnPath: function(perc, time, vectorType) { if (perc == 1) perc = this.v.c; else if (perc == 0) perc = .999; var pt1 = this.pointOnPath(perc, time); var pt2 = this.pointOnPath(perc + .001, 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]; return vectorType === "tangent" ? [xLength / magnitude, yLength / magnitude] : [-yLength / magnitude, xLength / magnitude]; }, 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; })(); //#endregion //#region node_modules/three-stdlib/loaders/LottieLoader.js var LottieLoader = class extends Loader { setQuality(value) { this._quality = value; } load(url, onLoad, onProgress, onError) { const quality = this._quality || 1; const texture = new CanvasTexture(); texture.minFilter = NearestFilter; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setWithCredentials(this.withCredentials); loader.load(url, function(text) { const data = JSON.parse(text); const container = document.createElement("div"); container.style.width = data.w + "px"; container.style.height = data.h + "px"; document.body.appendChild(container); const animation = lottie.loadAnimation({ container, animType: "canvas", loop: true, autoplay: true, animationData: data, rendererSettings: { dpr: quality } }); texture.animation = animation; texture.image = animation.container; animation.addEventListener("enterFrame", function() { texture.needsUpdate = true; }); container.style.display = "none"; if (onLoad !== void 0) onLoad(texture); }, onProgress, onError); return texture; } }; //#endregion //#region node_modules/three-stdlib/libs/opentype.js var { parseBuffer } = /* @__PURE__ */ (() => { 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(320); function tinf_build_bits_base(bits, base, delta, first) { var i, sum; for (i = 0; i < delta; ++i) bits[i] = 0; for (i = 0; i < 30 - delta; ++i) bits[i + delta] = i / delta | 0; for (sum = first, i = 0; i < 30; ++i) { base[i] = sum; sum += 1 << bits[i]; } } function tinf_build_fixed_trees(lt, dt) { var i; for (i = 0; i < 7; ++i) lt.table[i] = 0; lt.table[7] = 24; lt.table[8] = 152; lt.table[9] = 112; for (i = 0; i < 24; ++i) lt.trans[i] = 256 + i; for (i = 0; i < 144; ++i) lt.trans[24 + i] = i; for (i = 0; i < 8; ++i) lt.trans[168 + i] = 280 + i; for (i = 0; i < 112; ++i) lt.trans[176 + i] = 144 + i; for (i = 0; i < 5; ++i) dt.table[i] = 0; dt.table[5] = 32; for (i = 0; i < 32; ++i) dt.trans[i] = i; } var offs = new Uint16Array(16); function tinf_build_tree(t, lengths2, off, num) { var i, sum; for (i = 0; i < 16; ++i) t.table[i] = 0; for (i = 0; i < num; ++i) t.table[lengths2[off + i]]++; t.table[0] = 0; for (sum = 0, i = 0; i < 16; ++i) { offs[i] = sum; sum += t.table[i]; } for (i = 0; i < num; ++i) if (lengths2[off + i]) t.trans[offs[lengths2[off + i]]++] = i; } function tinf_getbit(d) { if (!d.bitcount--) { d.tag = d.source[d.sourceIndex++]; d.bitcount = 7; } var bit = d.tag & 1; d.tag >>>= 1; return bit; } function tinf_read_bits(d, num, base) { if (!num) return base; while (d.bitcount < 24) { d.tag |= d.source[d.sourceIndex++] << d.bitcount; d.bitcount += 8; } var val = d.tag & 65535 >>> 16 - num; d.tag >>>= num; d.bitcount -= num; return val + base; } function tinf_decode_symbol(d, t) { while (d.bitcount < 24) { d.tag |= d.source[d.sourceIndex++] << d.bitcount; d.bitcount += 8; } var sum = 0, cur = 0, len = 0; var tag = d.tag; do { cur = 2 * cur + (tag & 1); tag >>>= 1; ++len; sum += t.table[len]; cur -= t.table[len]; } while (cur >= 0); d.tag = tag; d.bitcount -= len; return t.trans[sum + cur]; } function tinf_decode_trees(d, lt, dt) { var hlit, hdist, hclen; var i, num, length; hlit = tinf_read_bits(d, 5, 257); hdist = tinf_read_bits(d, 5, 1); hclen = tinf_read_bits(d, 4, 4); for (i = 0; i < 19; ++i) lengths[i] = 0; for (i = 0; i < hclen; ++i) { var clen = tinf_read_bits(d, 3, 0); lengths[clcidx[i]] = clen; } tinf_build_tree(code_tree, lengths, 0, 19); for (num = 0; num < hlit + hdist;) { var sym = tinf_decode_symbol(d, code_tree); switch (sym) { case 16: var prev = lengths[num - 1]; for (length = tinf_read_bits(d, 2, 3); length; --length) lengths[num++] = prev; break; case 17: for (length = tinf_read_bits(d, 3, 3); length; --length) lengths[num++] = 0; break; case 18: for (length = tinf_read_bits(d, 7, 11); length; --length) lengths[num++] = 0; break; default: lengths[num++] = sym; break; } } tinf_build_tree(lt, lengths, 0, hlit); tinf_build_tree(dt, lengths, hlit, hdist); } function tinf_inflate_block_data(d, lt, dt) { while (1) { var sym = tinf_decode_symbol(d, lt); if (sym === 256) return TINF_OK; if (sym < 256) d.dest[d.destLen++] = sym; else { var length, dist, offs2; var i; sym -= 257; length = tinf_read_bits(d, length_bits[sym], length_base[sym]); dist = tinf_decode_symbol(d, dt); offs2 = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]); for (i = offs2; i < offs2 + length; ++i) d.dest[d.destLen++] = d.dest[i]; } } } function tinf_inflate_uncompressed_block(d) { var length, invlength; var i; while (d.bitcount > 8) { d.sourceIndex--; d.bitcount -= 8; } length = d.source[d.sourceIndex + 1]; length = 256 * length + d.source[d.sourceIndex]; invlength = d.source[d.sourceIndex + 3]; invlength = 256 * invlength + d.source[d.sourceIndex + 2]; if (length !== (~invlength & 65535)) return TINF_DATA_ERROR; d.sourceIndex += 4; for (i = length; i; --i) d.dest[d.destLen++] = d.source[d.sourceIndex++]; d.bitcount = 0; return TINF_OK; } function tinf_uncompress(source, dest) { var d = new Data(source, dest); var bfinal, btype, res; do { bfinal = tinf_getbit(d); btype = tinf_read_bits(d, 2, 0); switch (btype) { case 0: res = tinf_inflate_uncompressed_block(d); break; case 1: res = tinf_inflate_block_data(d, sltree, sdtree); break; case 2: tinf_decode_trees(d, d.ltree, d.dtree); res = tinf_inflate_block_data(d, d.ltree, d.dtree); break; default: res = TINF_DATA_ERROR; } if (res !== TINF_OK) throw new Error("Data error"); } while (!bfinal); if (d.destLen < d.dest.length) if (typeof d.dest.slice === "function") return d.dest.slice(0, d.destLen); else return d.dest.subarray(0, d.destLen); return d.dest; } tinf_build_fixed_trees(sltree, sdtree); tinf_build_bits_base(length_bits, length_base, 4, 3); tinf_build_bits_base(dist_bits, dist_base, 2, 1); length_bits[28] = 0; length_base[28] = 258; var tinyInflate = tinf_uncompress; function derive(v0, v1, v2, v3, t) { return Math.pow(1 - t, 3) * v0 + 3 * Math.pow(1 - t, 2) * t * v1 + 3 * (1 - t) * Math.pow(t, 2) * v2 + Math.pow(t, 3) * v3; } function BoundingBox() { this.x1 = NaN; this.y1 = NaN; this.x2 = NaN; this.y2 = 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 i = 0; i <= 1; i++) { var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; var c = 3 * p1[i] - 3 * p0[i]; if (a === 0) { if (b === 0) continue; var t = -c / b; if (0 < t && t < 1) { if (i === 0) this.addX(derive(p0[i], p1[i], p2[i], p3[i], t)); if (i === 1) this.addY(derive(p0[i], p1[i], p2[i], p3[i], t)); } continue; } var b2ac = Math.pow(b, 2) - 4 * c * a; if (b2ac < 0) continue; var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); if (0 < t1 && t1 < 1) { if (i === 0) this.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); if (i === 1) this.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); } var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); if (0 < t2 && t2 < 1) { if (i === 0) this.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); if (i === 1) this.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); } } }; 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 Path() { this.commands = []; this.fill = "black"; this.stroke = null; this.strokeWidth = 1; } Path.prototype.moveTo = function(x, y) { this.commands.push({ type: "M", x, y }); }; Path.prototype.lineTo = function(x, y) { this.commands.push({ type: "L", x, y }); }; Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) { this.commands.push({ type: "C", x1, y1, x2, y2, x, y }); }; Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) { this.commands.push({ type: "Q", x1, y1, x, y }); }; Path.prototype.close = Path.prototype.closePath = function() { this.commands.push({ type: "Z" }); }; Path.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); }; Path.prototype.getBoundingBox = function() { var box = new BoundingBox(); var startX = 0; var startY = 0; var prevX = 0; var prevY = 0; for (var i = 0; i < this.commands.length; i++) { var cmd = this.commands[i]; switch (cmd.type) { case "M": box.addPoint(cmd.x, cmd.y); startX = prevX = cmd.x; startY = prevY = cmd.y; break; case "L": box.addPoint(cmd.x, cmd.y); prevX = cmd.x; prevY = cmd.y; break; case "Q": box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y); prevX = cmd.x; prevY = cmd.y; break; case "C": box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); prevX = cmd.x; prevY = cmd.y; break; case "Z": prevX = startX; prevY = startY; break; default: throw new Error("Unexpected path command " + cmd.type); } } if (box.isEmpty()) box.addPoint(0, 0); return box; }; Path.prototype.draw = function(ctx) { ctx.beginPath(); for (var i = 0; i < this.commands.length; i += 1) { var cmd = this.commands[i]; if (cmd.type === "M") ctx.moveTo(cmd.x, cmd.y); else if (cmd.type === "L") ctx.lineTo(cmd.x, cmd.y); else if (cmd.type === "C") ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); else if (cmd.type === "Q") ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); else if (cmd.type === "Z") ctx.closePath(); } if (this.fill) { ctx.fillStyle = this.fill; ctx.fill(); } if (this.stroke) { ctx.strokeStyle = this.stroke; ctx.lineWidth = this.strokeWidth; ctx.stroke(); } }; Path.prototype.toPathData = function(decimalPlaces) { decimalPlaces = decimalPlaces !== void 0 ? decimalPlaces : 2; function floatToString(v) { if (Math.round(v) === v) return "" + Math.round(v); else return v.toFixed(decimalPlaces); } function packValues() { var arguments$1 = arguments; var s = ""; for (var i2 = 0; i2 < arguments.length; i2 += 1) { var v = arguments$1[i2]; if (v >= 0 && i2 > 0) s += " "; s += floatToString(v); } return s; } var d = ""; for (var i = 0; i < this.commands.length; i += 1) { var cmd = this.commands[i]; if (cmd.type === "M") d += "M" + packValues(cmd.x, cmd.y); else if (cmd.type === "L") d += "L" + packValues(cmd.x, cmd.y); else if (cmd.type === "C") d += "C" + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); else if (cmd.type === "Q") d += "Q" + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); else if (cmd.type === "Z") d += "Z"; } return d; }; Path.prototype.toSVG = function(decimalPlaces) { var svg = "= 0 && v <= 255, "Byte value should be between 0 and 255."); return [v]; }; sizeOf.BYTE = constant(1); encode.CHAR = function(v) { return [v.charCodeAt(0)]; }; sizeOf.CHAR = constant(1); encode.CHARARRAY = function(v) { if (typeof v === "undefined") { v = ""; console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name."); } var b = []; for (var i = 0; i < v.length; i += 1) b[i] = v.charCodeAt(i); return b; }; sizeOf.CHARARRAY = function(v) { if (typeof v === "undefined") return 0; return v.length; }; encode.USHORT = function(v) { return [v >> 8 & 255, v & 255]; }; sizeOf.USHORT = constant(2); encode.SHORT = function(v) { if (v >= LIMIT16) v = -(2 * LIMIT16 - v); return [v >> 8 & 255, v & 255]; }; sizeOf.SHORT = constant(2); encode.UINT24 = function(v) { return [ v >> 16 & 255, v >> 8 & 255, v & 255 ]; }; sizeOf.UINT24 = constant(3); encode.ULONG = function(v) { return [ v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255 ]; }; sizeOf.ULONG = constant(4); encode.LONG = function(v) { if (v >= LIMIT32) v = -(2 * LIMIT32 - v); return [ v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255 ]; }; sizeOf.LONG = constant(4); encode.FIXED = encode.ULONG; sizeOf.FIXED = sizeOf.ULONG; encode.FWORD = encode.SHORT; sizeOf.FWORD = sizeOf.SHORT; encode.UFWORD = encode.USHORT; sizeOf.UFWORD = sizeOf.USHORT; encode.LONGDATETIME = function(v) { return [ 0, 0, 0, 0, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255 ]; }; sizeOf.LONGDATETIME = constant(8); encode.TAG = function(v) { check.argument(v.length === 4, "Tag should be exactly 4 ASCII characters."); return [ v.charCodeAt(0), v.charCodeAt(1), v.charCodeAt(2), v.charCodeAt(3) ]; }; sizeOf.TAG = constant(4); encode.Card8 = encode.BYTE; sizeOf.Card8 = sizeOf.BYTE; encode.Card16 = encode.USHORT; sizeOf.Card16 = sizeOf.USHORT; encode.OffSize = encode.BYTE; sizeOf.OffSize = sizeOf.BYTE; encode.SID = encode.USHORT; sizeOf.SID = sizeOf.USHORT; encode.NUMBER = function(v) { if (v >= -107 && v <= 107) return [v + 139]; else if (v >= 108 && v <= 1131) { v = v - 108; return [(v >> 8) + 247, v & 255]; } else if (v >= -1131 && v <= -108) { v = -v - 108; return [(v >> 8) + 251, v & 255]; } else if (v >= -32768 && v <= 32767) return encode.NUMBER16(v); else return encode.NUMBER32(v); }; sizeOf.NUMBER = function(v) { return encode.NUMBER(v).length; }; encode.NUMBER16 = function(v) { return [ 28, v >> 8 & 255, v & 255 ]; }; sizeOf.NUMBER16 = constant(3); encode.NUMBER32 = function(v) { return [ 29, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255 ]; }; sizeOf.NUMBER32 = constant(5); encode.REAL = function(v) { var value = v.toString(); var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); if (m) { var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length)); value = (Math.round(v * epsilon) / epsilon).toString(); } var nibbles = ""; for (var i = 0, ii = value.length; i < ii; i += 1) { var c = value[i]; if (c === "e") nibbles += value[++i] === "-" ? "c" : "b"; else if (c === ".") nibbles += "a"; else if (c === "-") nibbles += "e"; else nibbles += c; } nibbles += nibbles.length & 1 ? "f" : "ff"; var out = [30]; for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) out.push(parseInt(nibbles.substr(i$1, 2), 16)); return out; }; sizeOf.REAL = function(v) { return encode.REAL(v).length; }; encode.NAME = encode.CHARARRAY; sizeOf.NAME = sizeOf.CHARARRAY; encode.STRING = encode.CHARARRAY; sizeOf.STRING = sizeOf.CHARARRAY; decode.UTF8 = function(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(v) { var b = []; for (var i = 0; i < v.length; i += 1) { var codepoint = v.charCodeAt(i); b[b.length] = codepoint >> 8 & 255; b[b.length] = codepoint & 255; } return b; }; sizeOf.UTF16 = function(v) { return v.length * 2; }; var eightBitMacEncodings = { "x-mac-croatian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ", "x-mac-cyrillic": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю", "x-mac-gaelic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ", "x-mac-greek": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­", "x-mac-icelandic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", "x-mac-inuit": "ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł", "x-mac-ce": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ", macintosh: "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", "x-mac-romanian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", "x-mac-turkish": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ" }; decode.MACSTRING = function(dataView, offset, dataLength, encoding) { var table2 = eightBitMacEncodings[encoding]; if (table2 === void 0) return; var result = ""; for (var i = 0; i < dataLength; i++) { var c = dataView.getUint8(offset + i); if (c <= 127) result += String.fromCharCode(c); else result += table2[c & 127]; } return result; }; var macEncodingTableCache = typeof WeakMap === "function" && /* @__PURE__ */ new WeakMap(); var macEncodingCacheKeys; var getMacEncodingTable = function(encoding) { if (!macEncodingCacheKeys) { macEncodingCacheKeys = {}; for (var e in eightBitMacEncodings) macEncodingCacheKeys[e] = new String(e); } var cacheKey = macEncodingCacheKeys[encoding]; if (cacheKey === void 0) return; if (macEncodingTableCache) { var cachedTable = macEncodingTableCache.get(cacheKey); if (cachedTable !== void 0) return cachedTable; } var decodingTable = eightBitMacEncodings[encoding]; if (decodingTable === void 0) return; var encodingTable = {}; for (var i = 0; i < decodingTable.length; i++) encodingTable[decodingTable.charCodeAt(i)] = i + 128; if (macEncodingTableCache) macEncodingTableCache.set(cacheKey, encodingTable); return encodingTable; }; encode.MACSTRING = function(str, encoding) { var table2 = getMacEncodingTable(encoding); if (table2 === void 0) return; var result = []; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); if (c >= 128) { c = table2[c]; if (c === void 0) return; } result[i] = c; } return result; }; sizeOf.MACSTRING = function(str, encoding) { var b = encode.MACSTRING(str, encoding); if (b !== void 0) return b.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 i = offset; i < pos; ++i) result.push(deltas[i] + 256 & 255); return pos; } function encodeVarDeltaRunAsWords(deltas, offset, result) { var runLength = 0; var numDeltas = deltas.length; var pos = offset; while (pos < numDeltas && runLength < 64) { var 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 i = offset; i < pos; ++i) { var val = deltas[i]; 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(l) { var offset = 1; var offsets = [offset]; var data = []; for (var i = 0; i < l.length; i += 1) { var v = encode.OBJECT(l[i]); Array.prototype.push.apply(data, v); offset += v.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(l.length), encode.OffSize(offSize), encodedOffsets, data); }; sizeOf.INDEX = function(v) { return encode.INDEX(v).length; }; encode.DICT = function(m) { var d = []; var keys = Object.keys(m); var length = keys.length; for (var i = 0; i < length; i += 1) { var k = parseInt(keys[i], 0); var v = m[k]; d = d.concat(encode.OPERAND(v.value, v.type)); d = d.concat(encode.OPERATOR(k)); } return d; }; sizeOf.DICT = function(m) { return encode.DICT(m).length; }; encode.OPERATOR = function(v) { if (v < 1200) return [v]; else return [12, v - 1200]; }; encode.OPERAND = function(v, type) { var d = []; if (Array.isArray(type)) for (var i = 0; i < type.length; i += 1) { check.argument(v.length === type.length, "Not enough arguments given for type" + type); d = d.concat(encode.OPERAND(v[i], type[i])); } else if (type === "SID") d = d.concat(encode.NUMBER(v)); else if (type === "offset") d = d.concat(encode.NUMBER32(v)); else if (type === "number") d = d.concat(encode.NUMBER(v)); else if (type === "real") d = d.concat(encode.REAL(v)); else throw new Error("Unknown operand type " + type); return d; }; encode.OP = encode.BYTE; sizeOf.OP = sizeOf.BYTE; var wmm = typeof WeakMap === "function" && /* @__PURE__ */ new WeakMap(); encode.CHARSTRING = function(ops) { if (wmm) { var cachedValue = wmm.get(ops); if (cachedValue !== void 0) return cachedValue; } var d = []; var length = ops.length; for (var i = 0; i < length; i += 1) { var op = ops[i]; d = d.concat(encode[op.type](op.value)); } if (wmm) wmm.set(ops, d); return d; }; sizeOf.CHARSTRING = function(ops) { return encode.CHARSTRING(ops).length; }; encode.OBJECT = function(v) { var encodingFunction = encode[v.type]; check.argument(encodingFunction !== void 0, "No encoding function for type " + v.type); return encodingFunction(v.value); }; sizeOf.OBJECT = function(v) { var sizeOfFunction = sizeOf[v.type]; check.argument(sizeOfFunction !== void 0, "No sizeOf function for type " + v.type); return sizeOfFunction(v.value); }; encode.TABLE = function(table2) { var d = []; var length = table2.fields.length; var subtables = []; var subtableOffsets = []; for (var i = 0; i < length; i += 1) { var field = table2.fields[i]; var encodingFunction = encode[field.type]; check.argument(encodingFunction !== void 0, "No encoding function for field type " + field.type + " (" + field.name + ")"); var value = table2[field.name]; if (value === void 0) value = field.value; var bytes = encodingFunction(value); if (field.type === "TABLE") { subtableOffsets.push(d.length); d = d.concat([0, 0]); subtables.push(bytes); } else d = d.concat(bytes); } for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) { var o = subtableOffsets[i$1]; var offset = d.length; check.argument(offset < 65536, "Table " + table2.tableName + " too big."); d[o] = offset >> 8; d[o + 1] = offset & 255; d = d.concat(subtables[i$1]); } return d; }; sizeOf.TABLE = function(table2) { var numBytes = 0; var length = table2.fields.length; for (var i = 0; i < length; i += 1) { var field = table2.fields[i]; var sizeOfFunction = sizeOf[field.type]; check.argument(sizeOfFunction !== void 0, "No sizeOf function for field type " + field.type + " (" + field.name + ")"); var 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(v) { return v; }; sizeOf.LITERAL = function(v) { return v.length; }; function Table(tableName, fields, options) { if (fields.length && (fields[0].name !== "coverageFormat" || fields[0].value === 1)) for (var i = 0; i < fields.length; i += 1) { var field = fields[i]; this[field.name] = field.value; } this.tableName = tableName; this.fields = fields; if (options) { var optionKeys = Object.keys(options); for (var i$1 = 0; i$1 < optionKeys.length; i$1 += 1) { var k = optionKeys[i$1]; var v = options[k]; if (this[k] !== void 0) this[k] = v; } } } Table.prototype.encode = function() { return encode.TABLE(this); }; Table.prototype.sizeOf = function() { return sizeOf.TABLE(this); }; function ushortList(itemName, list, count) { if (count === void 0) count = list.length; var fields = new Array(list.length + 1); fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; for (var i = 0; i < list.length; i++) fields[i + 1] = { name: itemName + i, type: "USHORT", value: list[i] }; return fields; } function tableList(itemName, records, itemCallback) { var count = records.length; var fields = new Array(count + 1); fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; for (var i = 0; i < count; i++) fields[i + 1] = { name: itemName + i, type: "TABLE", value: itemCallback(records[i], i) }; return fields; } function recordList(itemName, records, itemCallback) { var count = records.length; var fields = []; fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; for (var i = 0; i < count; i++) fields = fields.concat(itemCallback(records[i], i)); return fields; } function Coverage(coverageTable) { if (coverageTable.format === 1) Table.call(this, "coverageTable", [{ name: "coverageFormat", type: "USHORT", value: 1 }].concat(ushortList("glyph", coverageTable.glyphs))); else if (coverageTable.format === 2) Table.call(this, "coverageTable", [{ name: "coverageFormat", type: "USHORT", value: 2 }].concat(recordList("rangeRecord", coverageTable.ranges, function(RangeRecord) { return [ { name: "startGlyphID", type: "USHORT", value: RangeRecord.start }, { name: "endGlyphID", type: "USHORT", value: RangeRecord.end }, { name: "startCoverageIndex", type: "USHORT", value: RangeRecord.index } ]; }))); else check.assert(false, "Coverage format must be 1 or 2."); } Coverage.prototype = Object.create(Table.prototype); Coverage.prototype.constructor = Coverage; function ScriptList(scriptListTable) { Table.call(this, "scriptListTable", recordList("scriptRecord", scriptListTable, function(scriptRecord, i) { var script = scriptRecord.script; var defaultLangSys = script.defaultLangSys; check.assert(!!defaultLangSys, "Unable to write GSUB: script " + scriptRecord.tag + " has no default language system."); return [{ name: "scriptTag" + i, type: "TAG", value: scriptRecord.tag }, { name: "script" + i, type: "TABLE", value: new Table("scriptTable", [{ name: "defaultLangSys", type: "TABLE", value: new Table("defaultLangSys", [{ name: "lookupOrder", type: "USHORT", value: 0 }, { name: "reqFeatureIndex", type: "USHORT", value: defaultLangSys.reqFeatureIndex }].concat(ushortList("featureIndex", defaultLangSys.featureIndexes))) }].concat(recordList("langSys", script.langSysRecords, function(langSysRecord, i2) { var langSys = langSysRecord.langSys; return [{ name: "langSysTag" + i2, type: "TAG", value: langSysRecord.tag }, { name: "langSys" + i2, type: "TABLE", value: new Table("langSys", [{ name: "lookupOrder", type: "USHORT", value: 0 }, { name: "reqFeatureIndex", type: "USHORT", value: langSys.reqFeatureIndex }].concat(ushortList("featureIndex", langSys.featureIndexes))) }]; }))) }]; })); } ScriptList.prototype = Object.create(Table.prototype); ScriptList.prototype.constructor = ScriptList; function FeatureList(featureListTable) { Table.call(this, "featureListTable", recordList("featureRecord", featureListTable, function(featureRecord, i) { var feature = featureRecord.feature; return [{ name: "featureTag" + i, type: "TAG", value: featureRecord.tag }, { name: "feature" + i, type: "TABLE", value: new Table("featureTable", [{ name: "featureParams", type: "USHORT", value: feature.featureParams }].concat(ushortList("lookupListIndex", feature.lookupListIndexes))) }]; })); } FeatureList.prototype = Object.create(Table.prototype); FeatureList.prototype.constructor = FeatureList; function LookupList(lookupListTable, subtableMakers2) { Table.call(this, "lookupListTable", tableList("lookup", lookupListTable, function(lookupTable) { var subtableCallback = subtableMakers2[lookupTable.lookupType]; check.assert(!!subtableCallback, "Unable to write GSUB lookup type " + lookupTable.lookupType + " tables."); return new Table("lookupTable", [{ name: "lookupType", type: "USHORT", value: lookupTable.lookupType }, { name: "lookupFlag", type: "USHORT", value: lookupTable.lookupFlag }].concat(tableList("subtable", lookupTable.subtables, subtableCallback))); })); } LookupList.prototype = Object.create(Table.prototype); LookupList.prototype.constructor = LookupList; var table = { Table, Record: Table, Coverage, ScriptList, FeatureList, LookupList, ushortList, tableList, recordList }; function getByte(dataView, offset) { return dataView.getUint8(offset); } function getUShort(dataView, offset) { return dataView.getUint16(offset, false); } function getShort(dataView, offset) { return dataView.getInt16(offset, false); } function getULong(dataView, offset) { return dataView.getUint32(offset, false); } function getFixed(dataView, offset) { return dataView.getInt16(offset, false) + dataView.getUint16(offset + 2, false) / 65535; } function getTag(dataView, offset) { var tag = ""; for (var i = offset; i < offset + 4; i += 1) tag += String.fromCharCode(dataView.getInt8(i)); return tag; } function getOffset(dataView, offset, offSize) { var v = 0; for (var i = 0; i < offSize; i += 1) { v <<= 8; v += dataView.getUint8(offset + i); } return v; } function getBytes(dataView, startOffset, endOffset) { var bytes = []; for (var i = startOffset; i < endOffset; i += 1) bytes.push(dataView.getUint8(i)); return bytes; } function bytesToString(bytes) { var s = ""; for (var i = 0; i < bytes.length; i += 1) s += String.fromCharCode(bytes[i]); return s; } var typeOffsets = { byte: 1, uShort: 2, short: 2, uLong: 4, fixed: 4, longDateTime: 8, tag: 4 }; function Parser(data, offset) { this.data = data; this.offset = offset; this.relativeOffset = 0; } Parser.prototype.parseByte = function() { var v = this.data.getUint8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseChar = function() { var v = this.data.getInt8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseCard8 = Parser.prototype.parseByte; Parser.prototype.parseUShort = function() { var v = this.data.getUint16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseCard16 = Parser.prototype.parseUShort; Parser.prototype.parseSID = Parser.prototype.parseUShort; Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; Parser.prototype.parseShort = function() { var v = this.data.getInt16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseF2Dot14 = function() { var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; this.relativeOffset += 2; return v; }; Parser.prototype.parseULong = function() { var v = getULong(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.parseOffset32 = Parser.prototype.parseULong; Parser.prototype.parseFixed = function() { var v = getFixed(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.parseString = function(length) { var dataView = this.data; var offset = this.offset + this.relativeOffset; var string = ""; this.relativeOffset += length; for (var i = 0; i < length; i++) string += String.fromCharCode(dataView.getUint8(offset + i)); return string; }; Parser.prototype.parseTag = function() { return this.parseString(4); }; Parser.prototype.parseLongDateTime = function() { var v = getULong(this.data, this.offset + this.relativeOffset + 4); v -= 2082844800; this.relativeOffset += 8; return v; }; Parser.prototype.parseVersion = function(minorBase) { var major = getUShort(this.data, this.offset + this.relativeOffset); var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); this.relativeOffset += 4; if (minorBase === void 0) minorBase = 4096; return major + minor / minorBase / 10; }; Parser.prototype.skip = function(type, amount) { if (amount === void 0) amount = 1; this.relativeOffset += typeOffsets[type] * amount; }; Parser.prototype.parseULongList = function(count) { if (count === void 0) count = this.parseULong(); var offsets = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i = 0; i < count; i++) { offsets[i] = dataView.getUint32(offset); offset += 4; } this.relativeOffset += count * 4; return offsets; }; Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function(count) { if (count === void 0) count = this.parseUShort(); var offsets = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i = 0; i < count; i++) { offsets[i] = dataView.getUint16(offset); offset += 2; } this.relativeOffset += count * 2; return offsets; }; Parser.prototype.parseShortList = function(count) { var list = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i = 0; i < count; i++) { list[i] = dataView.getInt16(offset); offset += 2; } this.relativeOffset += count * 2; return list; }; Parser.prototype.parseByteList = function(count) { var list = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i = 0; i < count; i++) list[i] = dataView.getUint8(offset++); this.relativeOffset += count; return list; }; Parser.prototype.parseList = function(count, itemCallback) { if (!itemCallback) { itemCallback = count; count = this.parseUShort(); } var list = new Array(count); for (var i = 0; i < count; i++) list[i] = itemCallback.call(this); return list; }; Parser.prototype.parseList32 = function(count, itemCallback) { if (!itemCallback) { itemCallback = count; count = this.parseULong(); } var list = new Array(count); for (var i = 0; i < count; i++) list[i] = itemCallback.call(this); return list; }; Parser.prototype.parseRecordList = function(count, recordDescription) { if (!recordDescription) { recordDescription = count; count = this.parseUShort(); } var records = new Array(count); var fields = Object.keys(recordDescription); for (var i = 0; i < count; i++) { var rec = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; rec[fieldName] = recordDescription[fieldName].call(this); } records[i] = rec; } return records; }; Parser.prototype.parseRecordList32 = function(count, recordDescription) { if (!recordDescription) { recordDescription = count; count = this.parseULong(); } var records = new Array(count); var fields = Object.keys(recordDescription); for (var i = 0; i < count; i++) { var rec = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; rec[fieldName] = recordDescription[fieldName].call(this); } records[i] = rec; } return records; }; Parser.prototype.parseStruct = function(description) { if (typeof description === "function") return description.call(this); else { var fields = Object.keys(description); var struct = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; struct[fieldName] = description[fieldName].call(this); } return struct; } }; Parser.prototype.parseValueRecord = function(valueFormat) { if (valueFormat === void 0) valueFormat = this.parseUShort(); if (valueFormat === 0) return; var valueRecord = {}; if (valueFormat & 1) valueRecord.xPlacement = this.parseShort(); if (valueFormat & 2) valueRecord.yPlacement = this.parseShort(); if (valueFormat & 4) valueRecord.xAdvance = this.parseShort(); if (valueFormat & 8) valueRecord.yAdvance = this.parseShort(); if (valueFormat & 16) { valueRecord.xPlaDevice = void 0; this.parseShort(); } if (valueFormat & 32) { valueRecord.yPlaDevice = void 0; this.parseShort(); } if (valueFormat & 64) { valueRecord.xAdvDevice = void 0; this.parseShort(); } if (valueFormat & 128) { valueRecord.yAdvDevice = void 0; this.parseShort(); } return valueRecord; }; Parser.prototype.parseValueRecordList = function() { var valueFormat = this.parseUShort(); var valueCount = this.parseUShort(); var values = new Array(valueCount); for (var i = 0; i < valueCount; i++) values[i] = this.parseValueRecord(valueFormat); return values; }; Parser.prototype.parsePointer = function(description) { var structOffset = this.parseOffset16(); if (structOffset > 0) return new Parser(this.data, this.offset + structOffset).parseStruct(description); }; Parser.prototype.parsePointer32 = function(description) { var structOffset = this.parseOffset32(); if (structOffset > 0) return new Parser(this.data, this.offset + structOffset).parseStruct(description); }; Parser.prototype.parseListOfLists = function(itemCallback) { var offsets = this.parseOffset16List(); var count = offsets.length; var relativeOffset = this.relativeOffset; var list = new Array(count); for (var i = 0; i < count; i++) { var start = offsets[i]; if (start === 0) { list[i] = void 0; continue; } this.relativeOffset = start; if (itemCallback) { var subOffsets = this.parseOffset16List(); var subList = new Array(subOffsets.length); for (var j = 0; j < subOffsets.length; j++) { this.relativeOffset = start + subOffsets[j]; subList[j] = itemCallback.call(this); } list[i] = subList; } else list[i] = this.parseUShortList(); } this.relativeOffset = relativeOffset; return list; }; Parser.prototype.parseCoverage = function() { var startOffset = this.offset + this.relativeOffset; var format = this.parseUShort(); var count = this.parseUShort(); if (format === 1) return { format: 1, glyphs: this.parseUShortList(count) }; else if (format === 2) { var ranges = new Array(count); for (var i = 0; i < count; i++) ranges[i] = { start: this.parseUShort(), end: this.parseUShort(), index: this.parseUShort() }; return { format: 2, ranges }; } throw new Error("0x" + startOffset.toString(16) + ": Coverage format must be 1 or 2."); }; Parser.prototype.parseClassDef = function() { var startOffset = this.offset + this.relativeOffset; var format = this.parseUShort(); if (format === 1) return { format: 1, startGlyph: this.parseUShort(), classes: this.parseUShortList() }; else if (format === 2) return { format: 2, ranges: this.parseRecordList({ start: Parser.uShort, end: Parser.uShort, classId: Parser.uShort }) }; throw new Error("0x" + startOffset.toString(16) + ": ClassDef format must be 1 or 2."); }; Parser.list = function(count, itemCallback) { return function() { return this.parseList(count, itemCallback); }; }; Parser.list32 = function(count, itemCallback) { return function() { return this.parseList32(count, itemCallback); }; }; Parser.recordList = function(count, recordDescription) { return function() { return this.parseRecordList(count, recordDescription); }; }; Parser.recordList32 = function(count, recordDescription) { return function() { return this.parseRecordList32(count, recordDescription); }; }; Parser.pointer = function(description) { return function() { return this.parsePointer(description); }; }; Parser.pointer32 = function(description) { return function() { return this.parsePointer32(description); }; }; Parser.tag = Parser.prototype.parseTag; Parser.byte = Parser.prototype.parseByte; Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; Parser.uShortList = Parser.prototype.parseUShortList; Parser.uLong = Parser.offset32 = Parser.prototype.parseULong; Parser.uLongList = Parser.prototype.parseULongList; Parser.struct = Parser.prototype.parseStruct; Parser.coverage = Parser.prototype.parseCoverage; Parser.classDef = Parser.prototype.parseClassDef; var langSysTable = { reserved: Parser.uShort, reqFeatureIndex: Parser.uShort, featureIndexes: Parser.uShortList }; Parser.prototype.parseScriptList = function() { return this.parsePointer(Parser.recordList({ tag: Parser.tag, script: Parser.pointer({ defaultLangSys: Parser.pointer(langSysTable), langSysRecords: Parser.recordList({ tag: Parser.tag, langSys: Parser.pointer(langSysTable) }) }) })) || []; }; Parser.prototype.parseFeatureList = function() { return this.parsePointer(Parser.recordList({ tag: Parser.tag, feature: Parser.pointer({ featureParams: Parser.offset16, lookupListIndexes: Parser.uShortList }) })) || []; }; Parser.prototype.parseLookupList = function(lookupTableParsers) { return this.parsePointer(Parser.list(Parser.pointer(function() { var lookupType = this.parseUShort(); check.argument(1 <= lookupType && lookupType <= 9, "GPOS/GSUB lookup type " + lookupType + " unknown."); var lookupFlag = this.parseUShort(); var useMarkFilteringSet = lookupFlag & 16; return { lookupType, lookupFlag, subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), markFilteringSet: useMarkFilteringSet ? this.parseUShort() : void 0 }; }))) || []; }; Parser.prototype.parseFeatureVariationsList = function() { return this.parsePointer32(function() { var majorVersion = this.parseUShort(); var minorVersion = this.parseUShort(); check.argument(majorVersion === 1 && minorVersion < 1, "GPOS/GSUB feature variations table unknown."); return this.parseRecordList32({ conditionSetOffset: Parser.offset32, featureTableSubstitutionOffset: Parser.offset32 }); }) || []; }; var parse = { getByte, getCard8: getByte, getUShort, getCard16: getUShort, getShort, getULong, getFixed, getTag, getOffset, getBytes, bytesToString, Parser }; function parseCmapTableFormat12(cmap2, p) { p.parseUShort(); cmap2.length = p.parseULong(); cmap2.language = p.parseULong(); var groupCount; cmap2.groupCount = groupCount = p.parseULong(); cmap2.glyphIndexMap = {}; for (var i = 0; i < groupCount; i += 1) { var startCharCode = p.parseULong(); var endCharCode = p.parseULong(); var startGlyphId = p.parseULong(); for (var c = startCharCode; c <= endCharCode; c += 1) { cmap2.glyphIndexMap[c] = startGlyphId; startGlyphId++; } } } function parseCmapTableFormat4(cmap2, p, data, start, offset) { cmap2.length = p.parseUShort(); cmap2.language = p.parseUShort(); var segCount; cmap2.segCount = segCount = p.parseUShort() >> 1; p.skip("uShort", 3); cmap2.glyphIndexMap = {}; var endCountParser = new parse.Parser(data, start + offset + 14); var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2); var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4); var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6); var glyphIndexOffset = start + offset + 16 + segCount * 8; for (var i = 0; i < segCount - 1; i += 1) { var glyphIndex = void 0; var endCount = endCountParser.parseUShort(); var startCount = startCountParser.parseUShort(); var idDelta = idDeltaParser.parseShort(); var idRangeOffset = idRangeOffsetParser.parseUShort(); for (var c = startCount; c <= endCount; c += 1) { if (idRangeOffset !== 0) { glyphIndexOffset = idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2; glyphIndexOffset += idRangeOffset; glyphIndexOffset += (c - startCount) * 2; glyphIndex = parse.getUShort(data, glyphIndexOffset); if (glyphIndex !== 0) glyphIndex = glyphIndex + idDelta & 65535; } else glyphIndex = c + idDelta & 65535; cmap2.glyphIndexMap[c] = glyphIndex; } } } function parseCmapTable(data, start) { var cmap2 = {}; cmap2.version = parse.getUShort(data, start); check.argument(cmap2.version === 0, "cmap table version should be 0."); cmap2.numTables = parse.getUShort(data, start + 2); var offset = -1; for (var i = cmap2.numTables - 1; i >= 0; i -= 1) { var platformId = parse.getUShort(data, start + 4 + i * 8); var encodingId = parse.getUShort(data, start + 4 + i * 8 + 2); if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10) || platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4)) { offset = parse.getULong(data, start + 4 + i * 8 + 4); break; } } if (offset === -1) throw new Error("No valid cmap sub-tables found."); var p = new parse.Parser(data, start + offset); cmap2.format = p.parseUShort(); if (cmap2.format === 12) parseCmapTableFormat12(cmap2, p); else if (cmap2.format === 4) parseCmapTableFormat4(cmap2, p, data, start, offset); else throw new Error("Only format 4 and 12 cmap tables are supported (found format " + cmap2.format + ")."); return cmap2; } function addSegment(t, code, glyphIndex) { t.segments.push({ end: code, start: code, delta: -(code - glyphIndex), offset: 0, glyphIndex }); } function addTerminatorSegment(t) { t.segments.push({ end: 65535, start: 65535, delta: 1, offset: 0 }); } function makeCmapTable(glyphs) { var isPlan0Only = true; var i; for (i = glyphs.length - 1; i > 0; i -= 1) if (glyphs.get(i).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 }, { name: "platformID", type: "USHORT", value: 3 }, { name: "encodingID", type: "USHORT", value: 1 }, { name: "offset", type: "ULONG", value: isPlan0Only ? 12 : 20 } ]; if (!isPlan0Only) cmapTable = cmapTable.concat([ { name: "cmap12PlatformID", type: "USHORT", value: 3 }, { name: "cmap12EncodingID", type: "USHORT", value: 10 }, { name: "cmap12Offset", type: "ULONG", value: 0 } ]); cmapTable = cmapTable.concat([ { 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 t = new table.Table("cmap", cmapTable); t.segments = []; for (i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); for (var j = 0; j < glyph.unicodes.length; j += 1) addSegment(t, glyph.unicodes[j], i); t.segments = t.segments.sort(function(a, b) { return a.start - b.start; }); } addTerminatorSegment(t); var segCount = t.segments.length; var segCountToRemove = 0; var endCounts = []; var startCounts = []; var idDeltas = []; var idRangeOffsets = []; var glyphIds = []; var cmap12Groups = []; for (i = 0; i < segCount; i += 1) { var segment = t.segments[i]; if (segment.end <= 65535 && segment.start <= 65535) { endCounts = endCounts.concat({ name: "end_" + i, type: "USHORT", value: segment.end }); startCounts = startCounts.concat({ name: "start_" + i, type: "USHORT", value: segment.start }); idDeltas = idDeltas.concat({ name: "idDelta_" + i, type: "SHORT", value: segment.delta }); idRangeOffsets = idRangeOffsets.concat({ name: "idRangeOffset_" + i, type: "USHORT", value: segment.offset }); if (segment.glyphId !== void 0) glyphIds = glyphIds.concat({ name: "glyph_" + i, type: "USHORT", value: segment.glyphId }); } else segCountToRemove += 1; if (!isPlan0Only && segment.glyphIndex !== void 0) { cmap12Groups = cmap12Groups.concat({ name: "cmap12Start_" + i, type: "ULONG", value: segment.start }); cmap12Groups = cmap12Groups.concat({ name: "cmap12End_" + i, type: "ULONG", value: segment.end }); cmap12Groups = cmap12Groups.concat({ name: "cmap12Glyph_" + i, type: "ULONG", value: segment.glyphIndex }); } } t.segCountX2 = (segCount - segCountToRemove) * 2; t.searchRange = Math.pow(2, Math.floor(Math.log(segCount - segCountToRemove) / Math.log(2))) * 2; t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2); t.rangeShift = t.segCountX2 - t.searchRange; t.fields = t.fields.concat(endCounts); t.fields.push({ name: "reservedPad", type: "USHORT", value: 0 }); t.fields = t.fields.concat(startCounts); t.fields = t.fields.concat(idDeltas); t.fields = t.fields.concat(idRangeOffsets); t.fields = t.fields.concat(glyphIds); t.cmap4Length = 14 + endCounts.length * 2 + 2 + startCounts.length * 2 + idDeltas.length * 2 + idRangeOffsets.length * 2 + glyphIds.length * 2; if (!isPlan0Only) { var cmap12Length = 16 + cmap12Groups.length * 4; t.cmap12Offset = 20 + t.cmap4Length; t.fields = t.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 } ]); t.fields = t.fields.concat(cmap12Groups); } return t; } 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(c) { var code = c.codePointAt(0); var glyphs = this.font.glyphs; if (glyphs) for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); for (var j = 0; j < glyph.unicodes.length; j += 1) if (glyph.unicodes[j] === code) return i; } return null; }; function CmapEncoding(cmap2) { this.cmap = cmap2; } CmapEncoding.prototype.charToGlyphIndex = function(c) { return this.cmap.glyphIndexMap[c.codePointAt(0)] || 0; }; function CffEncoding(encoding, charset) { this.encoding = encoding; this.charset = charset; } CffEncoding.prototype.charToGlyphIndex = function(s) { var code = s.codePointAt(0); var charName = this.encoding[code]; return this.charset.indexOf(charName); }; function GlyphNames(post2) { switch (post2.version) { case 1: this.names = standardNames.slice(); break; case 2: this.names = new Array(post2.numberOfGlyphs); for (var i = 0; i < post2.numberOfGlyphs; i++) if (post2.glyphNameIndex[i] < standardNames.length) this.names[i] = standardNames[post2.glyphNameIndex[i]]; else this.names[i] = post2.names[post2.glyphNameIndex[i] - standardNames.length]; break; case 2.5: this.names = new Array(post2.numberOfGlyphs); for (var i$1 = 0; i$1 < post2.numberOfGlyphs; i$1++) this.names[i$1] = standardNames[i$1 + post2.glyphNameIndex[i$1]]; break; case 3: this.names = []; break; default: this.names = []; break; } } GlyphNames.prototype.nameToGlyphIndex = function(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 i = 0; i < charCodes.length; i += 1) { var c = charCodes[i]; var glyphIndex = glyphIndexMap[c]; glyph = font.glyphs.get(glyphIndex); glyph.addUnicode(parseInt(c)); } for (var i$1 = 0; i$1 < font.glyphs.length; i$1 += 1) { glyph = font.glyphs.get(i$1); if (font.cffEncoding) if (font.isCIDFont) glyph.name = "gid" + i$1; else glyph.name = font.cffEncoding.charset[i$1]; else if (font.glyphNames.names) glyph.name = font.glyphNames.glyphIndexToName(i$1); } } function addGlyphNamesToUnicodeMap(font) { font._IndexToUnicodeMap = {}; var glyphIndexMap = font.tables.cmap.glyphIndexMap; var charCodes = Object.keys(glyphIndexMap); for (var i = 0; i < charCodes.length; i += 1) { var c = charCodes[i]; var glyphIndex = glyphIndexMap[c]; if (font._IndexToUnicodeMap[glyphIndex] === void 0) font._IndexToUnicodeMap[glyphIndex] = { unicodes: [parseInt(c)] }; else font._IndexToUnicodeMap[glyphIndex].unicodes.push(parseInt(c)); } } 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 Path(); return { configurable: true, get: function() { if (typeof _path === "function") _path = _path(); return _path; }, set: function(p) { _path = p; } }; } function Glyph(options) { this.bindConstructorValues(options); } Glyph.prototype.bindConstructorValues = function(options) { this.index = options.index || 0; this.name = options.name || null; this.unicode = options.unicode || void 0; this.unicodes = options.unicodes || options.unicode !== void 0 ? [options.unicode] : []; if ("xMin" in options) this.xMin = options.xMin; if ("yMin" in options) this.yMin = options.yMin; if ("xMax" in options) this.xMax = options.xMax; if ("yMax" in options) this.yMax = options.yMax; if ("advanceWidth" in options) this.advanceWidth = options.advanceWidth; Object.defineProperty(this, "path", getPathDefinition(this, options.path)); }; Glyph.prototype.addUnicode = function(unicode) { if (this.unicodes.length === 0) this.unicode = unicode; this.unicodes.push(unicode); }; Glyph.prototype.getBoundingBox = function() { return this.path.getBoundingBox(); }; Glyph.prototype.getPath = function(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 scale = 1 / (this.path.unitsPerEm || 1e3) * fontSize; if (xScale === void 0) xScale = scale; if (yScale === void 0) yScale = scale; } var p = new Path(); for (var i = 0; i < commands.length; i += 1) { var cmd = commands[i]; if (cmd.type === "M") p.moveTo(x + cmd.x * xScale, y + -cmd.y * yScale); else if (cmd.type === "L") p.lineTo(x + cmd.x * xScale, y + -cmd.y * yScale); else if (cmd.type === "Q") p.quadraticCurveTo(x + cmd.x1 * xScale, y + -cmd.y1 * yScale, x + cmd.x * xScale, y + -cmd.y * yScale); else if (cmd.type === "C") p.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") p.closePath(); } return p; }; Glyph.prototype.getContours = function() { if (this.points === void 0) return []; var contours = []; var currentContour = []; for (var i = 0; i < this.points.length; i += 1) { var pt = this.points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } check.argument(currentContour.length === 0, "There are still points left in the current contour."); return contours; }; Glyph.prototype.getMetrics = function() { var commands = this.path.commands; var xCoords = []; var yCoords = []; for (var i = 0; i < commands.length; i += 1) { var cmd = commands[i]; if (cmd.type !== "Z") { xCoords.push(cmd.x); yCoords.push(cmd.y); } if (cmd.type === "Q" || cmd.type === "C") { xCoords.push(cmd.x1); yCoords.push(cmd.y1); } if (cmd.type === "C") { xCoords.push(cmd.x2); yCoords.push(cmd.y2); } } var metrics = { xMin: Math.min.apply(null, xCoords), yMin: Math.min.apply(null, yCoords), xMax: Math.max.apply(null, xCoords), yMax: Math.max.apply(null, yCoords), leftSideBearing: this.leftSideBearing }; if (!isFinite(metrics.xMin)) metrics.xMin = 0; if (!isFinite(metrics.xMax)) metrics.xMax = this.advanceWidth; if (!isFinite(metrics.yMin)) metrics.yMin = 0; if (!isFinite(metrics.yMax)) metrics.yMax = 0; metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); return metrics; }; Glyph.prototype.draw = function(ctx, x, y, fontSize, options) { this.getPath(x, y, fontSize, options).draw(ctx); }; Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) { function drawCircles(l, x2, y2, scale2) { ctx.beginPath(); for (var j = 0; j < l.length; j += 1) { ctx.moveTo(x2 + l[j].x * scale2, y2 + l[j].y * scale2); ctx.arc(x2 + l[j].x * scale2, y2 + l[j].y * scale2, 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 scale = 1 / this.path.unitsPerEm * fontSize; var blueCircles = []; var redCircles = []; var path = this.path; for (var i = 0; i < path.commands.length; i += 1) { var cmd = path.commands[i]; if (cmd.x !== void 0) blueCircles.push({ x: cmd.x, y: -cmd.y }); if (cmd.x1 !== void 0) redCircles.push({ x: cmd.x1, y: -cmd.y1 }); if (cmd.x2 !== void 0) redCircles.push({ x: cmd.x2, y: -cmd.y2 }); } ctx.fillStyle = "blue"; drawCircles(blueCircles, x, y, scale); ctx.fillStyle = "red"; drawCircles(redCircles, x, y, scale); }; Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) { var scale; x = x !== void 0 ? x : 0; y = y !== void 0 ? y : 0; fontSize = fontSize !== void 0 ? fontSize : 24; scale = 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 * scale, -1e4, x + xMin * scale, 1e4); draw.line(ctx, x + xMax * scale, -1e4, x + xMax * scale, 1e4); draw.line(ctx, -1e4, y + -yMin * scale, 1e4, y + -yMin * scale); draw.line(ctx, -1e4, y + -yMax * scale, 1e4, y + -yMax * scale); ctx.strokeStyle = "green"; draw.line(ctx, x + advanceWidth * scale, -1e4, x + advanceWidth * scale, 1e4); }; function defineDependentProperty(glyph, externalName, internalName) { Object.defineProperty(glyph, externalName, { get: function() { glyph.path; return glyph[internalName]; }, set: function(newValue) { glyph[internalName] = newValue; }, enumerable: true, configurable: true }); } function GlyphSet(font, glyphs) { this.font = font; this.glyphs = {}; if (Array.isArray(glyphs)) for (var i = 0; i < glyphs.length; i++) { var glyph = glyphs[i]; glyph.path.unitsPerEm = font.unitsPerEm; this.glyphs[i] = glyph; } this.length = glyphs && glyphs.length || 0; } GlyphSet.prototype.get = function(index) { if (this.glyphs[index] === void 0) { this.font._push(index); if (typeof this.glyphs[index] === "function") this.glyphs[index] = this.glyphs[index](); var glyph = this.glyphs[index]; var unicodeObj = this.font._IndexToUnicodeMap[index]; 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" + index; else glyph.name = this.font.cffEncoding.charset[index]; else if (this.font.glyphNames.names) glyph.name = this.font.glyphNames.glyphIndexToName(index); this.glyphs[index].advanceWidth = this.font._hmtxTableData[index].advanceWidth; this.glyphs[index].leftSideBearing = this.font._hmtxTableData[index].leftSideBearing; } else if (typeof this.glyphs[index] === "function") this.glyphs[index] = this.glyphs[index](); return this.glyphs[index]; }; GlyphSet.prototype.push = function(index, loader) { this.glyphs[index] = loader; this.length++; }; function glyphLoader(font, index) { return new Glyph({ index, font }); } function ttfGlyphLoader(font, index, parseGlyph2, data, position, buildPath2) { return function() { var glyph = new Glyph({ index, font }); glyph.path = function() { parseGlyph2(glyph, data, position); 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, index, parseCFFCharstring2, charstring) { return function() { var glyph = new Glyph({ index, 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(a, b) { if (a === b) return true; else if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; for (var i = 0; i < a.length; i += 1) if (!equals(a[i], b[i])) return false; return true; } else return false; } function calcCFFSubroutineBias(subrs) { var bias; if (subrs.length < 1240) bias = 107; else if (subrs.length < 33900) bias = 1131; else bias = 32768; return bias; } function parseCFFIndex(data, start, conversionFn) { var offsets = []; var objects = []; var count = parse.getCard16(data, start); var objectOffset; var endOffset; if (count !== 0) { var offsetSize = parse.getByte(data, start + 2); objectOffset = start + (count + 1) * offsetSize + 2; var pos = start + 3; for (var i = 0; i < count + 1; i += 1) { offsets.push(parse.getOffset(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 = parse.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 = parse.getCard16(data, start); var objectOffset; var endOffset; if (count !== 0) { var offsetSize = parse.getByte(data, start + 2); objectOffset = start + (count + 1) * offsetSize + 2; var pos = start + 3; for (var i = 0; i < count + 1; i += 1) { offsets.push(parse.getOffset(data, pos, offsetSize)); pos += offsetSize; } endOffset = objectOffset + offsets[count]; } else endOffset = start + 2; return { offsets, startOffset: start, endOffset }; } function getCffIndexObject(i, offsets, data, start, conversionFn) { var count = parse.getCard16(data, start); var objectOffset = 0; if (count !== 0) { var offsetSize = parse.getByte(data, start + 2); objectOffset = start + (count + 1) * offsetSize + 2; } var value = parse.getBytes(data, objectOffset + offsets[i], objectOffset + offsets[i + 1]); if (conversionFn) value = conversionFn(value); return value; } function parseFloatOperand(parser) { var s = ""; var eof = 15; var lookup = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "E", "E-", null, "-" ]; while (true) { var b = parser.parseByte(); var n1 = b >> 4; var n2 = b & 15; if (n1 === eof) break; s += lookup[n1]; if (n2 === eof) break; s += lookup[n2]; } return parseFloat(s); } function parseOperand(parser, b0) { var b1; var b2; var b3; var b4; if (b0 === 28) { b1 = parser.parseByte(); b2 = parser.parseByte(); return b1 << 8 | b2; } if (b0 === 29) { b1 = parser.parseByte(); b2 = parser.parseByte(); b3 = parser.parseByte(); b4 = parser.parseByte(); return b1 << 24 | b2 << 16 | b3 << 8 | b4; } if (b0 === 30) return parseFloatOperand(parser); if (b0 >= 32 && b0 <= 246) return b0 - 139; if (b0 >= 247 && b0 <= 250) { b1 = parser.parseByte(); return (b0 - 247) * 256 + b1 + 108; } if (b0 >= 251 && b0 <= 254) { b1 = parser.parseByte(); return -(b0 - 251) * 256 - b1 - 108; } throw new Error("Invalid b0 " + b0); } function entriesToObject(entries) { var o = {}; for (var i = 0; i < entries.length; i += 1) { var key = entries[i][0]; var values = entries[i][1]; var value = void 0; if (values.length === 1) value = values[0]; else value = values; if (o.hasOwnProperty(key) && !isNaN(o[key])) throw new Error("Object " + o + " already has key " + key); o[key] = value; } return o; } function parseCFFDict(data, start, size) { start = start !== void 0 ? start : 0; var parser = new parse.Parser(data, start); var entries = []; var operands = []; size = size !== void 0 ? size : data.length; while (parser.relativeOffset < size) { 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, index) { if (index <= 390) index = cffStandardStrings[index]; else index = strings[index - 391]; return index; } function interpretDict(dict, meta2, strings) { var newDict = {}; var value; for (var i = 0; i < meta2.length; i += 1) { var m = meta2[i]; 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 = parse.getCard8(data, start); header.formatMinor = parse.getCard8(data, start + 1); header.size = parse.getCard8(data, start + 2); header.offsetSize = parse.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: [ .001, 0, 0, .001, 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) { return interpretDict(parseCFFDict(data, 0, data.byteLength), TOP_DICT_META, strings); } function parseCFFPrivateDict(data, start, size, strings) { return interpretDict(parseCFFDict(data, start, size), PRIVATE_DICT_META, strings); } function gatherCFFTopDicts(data, start, cffIndex, strings) { var topDictArray = []; for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) { var topDict = parseCFFTopDict(new DataView(new Uint8Array(cffIndex[iTopDict]).buffer), 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) { topDict._subrs = parseCFFIndex(data, privateOffset + privateDict.subrs + start).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 parse.Parser(data, start); nGlyphs -= 1; var charset = [".notdef"]; var format = parser.parseCard8(); if (format === 0) for (var i = 0; i < nGlyphs; i += 1) { sid = parser.parseSID(); charset.push(getCFFString(strings, sid)); } else if (format === 1) while (charset.length <= nGlyphs) { sid = parser.parseSID(); count = parser.parseCard8(); for (var i$1 = 0; i$1 <= count; i$1 += 1) { charset.push(getCFFString(strings, sid)); sid += 1; } } else if (format === 2) while (charset.length <= nGlyphs) { sid = parser.parseSID(); count = parser.parseCard16(); for (var i$2 = 0; i$2 <= count; i$2 += 1) { charset.push(getCFFString(strings, sid)); sid += 1; } } else throw new Error("Unknown charset format " + format); return charset; } function parseCFFEncoding(data, start, charset) { var code; var enc = {}; var parser = new parse.Parser(data, start); var format = parser.parseCard8(); if (format === 0) { var nCodes = parser.parseCard8(); for (var i = 0; i < nCodes; i += 1) { code = parser.parseCard8(); enc[code] = i; } } else if (format === 1) { var nRanges = parser.parseCard8(); code = 1; for (var i$1 = 0; i$1 < nRanges; i$1 += 1) { var first = parser.parseCard8(); var nLeft = parser.parseCard8(); for (var j = first; j <= first + 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 p = new Path(); 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) p.closePath(); p.moveTo(x2, y2); open = true; } function parseStems() { if (stack.length % 2 !== 0 && !haveWidth) width = stack.shift() + nominalWidthX; nStems += stack.length >> 1; stack.length = 0; haveWidth = true; } function parse2(code2) { var b1; var b2; var b3; var b4; var codeIndex; var subrCode; var jpx; var jpy; var c3x; var c3y; var c4x; var c4y; var i = 0; while (i < code2.length) { var v = code2[i]; i += 1; switch (v) { case 1: parseStems(); break; case 3: parseStems(); break; case 4: if (stack.length > 1 && !haveWidth) { 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(); p.lineTo(x, y); } break; case 6: while (stack.length > 0) { x += stack.shift(); p.lineTo(x, y); if (stack.length === 0) break; y += stack.shift(); p.lineTo(x, y); } break; case 7: while (stack.length > 0) { y += stack.shift(); p.lineTo(x, y); if (stack.length === 0) break; x += stack.shift(); p.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(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 10: codeIndex = stack.pop() + subrsBias; subrCode = subrs[codeIndex]; if (subrCode) parse2(subrCode); break; case 11: return; case 12: v = code2[i]; i += 1; switch (v) { case 35: c1x = 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(); p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.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(); p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.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(); p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.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(); p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; default: console.log("Glyph " + glyph.index + ": unknown operator 1200" + v); stack.length = 0; } break; case 14: if (stack.length > 0 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } if (open) { p.closePath(); open = false; } break; case 18: parseStems(); break; case 19: case 20: parseStems(); i += 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(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } x += stack.shift(); y += stack.shift(); p.lineTo(x, y); break; case 25: while (stack.length > 6) { x += stack.shift(); y += stack.shift(); p.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(); p.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(); p.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; p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 28: b1 = code2[i]; b2 = code2[i + 1]; stack.push((b1 << 24 | b2 << 16) >> 16); i += 2; break; case 29: codeIndex = stack.pop() + font.gsubrsBias; subrCode = font.gsubrs[codeIndex]; if (subrCode) parse2(subrCode); break; case 30: while (stack.length > 0) { c1x = 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); p.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); p.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); p.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); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; default: if (v < 32) console.log("Glyph " + glyph.index + ": unknown operator " + v); else if (v < 247) stack.push(v - 139); else if (v < 251) { b1 = code2[i]; i += 1; stack.push((v - 247) * 256 + b1 + 108); } else if (v < 255) { b1 = code2[i]; i += 1; stack.push(-(v - 251) * 256 - b1 - 108); } else { b1 = code2[i]; b2 = code2[i + 1]; b3 = code2[i + 2]; b4 = code2[i + 3]; i += 4; stack.push((b1 << 24 | b2 << 16 | b3 << 8 | b4) / 65536); } } } } parse2(code); glyph.advanceWidth = width; return p; } function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) { var fdSelect = []; var fdIndex; var parser = new parse.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 first = parser.parseCard16(); if (first !== 0) throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID " + first); 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 (; first < next; first++) fdSelect.push(fdIndex); first = 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 topDictIndex = parseCFFIndex(data, parseCFFIndex(data, parseCFFHeader(data, start).endOffset, parse.bytesToString).endOffset); var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString); font.gsubrs = parseCFFIndex(data, stringIndex.endOffset).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 fdArray = gatherCFFTopDicts(data, start, parseCFFIndex(data, fdArrayOffset).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) { font.subrs = parseCFFIndex(data, privateDictOffset + privateDict.subrs).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(i2) { var charString2 = getCffIndexObject(i2, charStringsIndex.offsets, data, start + topDict.charStrings); font.glyphs.push(i2, glyphset.cffGlyphLoader(font, i2, parseCFFCharstring, charString2)); }; else for (var i = 0; i < font.nGlyphs; i += 1) { var charString = charStringsIndex.objects[i]; font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); } } function encodeString(s, strings) { var sid; var i = cffStandardStrings.indexOf(s); if (i >= 0) sid = i; i = strings.indexOf(s); if (i >= 0) sid = i + cffStandardStrings.length; else { sid = cffStandardStrings.length + strings.length; strings.push(s); } return sid; } function makeHeader() { return new table.Record("Header", [ { name: "major", type: "Card8", value: 1 }, { name: "minor", type: "Card8", value: 0 }, { name: "hdrSize", type: "Card8", value: 4 }, { name: "major", type: "Card8", value: 1 } ]); } function makeNameIndex(fontNames) { var t = new table.Record("Name INDEX", [{ name: "names", type: "INDEX", value: [] }]); t.names = []; for (var i = 0; i < fontNames.length; i += 1) t.names.push({ name: "name_" + i, type: "NAME", value: fontNames[i] }); return t; } function makeDict(meta2, attrs, strings) { var m = {}; for (var i = 0; i < meta2.length; i += 1) { var entry = meta2[i]; 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 t = new table.Record("Top DICT", [{ name: "dict", type: "DICT", value: {} }]); t.dict = makeDict(TOP_DICT_META, attrs, strings); return t; } function makeTopDictIndex(topDict) { var t = new table.Record("Top DICT INDEX", [{ name: "topDicts", type: "INDEX", value: [] }]); t.topDicts = [{ name: "topDict_0", type: "TABLE", value: topDict }]; return t; } function makeStringIndex(strings) { var t = new table.Record("String INDEX", [{ name: "strings", type: "INDEX", value: [] }]); t.strings = []; for (var i = 0; i < strings.length; i += 1) t.strings.push({ name: "string_" + i, type: "STRING", value: strings[i] }); return t; } function makeGlobalSubrIndex() { return new table.Record("Global Subr INDEX", [{ name: "subrs", type: "INDEX", value: [] }]); } function makeCharsets(glyphNames, strings) { var t = new table.Record("Charsets", [{ name: "format", type: "Card8", value: 0 }]); for (var i = 0; i < glyphNames.length; i += 1) { var glyphName = glyphNames[i]; var glyphSID = encodeString(glyphName, strings); t.fields.push({ name: "glyph_" + i, type: "SID", value: glyphSID }); } return t; } 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 i = 0; i < path.commands.length; i += 1) { var dx = void 0; var dy = void 0; var cmd = path.commands[i]; if (cmd.type === "Q") { var _13 = 1 / 3; var _23 = 2 / 3; cmd = { type: "C", x: cmd.x, y: cmd.y, x1: Math.round(_13 * 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 t = new table.Record("CharStrings INDEX", [{ name: "charStrings", type: "INDEX", value: [] }]); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); var ops = glyphToOps(glyph); t.charStrings.push({ name: glyph.name, type: "CHARSTRING", value: ops }); } return t; } function makePrivateDict(attrs, strings) { var t = new table.Record("Private DICT", [{ name: "dict", type: "DICT", value: {} }]); t.dict = makeDict(PRIVATE_DICT_META, attrs, strings); return t; } function makeCFFTable(glyphs, options) { var t = new table.Table("CFF ", [ { name: "header", type: "RECORD" }, { name: "nameIndex", type: "RECORD" }, { name: "topDictIndex", type: "RECORD" }, { name: "stringIndex", type: "RECORD" }, { name: "globalSubrIndex", type: "RECORD" }, { name: "charsets", type: "RECORD" }, { name: "charStringsIndex", type: "RECORD" }, { name: "privateDict", type: "RECORD" } ]); var fontScale = 1 / options.unitsPerEm; var attrs = { version: options.version, fullName: options.fullName, familyName: options.familyName, weight: options.weightName, fontBBox: options.fontBBox || [ 0, 0, 0, 0 ], fontMatrix: [ fontScale, 0, 0, fontScale, 0, 0 ], charset: 999, encoding: 0, charStrings: 999, private: [0, 999] }; var privateAttrs = {}; var glyphNames = []; var glyph; for (var i = 1; i < glyphs.length; i += 1) { glyph = glyphs.get(i); glyphNames.push(glyph.name); } var strings = []; t.header = makeHeader(); t.nameIndex = makeNameIndex([options.postScriptName]); var topDict = makeTopDict(attrs, strings); t.topDictIndex = makeTopDictIndex(topDict); t.globalSubrIndex = makeGlobalSubrIndex(); t.charsets = makeCharsets(glyphNames, strings); t.charStringsIndex = makeCharStringsIndex(glyphs); t.privateDict = makePrivateDict(privateAttrs, strings); t.stringIndex = makeStringIndex(strings); attrs.charset = t.header.sizeOf() + t.nameIndex.sizeOf() + t.topDictIndex.sizeOf() + t.stringIndex.sizeOf() + t.globalSubrIndex.sizeOf(); attrs.encoding = 0; attrs.charStrings = attrs.charset + t.charsets.sizeOf(); attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf(); topDict = makeTopDict(attrs, strings); t.topDictIndex = makeTopDictIndex(topDict); return t; } var cff = { parse: parseCFFTable, make: makeCFFTable }; function parseHeadTable(data, start) { var head2 = {}; var p = new parse.Parser(data, start); head2.version = p.parseVersion(); head2.fontRevision = Math.round(p.parseFixed() * 1e3) / 1e3; head2.checkSumAdjustment = p.parseULong(); head2.magicNumber = p.parseULong(); check.argument(head2.magicNumber === 1594834165, "Font header has wrong magic number."); head2.flags = p.parseUShort(); head2.unitsPerEm = p.parseUShort(); head2.created = p.parseLongDateTime(); head2.modified = p.parseLongDateTime(); head2.xMin = p.parseShort(); head2.yMin = p.parseShort(); head2.xMax = p.parseShort(); head2.yMax = p.parseShort(); head2.macStyle = p.parseUShort(); head2.lowestRecPPEM = p.parseUShort(); head2.fontDirectionHint = p.parseShort(); head2.indexToLocFormat = p.parseShort(); head2.glyphDataFormat = p.parseShort(); return head2; } function makeHeadTable(options) { var timestamp = Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3) + 2082844800; var createdTimestamp = timestamp; if (options.createdTimestamp) createdTimestamp = options.createdTimestamp + 2082844800; return new table.Table("head", [ { name: "version", type: "FIXED", value: 65536 }, { name: "fontRevision", type: "FIXED", value: 65536 }, { name: "checkSumAdjustment", type: "ULONG", value: 0 }, { name: "magicNumber", type: "ULONG", value: 1594834165 }, { name: "flags", type: "USHORT", value: 0 }, { name: "unitsPerEm", type: "USHORT", value: 1e3 }, { name: "created", type: "LONGDATETIME", value: createdTimestamp }, { name: "modified", type: "LONGDATETIME", value: timestamp }, { name: "xMin", type: "SHORT", value: 0 }, { name: "yMin", type: "SHORT", value: 0 }, { name: "xMax", type: "SHORT", value: 0 }, { name: "yMax", type: "SHORT", value: 0 }, { name: "macStyle", type: "USHORT", value: 0 }, { name: "lowestRecPPEM", type: "USHORT", value: 0 }, { name: "fontDirectionHint", type: "SHORT", value: 2 }, { name: "indexToLocFormat", type: "SHORT", value: 0 }, { name: "glyphDataFormat", type: "SHORT", value: 0 } ], options); } var head = { parse: parseHeadTable, make: makeHeadTable }; function parseHheaTable(data, start) { var hhea2 = {}; var p = new parse.Parser(data, start); hhea2.version = p.parseVersion(); hhea2.ascender = p.parseShort(); hhea2.descender = p.parseShort(); hhea2.lineGap = p.parseShort(); hhea2.advanceWidthMax = p.parseUShort(); hhea2.minLeftSideBearing = p.parseShort(); hhea2.minRightSideBearing = p.parseShort(); hhea2.xMaxExtent = p.parseShort(); hhea2.caretSlopeRise = p.parseShort(); hhea2.caretSlopeRun = p.parseShort(); hhea2.caretOffset = p.parseShort(); p.relativeOffset += 8; hhea2.metricDataFormat = p.parseShort(); hhea2.numberOfHMetrics = p.parseUShort(); return hhea2; } function makeHheaTable(options) { return new table.Table("hhea", [ { name: "version", type: "FIXED", value: 65536 }, { name: "ascender", type: "FWORD", value: 0 }, { name: "descender", type: "FWORD", value: 0 }, { name: "lineGap", type: "FWORD", value: 0 }, { name: "advanceWidthMax", type: "UFWORD", value: 0 }, { name: "minLeftSideBearing", type: "FWORD", value: 0 }, { name: "minRightSideBearing", type: "FWORD", value: 0 }, { name: "xMaxExtent", type: "FWORD", value: 0 }, { name: "caretSlopeRise", type: "SHORT", value: 1 }, { name: "caretSlopeRun", type: "SHORT", value: 0 }, { name: "caretOffset", type: "SHORT", value: 0 }, { name: "reserved1", type: "SHORT", value: 0 }, { name: "reserved2", type: "SHORT", value: 0 }, { name: "reserved3", type: "SHORT", value: 0 }, { name: "reserved4", type: "SHORT", value: 0 }, { name: "metricDataFormat", type: "SHORT", value: 0 }, { name: "numberOfHMetrics", type: "USHORT", value: 0 } ], options); } var hhea = { parse: parseHheaTable, make: makeHheaTable }; function parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs) { var advanceWidth; var leftSideBearing; var p = new parse.Parser(data, start); for (var i = 0; i < numGlyphs; i += 1) { if (i < numMetrics) { advanceWidth = p.parseUShort(); leftSideBearing = p.parseShort(); } var glyph = glyphs.get(i); glyph.advanceWidth = advanceWidth; glyph.leftSideBearing = leftSideBearing; } } function parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs) { font._hmtxTableData = {}; var advanceWidth; var leftSideBearing; var p = new parse.Parser(data, start); for (var i = 0; i < numGlyphs; i += 1) { if (i < numMetrics) { advanceWidth = p.parseUShort(); leftSideBearing = p.parseShort(); } font._hmtxTableData[i] = { advanceWidth, leftSideBearing }; } } function parseHmtxTable(font, 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 t = new table.Table("hmtx", []); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); var advanceWidth = glyph.advanceWidth || 0; var leftSideBearing = glyph.leftSideBearing || 0; t.fields.push({ name: "advanceWidth_" + i, type: "USHORT", value: advanceWidth }); t.fields.push({ name: "leftSideBearing_" + i, type: "SHORT", value: leftSideBearing }); } return t; } var hmtx = { parse: parseHmtxTable, make: makeHmtxTable }; function makeLtagTable(tags) { var result = new table.Table("ltag", [ { name: "version", type: "ULONG", value: 1 }, { name: "flags", type: "ULONG", value: 0 }, { name: "numTags", type: "ULONG", value: tags.length } ]); var stringPool = ""; var stringPoolOffset = 12 + tags.length * 4; for (var i = 0; i < tags.length; ++i) { var pos = stringPool.indexOf(tags[i]); if (pos < 0) { pos = stringPool.length; stringPool += tags[i]; } result.fields.push({ name: "offset " + i, type: "USHORT", value: stringPoolOffset + pos }); result.fields.push({ name: "length " + i, type: "USHORT", value: tags[i].length }); } result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool }); return result; } function parseLtagTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 1, "Unsupported ltag table version."); p.skip("uLong", 1); var numTags = p.parseULong(); var tags = []; for (var i = 0; i < numTags; i++) { var tag = ""; var offset = start + p.parseUShort(); var length = p.parseUShort(); for (var j = offset; j < offset + length; ++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 p = new parse.Parser(data, start); maxp2.version = p.parseVersion(); maxp2.numGlyphs = p.parseUShort(); if (maxp2.version === 1) { maxp2.maxPoints = p.parseUShort(); maxp2.maxContours = p.parseUShort(); maxp2.maxCompositePoints = p.parseUShort(); maxp2.maxCompositeContours = p.parseUShort(); maxp2.maxZones = p.parseUShort(); maxp2.maxTwilightPoints = p.parseUShort(); maxp2.maxStorage = p.parseUShort(); maxp2.maxFunctionDefs = p.parseUShort(); maxp2.maxInstructionDefs = p.parseUShort(); maxp2.maxStackElements = p.parseUShort(); maxp2.maxSizeOfInstructions = p.parseUShort(); maxp2.maxComponentElements = p.parseUShort(); maxp2.maxComponentDepth = p.parseUShort(); } return maxp2; } function makeMaxpTable(numGlyphs) { return new table.Table("maxp", [{ name: "version", type: "FIXED", value: 20480 }, { name: "numGlyphs", type: "USHORT", value: numGlyphs }]); } var maxp = { parse: parseMaxpTable, make: makeMaxpTable }; var nameTableNames = [ "copyright", "fontFamily", "fontSubfamily", "uniqueID", "fullName", "version", "postScriptName", "trademark", "manufacturer", "designer", "description", "manufacturerURL", "designerURL", "license", "licenseURL", "reserved", "preferredFamily", "preferredSubfamily", "compatibleFullName", "sampleText", "postScriptFindFontName", "wwsFamily", "wwsSubfamily" ]; 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, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 5, 11: 1, 12: 4, 13: 0, 14: 6, 15: 0, 16: 0, 17: 0, 18: 0, 19: 2, 20: 4, 21: 9, 22: 21, 23: 3, 24: 29, 25: 29, 26: 29, 27: 29, 28: 29, 29: 0, 30: 0, 31: 4, 32: 7, 33: 25, 34: 0, 35: 0, 36: 0, 37: 0, 38: 29, 39: 29, 40: 0, 41: 5, 42: 7, 43: 7, 44: 7, 45: 7, 46: 7, 47: 7, 48: 7, 49: 7, 50: 4, 51: 24, 52: 23, 53: 7, 54: 7, 55: 7, 56: 7, 57: 27, 58: 7, 59: 4, 60: 4, 61: 4, 62: 4, 63: 26, 64: 9, 65: 9, 66: 9, 67: 13, 68: 13, 69: 11, 70: 10, 71: 12, 72: 17, 73: 16, 74: 14, 75: 15, 76: 18, 77: 19, 78: 20, 79: 22, 80: 30, 81: 0, 82: 0, 83: 0, 84: 4, 85: 28, 86: 28, 87: 28, 88: 0, 89: 0, 90: 0, 91: 0, 92: 0, 93: 0, 94: 0, 128: 0, 129: 0, 130: 0, 131: 0, 132: 0, 133: 0, 134: 0, 135: 7, 136: 4, 137: 26, 138: 0, 139: 0, 140: 0, 141: 0, 142: 0, 143: 28, 144: 0, 145: 0, 146: 0, 147: 0, 148: 6, 149: 0, 150: 0, 151: 0 }; 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", 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]; } } var utf16 = "utf-16"; var macScriptEncodings = { 0: "macintosh", 1: "x-mac-japanese", 2: "x-mac-chinesetrad", 3: "x-mac-korean", 6: "x-mac-greek", 7: "x-mac-cyrillic", 9: "x-mac-devanagai", 10: "x-mac-gurmukhi", 11: "x-mac-gujarati", 12: "x-mac-oriya", 13: "x-mac-bengali", 14: "x-mac-tamil", 15: "x-mac-telugu", 16: "x-mac-kannada", 17: "x-mac-malayalam", 18: "x-mac-sinhalese", 19: "x-mac-burmese", 20: "x-mac-khmer", 21: "x-mac-thai", 22: "x-mac-lao", 23: "x-mac-georgian", 24: "x-mac-armenian", 25: "x-mac-chinesesimp", 26: "x-mac-tibetan", 27: "x-mac-mongolian", 28: "x-mac-ethiopic", 29: "x-mac-ce", 30: "x-mac-vietnamese", 31: "x-mac-extarabic" }; var macLanguageEncodings = { 15: "x-mac-icelandic", 17: "x-mac-turkish", 18: "x-mac-croatian", 24: "x-mac-ce", 25: "x-mac-ce", 26: "x-mac-ce", 27: "x-mac-ce", 28: "x-mac-ce", 30: "x-mac-icelandic", 37: "x-mac-romanian", 38: "x-mac-ce", 39: "x-mac-ce", 40: "x-mac-ce", 143: "x-mac-inuit", 146: "x-mac-gaelic" }; 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; } } function parseNameTable(data, start, ltag2) { var name = {}; var p = new parse.Parser(data, start); var format = p.parseUShort(); var count = p.parseUShort(); var stringOffset = p.offset + p.parseUShort(); for (var i = 0; i < count; i++) { var platformID = p.parseUShort(); var encodingID = p.parseUShort(); var languageID = p.parseUShort(); var nameID = p.parseUShort(); var property = nameTableNames[nameID] || nameID; var byteLength = p.parseUShort(); var offset = p.parseUShort(); var language = getLanguageCode(platformID, languageID, ltag2); var encoding = getEncoding(platformID, encodingID, languageID); if (encoding !== void 0 && language !== void 0) { var 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) p.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, length, 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: length }, { 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(s, pool) { var offset = findSubArray(s, pool); if (offset < 0) { offset = pool.length; var i = 0; var len = s.length; for (; i < len; ++i) pool.push(s[i]); } return offset; } function makeNameTable(names, ltag2) { var nameID; var nameIDs = []; var namesWithNumericKeys = {}; var nameTableIds = reverseDict(nameTableNames); for (var 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 i = 0; i < nameIDs.length; i++) { nameID = nameIDs[i]; 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(a, b) { return a.platformID - b.platformID || a.encodingID - b.encodingID || a.languageID - b.languageID || a.nameID - b.nameID; }); var t = new table.Table("name", [ { name: "format", type: "USHORT", value: 0 }, { name: "count", type: "USHORT", value: nameRecords.length }, { name: "stringOffset", type: "USHORT", value: 6 + nameRecords.length * 12 } ]); for (var r = 0; r < nameRecords.length; r++) t.fields.push({ name: "record_" + r, type: "RECORD", value: nameRecords[r] }); t.fields.push({ name: "strings", type: "LITERAL", value: stringPool }); return t; } var _name = { parse: parseNameTable, make: makeNameTable }; var unicodeRanges = [ { begin: 0, end: 127 }, { begin: 128, end: 255 }, { begin: 256, end: 383 }, { begin: 384, end: 591 }, { begin: 592, end: 687 }, { begin: 688, end: 767 }, { begin: 768, end: 879 }, { begin: 880, end: 1023 }, { begin: 11392, end: 11519 }, { begin: 1024, end: 1279 }, { begin: 1328, end: 1423 }, { begin: 1424, end: 1535 }, { begin: 42240, end: 42559 }, { begin: 1536, end: 1791 }, { begin: 1984, end: 2047 }, { begin: 2304, end: 2431 }, { begin: 2432, end: 2559 }, { begin: 2560, end: 2687 }, { begin: 2688, end: 2815 }, { begin: 2816, end: 2943 }, { begin: 2944, end: 3071 }, { begin: 3072, end: 3199 }, { begin: 3200, end: 3327 }, { begin: 3328, end: 3455 }, { begin: 3584, end: 3711 }, { begin: 3712, end: 3839 }, { begin: 4256, end: 4351 }, { begin: 6912, end: 7039 }, { begin: 4352, end: 4607 }, { begin: 7680, end: 7935 }, { begin: 7936, end: 8191 }, { begin: 8192, end: 8303 }, { begin: 8304, end: 8351 }, { begin: 8352, end: 8399 }, { begin: 8400, end: 8447 }, { begin: 8448, end: 8527 }, { begin: 8528, end: 8591 }, { begin: 8592, end: 8703 }, { begin: 8704, end: 8959 }, { begin: 8960, end: 9215 }, { begin: 9216, end: 9279 }, { begin: 9280, end: 9311 }, { begin: 9312, end: 9471 }, { begin: 9472, end: 9599 }, { begin: 9600, end: 9631 }, { begin: 9632, end: 9727 }, { begin: 9728, end: 9983 }, { begin: 9984, end: 10175 }, { begin: 12288, end: 12351 }, { begin: 12352, end: 12447 }, { begin: 12448, end: 12543 }, { begin: 12544, end: 12591 }, { begin: 12592, end: 12687 }, { begin: 43072, end: 43135 }, { begin: 12800, end: 13055 }, { begin: 13056, end: 13311 }, { begin: 44032, end: 55215 }, { begin: 55296, end: 57343 }, { begin: 67840, end: 67871 }, { begin: 19968, end: 40959 }, { begin: 57344, end: 63743 }, { begin: 12736, end: 12783 }, { begin: 64256, end: 64335 }, { begin: 64336, end: 65023 }, { begin: 65056, end: 65071 }, { begin: 65040, end: 65055 }, { begin: 65104, end: 65135 }, { begin: 65136, end: 65279 }, { begin: 65280, end: 65519 }, { begin: 65520, end: 65535 }, { begin: 3840, end: 4095 }, { begin: 1792, end: 1871 }, { begin: 1920, end: 1983 }, { begin: 3456, end: 3583 }, { begin: 4096, end: 4255 }, { begin: 4608, end: 4991 }, { begin: 5024, end: 5119 }, { begin: 5120, end: 5759 }, { begin: 5760, end: 5791 }, { begin: 5792, end: 5887 }, { begin: 6016, end: 6143 }, { begin: 6144, end: 6319 }, { begin: 10240, end: 10495 }, { begin: 40960, end: 42127 }, { begin: 5888, end: 5919 }, { begin: 66304, end: 66351 }, { begin: 66352, end: 66383 }, { begin: 66560, end: 66639 }, { begin: 118784, end: 119039 }, { begin: 119808, end: 120831 }, { begin: 1044480, end: 1048573 }, { begin: 65024, end: 65039 }, { begin: 917504, end: 917631 }, { begin: 6400, end: 6479 }, { begin: 6480, end: 6527 }, { begin: 6528, end: 6623 }, { begin: 6656, end: 6687 }, { begin: 11264, end: 11359 }, { begin: 11568, end: 11647 }, { begin: 19904, end: 19967 }, { begin: 43008, end: 43055 }, { begin: 65536, end: 65663 }, { begin: 65856, end: 65935 }, { begin: 66432, end: 66463 }, { begin: 66464, end: 66527 }, { begin: 66640, end: 66687 }, { begin: 66688, end: 66735 }, { begin: 67584, end: 67647 }, { begin: 68096, end: 68191 }, { begin: 119552, end: 119647 }, { begin: 73728, end: 74751 }, { begin: 119648, end: 119679 }, { begin: 7040, end: 7103 }, { begin: 7168, end: 7247 }, { begin: 7248, end: 7295 }, { begin: 43136, end: 43231 }, { begin: 43264, end: 43311 }, { begin: 43312, end: 43359 }, { begin: 43520, end: 43615 }, { begin: 65936, end: 65999 }, { begin: 66e3, end: 66047 }, { begin: 66208, end: 66271 }, { begin: 127024, end: 127135 } ]; function getUnicodeRange(unicode) { for (var i = 0; i < unicodeRanges.length; i += 1) { var range = unicodeRanges[i]; if (unicode >= range.begin && unicode < range.end) return i; } return -1; } function parseOS2Table(data, start) { var os22 = {}; var p = new parse.Parser(data, start); os22.version = p.parseUShort(); os22.xAvgCharWidth = p.parseShort(); os22.usWeightClass = p.parseUShort(); os22.usWidthClass = p.parseUShort(); os22.fsType = p.parseUShort(); os22.ySubscriptXSize = p.parseShort(); os22.ySubscriptYSize = p.parseShort(); os22.ySubscriptXOffset = p.parseShort(); os22.ySubscriptYOffset = p.parseShort(); os22.ySuperscriptXSize = p.parseShort(); os22.ySuperscriptYSize = p.parseShort(); os22.ySuperscriptXOffset = p.parseShort(); os22.ySuperscriptYOffset = p.parseShort(); os22.yStrikeoutSize = p.parseShort(); os22.yStrikeoutPosition = p.parseShort(); os22.sFamilyClass = p.parseShort(); os22.panose = []; for (var i = 0; i < 10; i++) os22.panose[i] = p.parseByte(); os22.ulUnicodeRange1 = p.parseULong(); os22.ulUnicodeRange2 = p.parseULong(); os22.ulUnicodeRange3 = p.parseULong(); os22.ulUnicodeRange4 = p.parseULong(); os22.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); os22.fsSelection = p.parseUShort(); os22.usFirstCharIndex = p.parseUShort(); os22.usLastCharIndex = p.parseUShort(); os22.sTypoAscender = p.parseShort(); os22.sTypoDescender = p.parseShort(); os22.sTypoLineGap = p.parseShort(); os22.usWinAscent = p.parseUShort(); os22.usWinDescent = p.parseUShort(); if (os22.version >= 1) { os22.ulCodePageRange1 = p.parseULong(); os22.ulCodePageRange2 = p.parseULong(); } if (os22.version >= 2) { os22.sxHeight = p.parseShort(); os22.sCapHeight = p.parseShort(); os22.usDefaultChar = p.parseUShort(); os22.usBreakChar = p.parseUShort(); os22.usMaxContent = p.parseUShort(); } return os22; } function makeOS2Table(options) { return new table.Table("OS/2", [ { name: "version", type: "USHORT", value: 3 }, { name: "xAvgCharWidth", type: "SHORT", value: 0 }, { name: "usWeightClass", type: "USHORT", value: 0 }, { name: "usWidthClass", type: "USHORT", value: 0 }, { name: "fsType", type: "USHORT", value: 0 }, { name: "ySubscriptXSize", type: "SHORT", value: 650 }, { name: "ySubscriptYSize", type: "SHORT", value: 699 }, { name: "ySubscriptXOffset", type: "SHORT", value: 0 }, { name: "ySubscriptYOffset", type: "SHORT", value: 140 }, { name: "ySuperscriptXSize", type: "SHORT", value: 650 }, { name: "ySuperscriptYSize", type: "SHORT", value: 699 }, { name: "ySuperscriptXOffset", type: "SHORT", value: 0 }, { name: "ySuperscriptYOffset", type: "SHORT", value: 479 }, { name: "yStrikeoutSize", type: "SHORT", value: 49 }, { name: "yStrikeoutPosition", type: "SHORT", value: 258 }, { name: "sFamilyClass", type: "SHORT", value: 0 }, { name: "bFamilyType", type: "BYTE", value: 0 }, { name: "bSerifStyle", type: "BYTE", value: 0 }, { name: "bWeight", type: "BYTE", value: 0 }, { name: "bProportion", type: "BYTE", value: 0 }, { name: "bContrast", type: "BYTE", value: 0 }, { name: "bStrokeVariation", type: "BYTE", value: 0 }, { name: "bArmStyle", type: "BYTE", value: 0 }, { name: "bLetterform", type: "BYTE", value: 0 }, { name: "bMidline", type: "BYTE", value: 0 }, { name: "bXHeight", type: "BYTE", value: 0 }, { name: "ulUnicodeRange1", type: "ULONG", value: 0 }, { name: "ulUnicodeRange2", type: "ULONG", value: 0 }, { name: "ulUnicodeRange3", type: "ULONG", value: 0 }, { name: "ulUnicodeRange4", type: "ULONG", value: 0 }, { name: "achVendID", type: "CHARARRAY", value: "XXXX" }, { name: "fsSelection", type: "USHORT", value: 0 }, { name: "usFirstCharIndex", type: "USHORT", value: 0 }, { name: "usLastCharIndex", type: "USHORT", value: 0 }, { name: "sTypoAscender", type: "SHORT", value: 0 }, { name: "sTypoDescender", type: "SHORT", value: 0 }, { name: "sTypoLineGap", type: "SHORT", value: 0 }, { name: "usWinAscent", type: "USHORT", value: 0 }, { name: "usWinDescent", type: "USHORT", value: 0 }, { name: "ulCodePageRange1", type: "ULONG", value: 0 }, { name: "ulCodePageRange2", type: "ULONG", value: 0 }, { name: "sxHeight", type: "SHORT", value: 0 }, { name: "sCapHeight", type: "SHORT", value: 0 }, { name: "usDefaultChar", type: "USHORT", value: 0 }, { name: "usBreakChar", type: "USHORT", value: 0 }, { name: "usMaxContext", type: "USHORT", value: 0 } ], options); } var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges, getUnicodeRange }; function parsePostTable(data, start) { var post2 = {}; var p = new parse.Parser(data, start); post2.version = p.parseVersion(); post2.italicAngle = p.parseFixed(); post2.underlinePosition = p.parseShort(); post2.underlineThickness = p.parseShort(); post2.isFixedPitch = p.parseULong(); post2.minMemType42 = p.parseULong(); post2.maxMemType42 = p.parseULong(); post2.minMemType1 = p.parseULong(); post2.maxMemType1 = p.parseULong(); switch (post2.version) { case 1: post2.names = standardNames.slice(); break; case 2: post2.numberOfGlyphs = p.parseUShort(); post2.glyphNameIndex = new Array(post2.numberOfGlyphs); for (var i = 0; i < post2.numberOfGlyphs; i++) post2.glyphNameIndex[i] = p.parseUShort(); post2.names = []; for (var i$1 = 0; i$1 < post2.numberOfGlyphs; i$1++) if (post2.glyphNameIndex[i$1] >= standardNames.length) { var nameLength = p.parseChar(); post2.names.push(p.parseString(nameLength)); } break; case 2.5: post2.numberOfGlyphs = p.parseUShort(); post2.offset = new Array(post2.numberOfGlyphs); for (var i$2 = 0; i$2 < post2.numberOfGlyphs; i$2++) post2.offset[i$2] = p.parseChar(); break; } return post2; } function makePostTable() { return new table.Table("post", [ { name: "version", type: "FIXED", value: 196608 }, { name: "italicAngle", type: "FIXED", value: 0 }, { name: "underlinePosition", type: "FWORD", value: 0 }, { name: "underlineThickness", type: "FWORD", value: 0 }, { name: "isFixedPitch", type: "ULONG", value: 0 }, { name: "minMemType42", type: "ULONG", value: 0 }, { name: "maxMemType42", type: "ULONG", value: 0 }, { name: "minMemType1", type: "ULONG", value: 0 }, { name: "maxMemType1", type: "ULONG", value: 0 } ]); } var post = { parse: parsePostTable, make: makePostTable }; var subtableParsers = new Array(9); subtableParsers[1] = function parseLookup1() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) return { substFormat: 1, coverage: this.parsePointer(Parser.coverage), deltaGlyphId: this.parseUShort() }; else if (substFormat === 2) return { substFormat: 2, coverage: this.parsePointer(Parser.coverage), substitute: this.parseOffset16List() }; check.assert(false, "0x" + start.toString(16) + ": lookup type 1 format must be 1 or 2."); }; subtableParsers[2] = function parseLookup2() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, "GSUB Multiple Substitution Subtable identifier-format must be 1"); return { substFormat, coverage: this.parsePointer(Parser.coverage), sequences: this.parseListOfLists() }; }; subtableParsers[3] = function parseLookup3() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, "GSUB Alternate Substitution Subtable identifier-format must be 1"); return { substFormat, coverage: this.parsePointer(Parser.coverage), alternateSets: this.parseListOfLists() }; }; subtableParsers[4] = function parseLookup4() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, "GSUB ligature table identifier-format must be 1"); return { substFormat, coverage: this.parsePointer(Parser.coverage), ligatureSets: this.parseListOfLists(function() { return { ligGlyph: this.parseUShort(), components: this.parseUShortList(this.parseUShort() - 1) }; }) }; }; var lookupRecordDesc = { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }; subtableParsers[5] = function parseLookup5() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) return { substFormat, coverage: this.parsePointer(Parser.coverage), ruleSets: this.parseListOfLists(function() { var glyphCount2 = this.parseUShort(); var substCount2 = this.parseUShort(); return { input: this.parseUShortList(glyphCount2 - 1), lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc) }; }) }; else if (substFormat === 2) return { substFormat, coverage: this.parsePointer(Parser.coverage), classDef: this.parsePointer(Parser.classDef), classSets: this.parseListOfLists(function() { var glyphCount2 = this.parseUShort(); var substCount2 = this.parseUShort(); return { classes: this.parseUShortList(glyphCount2 - 1), lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc) }; }) }; else if (substFormat === 3) { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { substFormat, coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; } check.assert(false, "0x" + start.toString(16) + ": lookup type 5 format must be 1, 2 or 3."); }; subtableParsers[6] = function parseLookup6() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) return { substFormat: 1, coverage: this.parsePointer(Parser.coverage), chainRuleSets: this.parseListOfLists(function() { return { backtrack: this.parseUShortList(), input: this.parseUShortList(this.parseShort() - 1), lookahead: this.parseUShortList(), lookupRecords: this.parseRecordList(lookupRecordDesc) }; }) }; else if (substFormat === 2) return { substFormat: 2, coverage: this.parsePointer(Parser.coverage), backtrackClassDef: this.parsePointer(Parser.classDef), inputClassDef: this.parsePointer(Parser.classDef), lookaheadClassDef: this.parsePointer(Parser.classDef), chainClassSet: this.parseListOfLists(function() { return { backtrack: this.parseUShortList(), input: this.parseUShortList(this.parseShort() - 1), lookahead: this.parseUShortList(), lookupRecords: this.parseRecordList(lookupRecordDesc) }; }) }; else if (substFormat === 3) return { substFormat: 3, backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookupRecords: this.parseRecordList(lookupRecordDesc) }; check.assert(false, "0x" + start.toString(16) + ": lookup type 6 format must be 1, 2 or 3."); }; subtableParsers[7] = function parseLookup7() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, "GSUB Extension Substitution subtable identifier-format must be 1"); var extensionLookupType = this.parseUShort(); var extensionParser = new Parser(this.data, this.offset + this.parseULong()); return { substFormat: 1, lookupType: extensionLookupType, extension: subtableParsers[extensionLookupType].call(extensionParser) }; }; subtableParsers[8] = function parseLookup8() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, "GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1"); return { substFormat, coverage: this.parsePointer(Parser.coverage), backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), substitutes: this.parseUShortList() }; }; function parseGsubTable(data, start) { start = start || 0; var p = new Parser(data, start); var tableVersion = p.parseVersion(1); check.argument(tableVersion === 1 || tableVersion === 1.1, "Unsupported GSUB table version."); if (tableVersion === 1) return { version: tableVersion, scripts: p.parseScriptList(), features: p.parseFeatureList(), lookups: p.parseLookupList(subtableParsers) }; else return { version: tableVersion, scripts: p.parseScriptList(), features: p.parseFeatureList(), lookups: p.parseLookupList(subtableParsers), variations: p.parseFeatureVariationsList() }; } var subtableMakers = new Array(9); subtableMakers[1] = function makeLookup1(subtable) { if (subtable.substFormat === 1) return new table.Table("substitutionTable", [ { name: "substFormat", type: "USHORT", value: 1 }, { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }, { name: "deltaGlyphID", type: "USHORT", value: subtable.deltaGlyphId } ]); else return new table.Table("substitutionTable", [{ name: "substFormat", type: "USHORT", value: 2 }, { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }].concat(table.ushortList("substitute", subtable.substitute))); }; subtableMakers[2] = function makeLookup2(subtable) { check.assert(subtable.substFormat === 1, "Lookup type 2 substFormat must be 1."); return new table.Table("substitutionTable", [{ name: "substFormat", type: "USHORT", value: 1 }, { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }].concat(table.tableList("seqSet", subtable.sequences, function(sequenceSet) { return new table.Table("sequenceSetTable", table.ushortList("sequence", sequenceSet)); }))); }; subtableMakers[3] = function makeLookup3(subtable) { check.assert(subtable.substFormat === 1, "Lookup type 3 substFormat must be 1."); return new table.Table("substitutionTable", [{ name: "substFormat", type: "USHORT", value: 1 }, { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }].concat(table.tableList("altSet", subtable.alternateSets, function(alternateSet) { return new table.Table("alternateSetTable", table.ushortList("alternate", alternateSet)); }))); }; subtableMakers[4] = function makeLookup4(subtable) { check.assert(subtable.substFormat === 1, "Lookup type 4 substFormat must be 1."); return new table.Table("substitutionTable", [{ name: "substFormat", type: "USHORT", value: 1 }, { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }].concat(table.tableList("ligSet", subtable.ligatureSets, function(ligatureSet) { return new table.Table("ligatureSetTable", table.tableList("ligature", ligatureSet, function(ligature) { return new table.Table("ligatureTable", [{ name: "ligGlyph", type: "USHORT", value: ligature.ligGlyph }].concat(table.ushortList("component", ligature.components, ligature.components.length + 1))); })); }))); }; subtableMakers[6] = function makeLookup6(subtable) { if (subtable.substFormat === 1) return new table.Table("chainContextTable", [{ name: "substFormat", type: "USHORT", value: subtable.substFormat }, { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }].concat(table.tableList("chainRuleSet", subtable.chainRuleSets, function(chainRuleSet) { return new table.Table("chainRuleSetTable", table.tableList("chainRule", chainRuleSet, function(chainRule) { var tableData2 = table.ushortList("backtrackGlyph", chainRule.backtrack, chainRule.backtrack.length).concat(table.ushortList("inputGlyph", chainRule.input, chainRule.input.length + 1)).concat(table.ushortList("lookaheadGlyph", chainRule.lookahead, chainRule.lookahead.length)).concat(table.ushortList("substitution", [], chainRule.lookupRecords.length)); chainRule.lookupRecords.forEach(function(record, i) { tableData2 = tableData2.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex }); }); return new table.Table("chainRuleTable", tableData2); })); }))); else if (subtable.substFormat === 2) check.assert(false, "lookup type 6 format 2 is not yet supported."); else if (subtable.substFormat === 3) { var tableData = [{ name: "substFormat", type: "USHORT", value: subtable.substFormat }]; tableData.push({ name: "backtrackGlyphCount", type: "USHORT", value: subtable.backtrackCoverage.length }); subtable.backtrackCoverage.forEach(function(coverage, i) { tableData.push({ name: "backtrackCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); }); tableData.push({ name: "inputGlyphCount", type: "USHORT", value: subtable.inputCoverage.length }); subtable.inputCoverage.forEach(function(coverage, i) { tableData.push({ name: "inputCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); }); tableData.push({ name: "lookaheadGlyphCount", type: "USHORT", value: subtable.lookaheadCoverage.length }); subtable.lookaheadCoverage.forEach(function(coverage, i) { tableData.push({ name: "lookaheadCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); }); tableData.push({ name: "substitutionCount", type: "USHORT", value: subtable.lookupRecords.length }); subtable.lookupRecords.forEach(function(record, i) { tableData = tableData.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex }); }); return new table.Table("chainContextTable", tableData); } 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 p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 1, "Unsupported META table version."); p.parseULong(); p.parseULong(); var numDataMaps = p.parseULong(); var tags = {}; for (var i = 0; i < numDataMaps; i++) { var tag = p.parseTag(); var dataOffset = p.parseULong(); var dataLength = p.parseULong(); tags[tag] = decode.UTF8(data, start + dataOffset, dataLength); } 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(v) { return Math.log(v) / Math.log(2) | 0; } function computeCheckSum(bytes) { while (bytes.length % 4 !== 0) bytes.push(0); var sum = 0; for (var i = 0; i < bytes.length; i += 4) sum += (bytes[i] << 24) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3]; sum %= Math.pow(2, 32); return sum; } function makeTableRecord(tag, checkSum, offset, length) { 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: length !== void 0 ? length : 0 } ]); } function makeSfntTable(tables) { var sfnt2 = new table.Table("sfnt", [ { name: "version", type: "TAG", value: "OTTO" }, { name: "numTables", type: "USHORT", value: 0 }, { name: "searchRange", type: "USHORT", value: 0 }, { name: "entrySelector", type: "USHORT", value: 0 }, { name: "rangeShift", type: "USHORT", value: 0 } ]); sfnt2.tables = tables; sfnt2.numTables = tables.length; var highestPowerOf2 = Math.pow(2, log2(sfnt2.numTables)); sfnt2.searchRange = 16 * highestPowerOf2; sfnt2.entrySelector = log2(highestPowerOf2); sfnt2.rangeShift = sfnt2.numTables * 16 - sfnt2.searchRange; var recordFields = []; var tableFields = []; var offset = sfnt2.sizeOf() + makeTableRecord().sizeOf() * sfnt2.numTables; while (offset % 4 !== 0) { offset += 1; tableFields.push({ name: "padding", type: "BYTE", value: 0 }); } for (var i = 0; i < tables.length; i += 1) { var t = tables[i]; check.argument(t.tableName.length === 4, "Table name" + t.tableName + " is invalid."); var tableLength = t.sizeOf(); var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength); recordFields.push({ name: tableRecord.tag + " Table Record", type: "RECORD", value: tableRecord }); tableFields.push({ name: t.tableName + " table", type: "RECORD", value: t }); offset += tableLength; check.argument(!isNaN(offset), "Something went wrong calculating the offset."); while (offset % 4 !== 0) { offset += 1; tableFields.push({ name: "padding", type: "BYTE", value: 0 }); } } recordFields.sort(function(r1, r2) { if (r1.value.tag > r2.value.tag) return 1; else return -1; }); sfnt2.fields = sfnt2.fields.concat(recordFields); sfnt2.fields = sfnt2.fields.concat(tableFields); return sfnt2; } function metricsForChar(font, chars, notFoundMetrics) { for (var i = 0; i < chars.length; i += 1) { var glyphIndex = font.charToGlyphIndex(chars[i]); if (glyphIndex > 0) return font.glyphs.get(glyphIndex).getMetrics(); } return notFoundMetrics; } function average(vs) { var sum = 0; for (var i = 0; i < vs.length; i += 1) sum += vs[i]; 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 i = 0; i < font.glyphs.length; i += 1) { var glyph = font.glyphs.get(i); var unicode = glyph.unicode | 0; if (isNaN(glyph.advanceWidth)) throw new Error("Glyph " + glyph.name + " (" + i + "): advanceWidth is not a number."); if (firstCharIndex > unicode || firstCharIndex === void 0) { if (unicode > 0) firstCharIndex = unicode; } if (lastCharIndex < unicode) lastCharIndex = unicode; var position = os2.getUnicodeRange(unicode); if (position < 32) ulUnicodeRange1 |= 1 << position; else if (position < 64) ulUnicodeRange2 |= 1 << position - 32; else if (position < 96) ulUnicodeRange3 |= 1 << position - 64; else if (position < 123) ulUnicodeRange4 |= 1 << position - 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, 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, sTypoAscender: globals.ascender, sTypoDescender: globals.descender, sTypoLineGap: 0, usWinAscent: globals.yMax, usWinDescent: Math.abs(globals.yMin), ulCodePageRange1: 1, sxHeight: metricsForChar(font, "xyvw", { yMax: Math.round(globals.ascender / 2) }).yMax, sCapHeight: metricsForChar(font, "HIKLEFJMNTZBDPRAGOQSUVWXY", globals).yMax, usDefaultChar: font.hasChar(" ") ? 32 : 0, usBreakChar: font.hasChar(" ") ? 32 : 0 }, 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 n in font.names) names[n] = font.names[n]; 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 checkSum = computeCheckSum(sfntTable.encode()); 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(create) { var layout = this.font.tables[this.tableName]; if (!layout && create) layout = this.font.tables[this.tableName] = this.createDefaultTable(); return layout; }, /** * Returns all scripts in the substitution table. * @instance * @return {Array} */ getScriptNames: function() { var layout = this.getTable(); if (!layout) return []; return layout.scripts.map(function(script) { return script.tag; }); }, /** * Returns the best bet for a script name. * Returns 'DFLT' if it exists. * If not, returns 'latn' if it exists. * If neither exist, returns undefined. */ getDefaultScriptName: function() { var layout = this.getTable(); if (!layout) return; var hasLatn = false; for (var i = 0; i < layout.scripts.length; i++) { var name = layout.scripts[i].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, create) { var layout = this.getTable(create); if (layout) { script = script || "DFLT"; var scripts = layout.scripts; var pos = searchTag(layout.scripts, script); if (pos >= 0) return scripts[pos].script; else if (create) { var scr = { tag: script, script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] }, langSysRecords: [] } }; scripts.splice(-1 - pos, 0, scr); return scr.script; } } }, /** * Returns a language system table * @instance * @param {string} [script='DFLT'] * @param {string} [language='dlft'] * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist. * @return {Object} */ getLangSysTable: function(script, language, create) { var scriptTable = this.getScriptTable(script, create); if (scriptTable) { if (!language || language === "dflt" || language === "DFLT") return scriptTable.defaultLangSys; var pos = searchTag(scriptTable.langSysRecords, language); if (pos >= 0) return scriptTable.langSysRecords[pos].langSys; else if (create) { var langSysRecord = { tag: language, langSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] } }; scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); return langSysRecord.langSys; } } }, /** * Get a specific feature table. * @instance * @param {string} [script='DFLT'] * @param {string} [language='dlft'] * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm * @param {boolean} create - forces the creation of the feature table if it doesn't exist. * @return {Object} */ getFeatureTable: function(script, language, feature, create) { var langSysTable2 = this.getLangSysTable(script, language, create); if (langSysTable2) { var featureRecord; var featIndexes = langSysTable2.featureIndexes; var allFeatures = this.font.tables[this.tableName].features; for (var i = 0; i < featIndexes.length; i++) { featureRecord = allFeatures[featIndexes[i]]; if (featureRecord.tag === feature) return featureRecord.feature; } if (create) { var index = allFeatures.length; check.assert(index === 0 || feature >= allFeatures[index - 1].tag, "Features must be added in alphabetical order."); featureRecord = { tag: feature, feature: { params: 0, lookupListIndexes: [] } }; allFeatures.push(featureRecord); featIndexes.push(index); return featureRecord.feature; } } }, /** * Get the lookup tables of a given type for a script/language/feature. * @instance * @param {string} [script='DFLT'] * @param {string} [language='dlft'] * @param {string} feature - 4-letter feature code * @param {number} lookupType - 1 to 9 * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables. * @return {Object[]} */ getLookupTables: function(script, language, feature, lookupType, create) { var featureTable = this.getFeatureTable(script, language, feature, create); var tables = []; if (featureTable) { var lookupTable; var lookupListIndexes = featureTable.lookupListIndexes; var allLookups = this.font.tables[this.tableName].lookups; for (var i = 0; i < lookupListIndexes.length; i++) { lookupTable = allLookups[lookupListIndexes[i]]; if (lookupTable.lookupType === lookupType) tables.push(lookupTable); } if (tables.length === 0 && create) { lookupTable = { lookupType, lookupFlag: 0, subtables: [], markFilteringSet: void 0 }; var index = allLookups.length; allLookups.push(lookupTable); lookupListIndexes.push(index); 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 index = binSearch(coverageTable.glyphs, glyphIndex); return index >= 0 ? index : -1; case 2: var range = searchRange(coverageTable.ranges, glyphIndex); return range ? range.index + glyphIndex - range.start : -1; } }, /** * Returns the list of glyph indexes of a coverage table. * Format 1: the list is stored raw * Format 2: compact list as range records. * @instance * @param {Object} coverageTable * @return {Array} */ expandCoverage: function(coverageTable) { if (coverageTable.format === 1) return coverageTable.glyphs; else { var glyphs = []; var ranges = coverageTable.ranges; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; var start = range.start; var end = range.end; for (var 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 i = 0; i < kerningLookups.length; i++) { var subtables = kerningLookups[i].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 n = ar1.length; if (n !== ar2.length) return false; for (var i = 0; i < n; i++) if (ar1[i] !== ar2[i]) return false; return true; } function getSubstFormat(lookupTable, format, defaultSubtable) { var subtables = lookupTable.subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; if (subtable.substFormat === format) return subtable; } if (defaultSubtable) { subtables.push(defaultSubtable); return defaultSubtable; } } Substitution.prototype = Layout.prototype; Substitution.prototype.createDefaultTable = function() { return { version: 1, scripts: [{ tag: "DFLT", script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] }, langSysRecords: [] } }], features: [], lookups: [] }; }; Substitution.prototype.getSingle = function(feature, script, language) { var substitutions = []; var lookupTables = this.getLookupTables(script, language, feature, 1); for (var idx = 0; idx < lookupTables.length; idx++) { var subtables = lookupTables[idx].subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; var glyphs = this.expandCoverage(subtable.coverage); var 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 i = 0; i < subtables.length; i++) { var subtable = subtables[i]; 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 i = 0; i < subtables.length; i++) { var subtable = subtables[i]; 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 i = 0; i < subtables.length; i++) { var subtable = subtables[i]; 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, { 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, { 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, { 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 = { substFormat: 1, coverage: { format: 1, glyphs: [] }, ligatureSets: [] }; lookupTable.subtables[0] = subtable; } check.assert(subtable.coverage.format === 1, "Ligature: unable to modify coverage table format " + subtable.coverage.format); var coverageGlyph = ligature.sub[0]; var ligComponents = ligature.sub.slice(1); var ligatureTable = { ligGlyph: ligature.by, components: ligComponents }; var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); if (pos >= 0) { var ligatureSet = subtable.ligatureSets[pos]; for (var i = 0; i < ligatureSet.length; i++) if (arraysEqual(ligatureSet[i].components, ligComponents)) return; ligatureSet.push(ligatureTable); } else { pos = -1 - pos; subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); subtable.ligatureSets.splice(pos, 0, [ligatureTable]); } }; Substitution.prototype.getFeature = function(feature, script, language) { if (/ss\d\d/.test(feature)) return this.getSingle(feature, script, language); switch (feature) { case "aalt": case "salt": return this.getSingle(feature, script, language).concat(this.getAlternates(feature, script, language)); case "dlig": case "liga": case "rlig": return this.getLigatures(feature, script, language); case "ccmp": return this.getMultiple(feature, script, language).concat(this.getLigatures(feature, script, language)); case "stch": return this.getMultiple(feature, script, language); } }; Substitution.prototype.add = function(feature, sub, script, language) { if (/ss\d\d/.test(feature)) return this.addSingle(feature, sub, script, language); switch (feature) { case "aalt": case "salt": if (typeof sub.by === "number") return this.addSingle(feature, sub, script, language); return this.addAlternate(feature, sub, script, language); case "dlig": case "liga": case "rlig": return this.addLigature(feature, sub, script, language); case "ccmp": if (sub.by instanceof Array) return this.addMultiple(feature, sub, script, language); return this.addLigature(feature, sub, script, language); } }; function checkArgument(expression, message) { if (!expression) throw message; } function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { var v; if ((flag & shortVectorBitMask) > 0) { v = p.parseByte(); if ((flag & sameBitMask) === 0) v = -v; v = previousValue + v; } else if ((flag & sameBitMask) > 0) v = previousValue; else v = previousValue + p.parseShort(); return v; } function parseGlyph(glyph, data, start) { var p = new parse.Parser(data, start); glyph.numberOfContours = p.parseShort(); glyph._xMin = p.parseShort(); glyph._yMin = p.parseShort(); glyph._xMax = p.parseShort(); glyph._yMax = p.parseShort(); var flags; var flag; if (glyph.numberOfContours > 0) { var endPointIndices = glyph.endPointIndices = []; for (var i = 0; i < glyph.numberOfContours; i += 1) endPointIndices.push(p.parseUShort()); glyph.instructionLength = p.parseUShort(); glyph.instructions = []; for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) glyph.instructions.push(p.parseByte()); var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; flags = []; for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) { flag = p.parseByte(); flags.push(flag); if ((flag & 8) > 0) { var repeatCount = p.parseByte(); for (var 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(p, flag, px, 2, 16); px = point.x; } var py = 0; for (var i$5 = 0; i$5 < numberOfCoordinates; i$5 += 1) { flag = flags[i$5]; point = points[i$5]; point.y = parseGlyphCoordinate(p, flag, py, 4, 32); py = point.y; } } glyph.points = points; } else glyph.points = []; } else if (glyph.numberOfContours === 0) glyph.points = []; else { glyph.isComposite = true; glyph.points = []; glyph.components = []; var moreComponents = true; while (moreComponents) { flags = p.parseUShort(); var component = { glyphIndex: p.parseUShort(), xScale: 1, scale01: 0, scale10: 0, yScale: 1, dx: 0, dy: 0 }; if ((flags & 1) > 0) if ((flags & 2) > 0) { component.dx = p.parseShort(); component.dy = p.parseShort(); } else component.matchedPoints = [p.parseUShort(), p.parseUShort()]; else if ((flags & 2) > 0) { component.dx = p.parseChar(); component.dy = p.parseChar(); } else component.matchedPoints = [p.parseByte(), p.parseByte()]; if ((flags & 8) > 0) component.xScale = component.yScale = p.parseF2Dot14(); else if ((flags & 64) > 0) { component.xScale = p.parseF2Dot14(); component.yScale = p.parseF2Dot14(); } else if ((flags & 128) > 0) { component.xScale = p.parseF2Dot14(); component.scale01 = p.parseF2Dot14(); component.scale10 = p.parseF2Dot14(); component.yScale = p.parseF2Dot14(); } glyph.components.push(component); moreComponents = !!(flags & 32); } if (flags & 256) { glyph.instructionLength = p.parseUShort(); glyph.instructions = []; for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) glyph.instructions.push(p.parseByte()); } } } function transformPoints(points, transform) { var newPoints = []; for (var i = 0; i < points.length; i += 1) { var pt = points[i]; 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 i = 0; i < points.length; i += 1) { var pt = points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } check.argument(currentContour.length === 0, "There are still points left in the current contour."); return contours; } function getPath(points) { var p = new Path(); if (!points) return p; var contours = getContours(points); for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) { var contour = contours[contourIndex]; var prev = null; var curr = contour[contour.length - 1]; var next = contour[0]; if (curr.onCurve) p.moveTo(curr.x, curr.y); else if (next.onCurve) p.moveTo(next.x, next.y); else { var start = { x: (curr.x + next.x) * .5, y: (curr.y + next.y) * .5 }; p.moveTo(start.x, start.y); } for (var i = 0; i < contour.length; ++i) { prev = curr; curr = next; next = contour[(i + 1) % contour.length]; if (curr.onCurve) p.lineTo(curr.x, curr.y); else { var next2 = next; if (!prev.onCurve) (curr.x + prev.x) * .5, (curr.y + prev.y) * .5; if (!next.onCurve) next2 = { x: (curr.x + next.x) * .5, y: (curr.y + next.y) * .5 }; p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); } } p.closePath(); } return p; } 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 i = 0; i < loca2.length - 1; i += 1) { var offset = loca2[i]; if (offset !== loca2[i + 1]) glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); else glyphs.push(i, glyphset.glyphLoader(font, i)); } return glyphs; } function parseGlyfTableOnLowMemory(data, start, loca2, font) { var glyphs = new glyphset.GlyphSet(font); font._push = function(i) { var offset = loca2[i]; if (offset !== loca2[i + 1]) glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); else glyphs.push(i, glyphset.glyphLoader(font, i)); }; 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(v) { return v; } function roundToGrid(v) { return Math.sign(v) * Math.round(Math.abs(v)); } function roundToDoubleGrid(v) { return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2; } function roundToHalfGrid(v) { return Math.sign(v) * (Math.round(Math.abs(v) + .5) - .5); } function roundUpToGrid(v) { return Math.sign(v) * Math.ceil(Math.abs(v)); } function roundDownToGrid(v) { return Math.sign(v) * Math.floor(Math.abs(v)); } var roundSuper = function(v) { var period = this.srPeriod; var phase = this.srPhase; var threshold = this.srThreshold; var sign = 1; if (v < 0) { v = -v; sign = -1; } v += threshold - phase; v = Math.trunc(v / period) * period; v += phase; if (v < 0) return phase * sign; return v * sign; }; var xUnitVector = { x: 1, y: 0, axis: "x", distance: function(p1, p2, o1, o2) { return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x); }, interpolate: function(p, rp1, rp2, pv) { var do1; var do2; var doa1; var doa2; var dm1; var dm2; var dt; if (!pv || pv === this) { do1 = p.xo - rp1.xo; do2 = p.xo - rp2.xo; dm1 = rp1.x - rp1.xo; dm2 = rp2.x - rp2.xo; doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { p.x = p.xo + (dm1 + dm2) / 2; return; } p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt; return; } do1 = pv.distance(p, rp1, true, true); do2 = pv.distance(p, rp2, true, true); dm1 = pv.distance(rp1, rp1, false, true); dm2 = pv.distance(rp2, rp2, false, true); doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); return; } xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); }, normalSlope: Number.NEGATIVE_INFINITY, setRelative: function(p, rp, d, pv, org) { if (!pv || pv === this) { p.x = (org ? rp.xo : rp.x) + d; return; } var rpx = org ? rp.xo : rp.x; var rpy = org ? rp.yo : rp.y; var rpdx = rpx + d * pv.x; var rpdy = rpy + d * pv.y; p.x = rpdx + (p.y - rpdy) / pv.normalSlope; }, slope: 0, touch: function(p) { p.xTouched = true; }, touched: function(p) { return p.xTouched; }, untouch: function(p) { p.xTouched = false; } }; var yUnitVector = { x: 0, y: 1, axis: "y", distance: function(p1, p2, o1, o2) { return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y); }, interpolate: function(p, rp1, rp2, pv) { var do1; var do2; var doa1; var doa2; var dm1; var dm2; var dt; if (!pv || pv === this) { do1 = p.yo - rp1.yo; do2 = p.yo - rp2.yo; dm1 = rp1.y - rp1.yo; dm2 = rp2.y - rp2.yo; doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { p.y = p.yo + (dm1 + dm2) / 2; return; } p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt; return; } do1 = pv.distance(p, rp1, true, true); do2 = pv.distance(p, rp2, true, true); dm1 = pv.distance(rp1, rp1, false, true); dm2 = pv.distance(rp2, rp2, false, true); doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); return; } yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); }, normalSlope: 0, setRelative: function(p, rp, d, pv, org) { if (!pv || pv === this) { p.y = (org ? rp.yo : rp.y) + d; return; } var rpx = org ? rp.xo : rp.x; var rpy = org ? rp.yo : rp.y; var rpdx = rpx + d * pv.x; p.y = rpy + d * pv.y + pv.normalSlope * (p.x - rpdx); }, slope: Number.POSITIVE_INFINITY, touch: function(p) { p.yTouched = true; }, touched: function(p) { return p.yTouched; }, untouch: function(p) { p.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(p, rp1, rp2, pv) { var dm1; var dm2; var do1; var do2; var doa1; var doa2; var dt; do1 = pv.distance(p, rp1, true, true); do2 = pv.distance(p, rp2, true, true); dm1 = pv.distance(rp1, rp1, false, true); dm2 = pv.distance(rp2, rp2, false, true); doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { this.setRelative(p, p, (dm1 + dm2) / 2, pv, true); return; } this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); }; UnitVector.prototype.setRelative = function(p, rp, d, pv, org) { pv = pv || this; var rpx = org ? rp.xo : rp.x; var rpy = org ? rp.yo : rp.y; var rpdx = rpx + d * pv.x; var rpdy = rpy + d * pv.y; var pvns = pv.normalSlope; var fvs = this.slope; var px = p.x; var py = p.y; p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns); p.y = fvs * (p.x - px) + py; }; UnitVector.prototype.touch = function(p) { p.xTouched = true; p.yTouched = true; }; function getUnitVector(x, y) { var d = Math.sqrt(x * x + y * y); x /= d; y /= d; 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(v) { var p = this.nextPointOnContour; while (!v.touched(p) && p !== this) p = p.nextPointOnContour; return p; }; HPoint.prototype.prevTouched = function(v) { var p = this.prevPointOnContour; while (!v.touched(p) && p !== this) p = p.prevPointOnContour; return p; }; var HPZero = Object.freeze(new HPoint(0, 0)); var defaultState = { cvCutIn: 17 / 16, deltaBase: 9, deltaShift: .125, loop: 1, minDis: 1, 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 (e) { console.log("Hinting error in FPGM:" + e); this._errorState = 3; return; } } State.prototype = fpgmState; prepState = this._prepState = new State("prep", font.tables.prep); prepState.ppem = ppem; var oCvt = font.tables.cvt; if (oCvt) { var cvt = prepState.cvt = new Array(oCvt.length); var scale = ppem / font.unitsPerEm; for (var c = 0; c < oCvt.length; c++) cvt[c] = oCvt[c] * scale; } else prepState.cvt = []; if (exports.DEBUG) { console.log("---EXEC PREP---"); prepState.step = -1; } try { exec(prepState); } catch (e) { if (this._errorState < 2) console.log("Hinting error in PREP:" + e); this._errorState = 2; } } if (this._errorState > 1) return; try { return execGlyph(glyph, prepState); } catch (e) { if (this._errorState < 1) { console.log("Hinting error:" + e); console.log("Note: further hinting errors are silenced"); } this._errorState = 1; return; } }; execGlyph = function(glyph, prepState) { var xScale = prepState.ppem / prepState.font.unitsPerEm; var yScale = xScale; var components = glyph.components; var contours; var gZone; var state; State.prototype = prepState; if (!components) { state = new State("glyf", glyph.instructions); if (exports.DEBUG) { console.log("---EXEC GLYPH---"); state.step = -1; } execComponent(glyph, state, xScale, yScale); gZone = state.gZone; } else { var font = prepState.font; gZone = []; contours = []; for (var i = 0; i < components.length; i++) { var c = components[i]; var cg = font.glyphs.get(c.glyphIndex); state = new State("glyf", cg.instructions); if (exports.DEBUG) { console.log("---EXEC COMP " + i + "---"); state.step = -1; } execComponent(cg, state, xScale, yScale); var dx = Math.round(c.dx * xScale); var dy = Math.round(c.dy * yScale); var gz = state.gZone; var cc = state.contours; for (var pi = 0; pi < gz.length; pi++) { var p = gz[pi]; p.xTouched = p.yTouched = false; p.xo = p.x = p.x + dx; p.yo = p.y = p.y + dy; } var gLen = gZone.length; gZone.push.apply(gZone, gz); for (var 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 i = 0; i < pLen; i++) { cp = points[i]; gZone[i] = new HPoint(cp.x * xScale, cp.y * yScale, cp.lastPointOfContour, cp.onCurve); } var sp; var np; for (var i$1 = 0; i$1 < pLen; i$1++) { cp = gZone[i$1]; if (!sp) { sp = cp; contours.push(i$1); } if (cp.lastPointOfContour) { cp.nextPointOnContour = sp; sp.prevPointOnContour = cp; sp = void 0; } else { np = gZone[i$1 + 1]; cp.nextPointOnContour = np; np.prevPointOnContour = cp; } } if (state.inhibitGridFit) return; if (exports.DEBUG) { console.log("PROCESSING GLYPH", state.stack); for (var i$2 = 0; i$2 < pLen; i$2++) console.log(i$2, gZone[i$2].x, gZone[i$2].y); } gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); exec(state); gZone.length -= 2; if (exports.DEBUG) { console.log("FINISHED GLYPH", state.stack); for (var i$3 = 0; i$3 < pLen; i$3++) console.log(i$3, gZone[i$3].x, gZone[i$3].y); } }; exec = function(state) { var prog = state.prog; if (!prog) return; var pLen = prog.length; var ins; for (state.ip = 0; state.ip < pLen; state.ip++) { if (exports.DEBUG) state.step++; ins = instructionTable[prog[state.ip]]; if (!ins) throw new Error("unknown instruction: 0x" + Number(prog[state.ip]).toString(16)); ins(state); } }; function initTZone(state) { var tZone = state.tZone = new Array(state.gZone.length); for (var i = 0; i < tZone.length; i++) tZone[i] = new HPoint(0, 0); } function skip(state, handleElse) { var prog = state.prog; var ip = state.ip; var nesting = 1; var ins; do { ins = prog[++ip]; if (ins === 88) nesting++; else if (ins === 89) nesting--; else if (ins === 64) ip += prog[ip + 1] + 1; else if (ins === 65) ip += 2 * prog[ip + 1] + 1; else if (ins >= 176 && ins <= 183) ip += ins - 176 + 1; else if (ins >= 184 && ins <= 191) ip += (ins - 184 + 1) * 2; else if (handleElse && nesting === 1 && ins === 27) break; } while (nesting > 0); state.ip = ip; } function SVTCA(v, state) { if (exports.DEBUG) console.log(state.step, "SVTCA[" + v.axis + "]"); state.fv = state.pv = state.dpv = v; } function SPVTCA(v, state) { if (exports.DEBUG) console.log(state.step, "SPVTCA[" + v.axis + "]"); state.pv = state.dpv = v; } function SFVTCA(v, state) { if (exports.DEBUG) console.log(state.step, "SFVTCA[" + v.axis + "]"); state.fv = v; } function SPVTL(a, 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[" + a + "]", p2i, p1i); var dx; var dy; if (!a) { 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(a, 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[" + a + "]", p2i, p1i); var dx; var dy; if (!a) { 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 p = 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; p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div; p.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 n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SZP0[]", n); state.zp0 = n; switch (n) { 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 n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SZP1[]", n); state.zp1 = n; switch (n) { 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 n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SZP2[]", n); state.zp2 = n; switch (n) { 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 n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SZPS[]", n); state.zp0 = state.zp1 = state.zp2 = n; switch (n) { case 0: if (!state.tZone) initTZone(state); state.z0 = state.z1 = state.z2 = state.tZone; break; case 1: state.z0 = state.z1 = state.z2 = state.gZone; break; default: throw new Error("Invalid zone pointer"); } } function SLOOP(state) { state.loop = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SLOOP[]", state.loop); } function RTG(state) { if (exports.DEBUG) console.log(state.step, "RTG[]"); state.round = roundToGrid; } function RTHG(state) { if (exports.DEBUG) console.log(state.step, "RTHG[]"); state.round = roundToHalfGrid; } function SMD(state) { var d = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SMD[]", d); state.minDis = d / 64; } function ELSE(state) { if (exports.DEBUG) console.log(state.step, "ELSE[]"); skip(state, false); } function JMPR(state) { var o = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "JMPR[]", o); state.ip += o - 1; } function SCVTCI(state) { var n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SCVTCI[]", n); state.cvCutIn = n / 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 a = stack.pop(); var b = stack.pop(); if (exports.DEBUG) console.log(state.step, "SWAP[]"); stack.push(a); stack.push(b); } 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 c = stack.pop(); if (exports.DEBUG) console.log(state.step, "LOOPCALL[]", fn, c); var cip = state.ip; var cprog = state.prog; state.prog = state.funcs[fn]; for (var i = 0; i < c; i++) { exec(state); if (exports.DEBUG) console.log(++state.step, i + 1 < c ? "next loopcall" : "done loopcall", i); } state.ip = cip; state.prog = cprog; } function CALL(state) { var fn = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "CALL[]", fn); var cip = state.ip; var cprog = state.prog; state.prog = state.funcs[fn]; exec(state); state.ip = cip; state.prog = cprog; if (exports.DEBUG) console.log(++state.step, "returning from", fn); } function CINDEX(state) { var stack = state.stack; var 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 p = state.z0[pi]; var fv = state.fv; var pv = state.pv; if (exports.DEBUG) console.log(state.step, "MDAP[" + round + "]", pi); var d = pv.distance(p, HPZero); if (round) d = state.round(d); fv.setRelative(p, HPZero, d, pv); fv.touch(p); state.rp0 = state.rp1 = pi; } function IUP(v, state) { var z2 = state.z2; var pLen = z2.length - 2; var cp; var pp; var np; if (exports.DEBUG) console.log(state.step, "IUP[" + v.axis + "]"); for (var i = 0; i < pLen; i++) { cp = z2[i]; if (v.touched(cp)) continue; pp = cp.prevTouched(v); if (pp === cp) continue; np = cp.nextTouched(v); if (pp === np) v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true); v.interpolate(cp, pp, np, v); } } function SHP(a, state) { var stack = state.stack; var rpi = a ? state.rp1 : state.rp2; var rp = (a ? 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 p = z2[pi]; var d = pv.distance(rp, rp, false, true); fv.setRelative(p, p, d, pv); fv.touch(p); if (exports.DEBUG) console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHP[" + (a ? "rp1" : "rp2") + "]", pi); } state.loop = 1; } function SHC(a, state) { var stack = state.stack; var rpi = a ? state.rp1 : state.rp2; var rp = (a ? state.z0 : state.z1)[rpi]; var fv = state.fv; var pv = state.pv; var ci = stack.pop(); var sp = state.z2[state.contours[ci]]; var p = sp; if (exports.DEBUG) console.log(state.step, "SHC[" + a + "]", ci); var d = pv.distance(rp, rp, false, true); do { if (p !== rp) fv.setRelative(p, p, d, pv); p = p.nextPointOnContour; } while (p !== sp); } function SHZ(a, state) { var stack = state.stack; var rpi = a ? state.rp1 : state.rp2; var rp = (a ? state.z0 : state.z1)[rpi]; var fv = state.fv; var pv = state.pv; var e = stack.pop(); if (exports.DEBUG) console.log(state.step, "SHZ[" + a + "]", e); var z; switch (e) { case 0: z = state.tZone; break; case 1: z = state.gZone; break; default: throw new Error("Invalid zone"); } var p; var d = pv.distance(rp, rp, false, true); var pLen = z.length - 2; for (var i = 0; i < pLen; i++) { p = z[i]; fv.setRelative(p, p, d, pv); } } function SHPIX(state) { var stack = state.stack; var loop = state.loop; var fv = state.fv; var d = stack.pop() / 64; var z2 = state.z2; while (loop--) { var pi = stack.pop(); var p = z2[pi]; if (exports.DEBUG) console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHPIX[]", pi, d); fv.setRelative(p, p, d); fv.touch(p); } state.loop = 1; } function IP(state) { var stack = state.stack; var rp1i = state.rp1; var rp2i = state.rp2; var loop = state.loop; var rp1 = state.z0[rp1i]; var rp2 = state.z1[rp2i]; var fv = state.fv; var pv = state.dpv; var z2 = state.z2; while (loop--) { var pi = stack.pop(); var p = z2[pi]; if (exports.DEBUG) console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "IP[]", pi, rp1i, "<->", rp2i); fv.interpolate(p, rp1, rp2, pv); fv.touch(p); } state.loop = 1; } function MSIRP(a, state) { var stack = state.stack; var d = stack.pop() / 64; var pi = stack.pop(); var p = state.z1[pi]; var rp0 = state.z0[state.rp0]; var fv = state.fv; var pv = state.pv; fv.setRelative(p, rp0, d, pv); fv.touch(p); if (exports.DEBUG) console.log(state.step, "MSIRP[" + a + "]", d, pi); state.rp1 = state.rp0; state.rp2 = pi; if (a) 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 p = z1[pi]; if (exports.DEBUG) console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "ALIGNRP[]", pi); fv.setRelative(p, rp0, 0, pv); fv.touch(p); } state.loop = 1; } function RTDG(state) { if (exports.DEBUG) console.log(state.step, "RTDG[]"); state.round = roundToDoubleGrid; } function MIAP(round, state) { var stack = state.stack; var n = stack.pop(); var pi = stack.pop(); var p = state.z0[pi]; var fv = state.fv; var pv = state.pv; var cv = state.cvt[n]; if (exports.DEBUG) console.log(state.step, "MIAP[" + round + "]", n, "(", cv, ")", pi); var d = pv.distance(p, HPZero); if (round) { if (Math.abs(d - cv) < state.cvCutIn) d = cv; d = state.round(d); } fv.setRelative(p, HPZero, d, pv); if (state.zp0 === 0) { p.xo = p.x; p.yo = p.y; } fv.touch(p); state.rp0 = state.rp1 = pi; } function NPUSHB(state) { var prog = state.prog; var ip = state.ip; var stack = state.stack; var n = prog[++ip]; if (exports.DEBUG) console.log(state.step, "NPUSHB[]", n); for (var i = 0; i < n; i++) stack.push(prog[++ip]); state.ip = ip; } function NPUSHW(state) { var ip = state.ip; var prog = state.prog; var stack = state.stack; var n = prog[++ip]; if (exports.DEBUG) console.log(state.step, "NPUSHW[]", n); for (var i = 0; i < n; i++) { var w = prog[++ip] << 8 | prog[++ip]; if (w & 32768) w = -((w ^ 65535) + 1); stack.push(w); } state.ip = ip; } function WS(state) { var stack = state.stack; var store = state.store; if (!store) store = state.store = []; var v = stack.pop(); var l = stack.pop(); if (exports.DEBUG) console.log(state.step, "WS", v, l); store[l] = v; } function RS(state) { var stack = state.stack; var store = state.store; var l = stack.pop(); if (exports.DEBUG) console.log(state.step, "RS", l); var v = store && store[l] || 0; stack.push(v); } function WCVTP(state) { var stack = state.stack; var v = stack.pop(); var l = stack.pop(); if (exports.DEBUG) console.log(state.step, "WCVTP", v, l); state.cvt[l] = v / 64; } function RCVT(state) { var stack = state.stack; var cvte = stack.pop(); if (exports.DEBUG) console.log(state.step, "RCVT", cvte); stack.push(state.cvt[cvte] * 64); } function GC(a, state) { var stack = state.stack; var pi = stack.pop(); var p = state.z2[pi]; if (exports.DEBUG) console.log(state.step, "GC[" + a + "]", pi); stack.push(state.dpv.distance(p, HPZero, a, false) * 64); } function MD(a, state) { var stack = state.stack; var pi2 = stack.pop(); var pi1 = stack.pop(); var p2 = state.z1[pi2]; var p1 = state.z0[pi1]; var d = state.dpv.distance(p1, p2, a, a); if (exports.DEBUG) console.log(state.step, "MD[" + a + "]", pi2, pi1, "->", d); state.stack.push(Math.round(d * 64)); } function MPPEM(state) { if (exports.DEBUG) console.log(state.step, "MPPEM[]"); state.stack.push(state.ppem); } function FLIPON(state) { if (exports.DEBUG) console.log(state.step, "FLIPON[]"); state.autoFlip = true; } function LT(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (exports.DEBUG) console.log(state.step, "LT[]", e2, e1); stack.push(e1 < e2 ? 1 : 0); } function LTEQ(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (exports.DEBUG) console.log(state.step, "LTEQ[]", e2, e1); stack.push(e1 <= e2 ? 1 : 0); } function GT(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (exports.DEBUG) console.log(state.step, "GT[]", e2, e1); stack.push(e1 > e2 ? 1 : 0); } function GTEQ(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (exports.DEBUG) console.log(state.step, "GTEQ[]", e2, e1); stack.push(e1 >= e2 ? 1 : 0); } function EQ(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (exports.DEBUG) console.log(state.step, "EQ[]", e2, e1); stack.push(e2 === e1 ? 1 : 0); } function NEQ(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (exports.DEBUG) console.log(state.step, "NEQ[]", e2, e1); stack.push(e2 !== e1 ? 1 : 0); } function ODD(state) { var stack = state.stack; var n = stack.pop(); if (exports.DEBUG) console.log(state.step, "ODD[]", n); stack.push(Math.trunc(n) % 2 ? 1 : 0); } function EVEN(state) { var stack = state.stack; var n = stack.pop(); if (exports.DEBUG) console.log(state.step, "EVEN[]", n); stack.push(Math.trunc(n) % 2 ? 0 : 1); } function IF(state) { var test = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "IF[]", test); if (!test) { skip(state, true); if (exports.DEBUG) console.log(state.step, "EIF[]"); } } function EIF(state) { if (exports.DEBUG) console.log(state.step, "EIF[]"); } function AND(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (exports.DEBUG) console.log(state.step, "AND[]", e2, e1); stack.push(e2 && e1 ? 1 : 0); } function OR(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (exports.DEBUG) console.log(state.step, "OR[]", e2, e1); stack.push(e2 || e1 ? 1 : 0); } function NOT(state) { var stack = state.stack; var e = stack.pop(); if (exports.DEBUG) console.log(state.step, "NOT[]", e); stack.push(e ? 0 : 1); } function DELTAP123(b, state) { var stack = state.stack; var n = stack.pop(); var fv = state.fv; var pv = state.pv; var ppem = state.ppem; var base = state.deltaBase + (b - 1) * 16; var ds = state.deltaShift; var z0 = state.z0; if (exports.DEBUG) console.log(state.step, "DELTAP[" + b + "]", n, stack); for (var i = 0; i < n; i++) { var pi = stack.pop(); var arg = stack.pop(); if (base + ((arg & 240) >> 4) !== ppem) continue; var mag = (arg & 15) - 8; if (mag >= 0) mag++; if (exports.DEBUG) console.log(state.step, "DELTAPFIX", pi, "by", mag * ds); var p = z0[pi]; fv.setRelative(p, p, mag * ds, pv); } } function SDB(state) { var n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SDB[]", n); state.deltaBase = n; } function SDS(state) { var n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SDS[]", n); state.deltaShift = Math.pow(.5, n); } 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 n = stack.pop(); if (exports.DEBUG) console.log(state.step, "ABS[]", n); stack.push(Math.abs(n)); } function NEG(state) { var stack = state.stack; var n = stack.pop(); if (exports.DEBUG) console.log(state.step, "NEG[]", n); stack.push(-n); } function FLOOR(state) { var stack = state.stack; var n = stack.pop(); if (exports.DEBUG) console.log(state.step, "FLOOR[]", n); stack.push(Math.floor(n / 64) * 64); } function CEILING(state) { var stack = state.stack; var n = stack.pop(); if (exports.DEBUG) console.log(state.step, "CEILING[]", n); stack.push(Math.ceil(n / 64) * 64); } function ROUND(dt, state) { var stack = state.stack; var n = stack.pop(); if (exports.DEBUG) console.log(state.step, "ROUND[]"); stack.push(state.round(n / 64) * 64); } function WCVTF(state) { var stack = state.stack; var v = stack.pop(); var l = stack.pop(); if (exports.DEBUG) console.log(state.step, "WCVTF[]", v, l); state.cvt[l] = v * state.ppem / state.font.unitsPerEm; } function DELTAC123(b, state) { var stack = state.stack; var n = stack.pop(); var ppem = state.ppem; var base = state.deltaBase + (b - 1) * 16; var ds = state.deltaShift; if (exports.DEBUG) console.log(state.step, "DELTAC[" + b + "]", n, stack); for (var i = 0; i < n; i++) { var c = stack.pop(); var arg = stack.pop(); if (base + ((arg & 240) >> 4) !== ppem) continue; var mag = (arg & 15) - 8; if (mag >= 0) mag++; var delta = mag * ds; if (exports.DEBUG) console.log(state.step, "DELTACFIX", c, "by", delta); state.cvt[c] += delta; } } function SROUND(state) { var n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SROUND[]", n); state.round = roundSuper; var period; switch (n & 192) { case 0: period = .5; break; case 64: period = 1; break; case 128: period = 2; break; default: throw new Error("invalid SROUND value"); } state.srPeriod = period; switch (n & 48) { case 0: state.srPhase = 0; break; case 16: state.srPhase = .25 * period; break; case 32: state.srPhase = .5 * period; break; case 48: state.srPhase = .75 * period; break; default: throw new Error("invalid SROUND value"); } n &= 15; if (n === 0) state.srThreshold = 0; else state.srThreshold = (n / 8 - .5) * period; } function S45ROUND(state) { var n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "S45ROUND[]", n); state.round = roundSuper; var period; switch (n & 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 (n & 48) { case 0: state.srPhase = 0; break; case 16: state.srPhase = .25 * period; break; case 32: state.srPhase = .5 * period; break; case 48: state.srPhase = .75 * period; break; default: throw new Error("invalid S45ROUND value"); } n &= 15; if (n === 0) state.srThreshold = 0; else state.srThreshold = (n / 8 - .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 n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SCANCTRL[]", n); } function SDPVTL(a, 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[" + a + "]", p2i, p1i); var dx; var dy; if (!a) { dx = p1.x - p2.x; dy = p1.y - p2.y; } else { dx = p2.y - p1.y; dy = p1.x - p2.x; } state.dpv = getUnitVector(dx, dy); } function GETINFO(state) { var stack = state.stack; var sel = stack.pop(); var r = 0; if (exports.DEBUG) console.log(state.step, "GETINFO[]", sel); if (sel & 1) r = 35; if (sel & 32) r |= 4096; stack.push(r); } function ROLL(state) { var stack = state.stack; var a = stack.pop(); var b = stack.pop(); var c = stack.pop(); if (exports.DEBUG) console.log(state.step, "ROLL[]"); stack.push(b); stack.push(a); stack.push(c); } 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 n = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "SCANTYPE[]", n); } function INSTCTRL(state) { var s = state.stack.pop(); var v = state.stack.pop(); if (exports.DEBUG) console.log(state.step, "INSTCTRL[]", s, v); switch (s) { case 1: state.inhibitGridFit = !!v; return; case 2: state.ignoreCvt = !!v; return; default: throw new Error("invalid INSTCTRL[] selector"); } } function PUSHB(n, state) { var stack = state.stack; var prog = state.prog; var ip = state.ip; if (exports.DEBUG) console.log(state.step, "PUSHB[" + n + "]"); for (var i = 0; i < n; i++) stack.push(prog[++ip]); state.ip = ip; } function PUSHW(n, state) { var ip = state.ip; var prog = state.prog; var stack = state.stack; if (exports.DEBUG) console.log(state.ip, "PUSHW[" + n + "]"); for (var i = 0; i < n; i++) { var w = prog[++ip] << 8 | prog[++ip]; if (w & 32768) w = -((w ^ 65535) + 1); stack.push(w); } state.ip = ip; } function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) { var stack = state.stack; var cvte = indirect && stack.pop(); var pi = stack.pop(); var rp0i = state.rp0; var rp = state.z0[rp0i]; var p = state.z1[pi]; var md = state.minDis; var fv = state.fv; var pv = state.dpv; var od; var d; var sign; var cv; d = od = pv.distance(p, rp, true, true); sign = d >= 0 ? 1 : -1; d = Math.abs(d); if (indirect) { cv = state.cvt[cvte]; if (ro && Math.abs(d - cv) < state.cvCutIn) d = cv; } if (keepD && d < md) d = md; if (ro) d = state.round(d); fv.setRelative(p, rp, sign * d, pv); fv.touch(p); if (exports.DEBUG) console.log(state.step, (indirect ? "MIRP[" : "MDRP[") + (setRp0 ? "M" : "m") + (keepD ? ">" : "_") + (ro ? "R" : "_") + (dt === 0 ? "Gr" : dt === 1 ? "Bl" : dt === 2 ? "Wh" : "") + "]", indirect ? cvte + "(" + state.cvt[cvte] + "," + cv + ")" : "", pi, "(d =", od, "->", sign * d, ")"); state.rp1 = state.rp0; state.rp2 = pi; if (setRp0) state.rp0 = pi; } instructionTable = [ SVTCA.bind(void 0, yUnitVector), SVTCA.bind(void 0, xUnitVector), SPVTCA.bind(void 0, yUnitVector), SPVTCA.bind(void 0, xUnitVector), SFVTCA.bind(void 0, yUnitVector), SFVTCA.bind(void 0, xUnitVector), SPVTL.bind(void 0, 0), SPVTL.bind(void 0, 1), SFVTL.bind(void 0, 0), SFVTL.bind(void 0, 1), SPVFS, SFVFS, GPV, GFV, SFVTPV, ISECT, SRP0, SRP1, SRP2, SZP0, SZP1, SZP2, SZPS, SLOOP, RTG, RTHG, SMD, ELSE, JMPR, SCVTCI, void 0, void 0, DUP, POP, CLEAR, SWAP, DEPTH, CINDEX, MINDEX, void 0, void 0, void 0, LOOPCALL, CALL, FDEF, void 0, MDAP.bind(void 0, 0), MDAP.bind(void 0, 1), IUP.bind(void 0, yUnitVector), IUP.bind(void 0, xUnitVector), SHP.bind(void 0, 0), SHP.bind(void 0, 1), SHC.bind(void 0, 0), SHC.bind(void 0, 1), SHZ.bind(void 0, 0), SHZ.bind(void 0, 1), SHPIX, IP, MSIRP.bind(void 0, 0), MSIRP.bind(void 0, 1), ALIGNRP, RTDG, MIAP.bind(void 0, 0), MIAP.bind(void 0, 1), NPUSHB, NPUSHW, WS, RS, WCVTP, RCVT, GC.bind(void 0, 0), GC.bind(void 0, 1), void 0, MD.bind(void 0, 0), MD.bind(void 0, 1), MPPEM, void 0, FLIPON, void 0, void 0, LT, LTEQ, GT, GTEQ, EQ, NEQ, ODD, EVEN, IF, EIF, AND, OR, NOT, DELTAP123.bind(void 0, 1), SDB, SDS, ADD, SUB, DIV, MUL, ABS, NEG, FLOOR, CEILING, ROUND.bind(void 0, 0), ROUND.bind(void 0, 1), ROUND.bind(void 0, 2), ROUND.bind(void 0, 3), void 0, void 0, void 0, void 0, WCVTF, DELTAP123.bind(void 0, 2), DELTAP123.bind(void 0, 3), DELTAC123.bind(void 0, 1), DELTAC123.bind(void 0, 2), DELTAC123.bind(void 0, 3), SROUND, S45ROUND, void 0, void 0, ROFF, void 0, RUTG, RDTG, POP, POP, void 0, void 0, void 0, void 0, void 0, SCANCTRL, SDPVTL.bind(void 0, 0), SDPVTL.bind(void 0, 1), GETINFO, void 0, ROLL, MAX, MIN, SCANTYPE, INSTCTRL, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, PUSHB.bind(void 0, 1), PUSHB.bind(void 0, 2), PUSHB.bind(void 0, 3), PUSHB.bind(void 0, 4), PUSHB.bind(void 0, 5), PUSHB.bind(void 0, 6), PUSHB.bind(void 0, 7), PUSHB.bind(void 0, 8), PUSHW.bind(void 0, 1), PUSHW.bind(void 0, 2), PUSHW.bind(void 0, 3), PUSHW.bind(void 0, 4), PUSHW.bind(void 0, 5), PUSHW.bind(void 0, 6), PUSHW.bind(void 0, 7), PUSHW.bind(void 0, 8), MDRP_MIRP.bind(void 0, 0, 0, 0, 0, 0), MDRP_MIRP.bind(void 0, 0, 0, 0, 0, 1), MDRP_MIRP.bind(void 0, 0, 0, 0, 0, 2), MDRP_MIRP.bind(void 0, 0, 0, 0, 0, 3), MDRP_MIRP.bind(void 0, 0, 0, 0, 1, 0), MDRP_MIRP.bind(void 0, 0, 0, 0, 1, 1), MDRP_MIRP.bind(void 0, 0, 0, 0, 1, 2), MDRP_MIRP.bind(void 0, 0, 0, 0, 1, 3), MDRP_MIRP.bind(void 0, 0, 0, 1, 0, 0), MDRP_MIRP.bind(void 0, 0, 0, 1, 0, 1), MDRP_MIRP.bind(void 0, 0, 0, 1, 0, 2), MDRP_MIRP.bind(void 0, 0, 0, 1, 0, 3), MDRP_MIRP.bind(void 0, 0, 0, 1, 1, 0), MDRP_MIRP.bind(void 0, 0, 0, 1, 1, 1), MDRP_MIRP.bind(void 0, 0, 0, 1, 1, 2), MDRP_MIRP.bind(void 0, 0, 0, 1, 1, 3), MDRP_MIRP.bind(void 0, 0, 1, 0, 0, 0), MDRP_MIRP.bind(void 0, 0, 1, 0, 0, 1), MDRP_MIRP.bind(void 0, 0, 1, 0, 0, 2), MDRP_MIRP.bind(void 0, 0, 1, 0, 0, 3), MDRP_MIRP.bind(void 0, 0, 1, 0, 1, 0), MDRP_MIRP.bind(void 0, 0, 1, 0, 1, 1), MDRP_MIRP.bind(void 0, 0, 1, 0, 1, 2), MDRP_MIRP.bind(void 0, 0, 1, 0, 1, 3), MDRP_MIRP.bind(void 0, 0, 1, 1, 0, 0), MDRP_MIRP.bind(void 0, 0, 1, 1, 0, 1), MDRP_MIRP.bind(void 0, 0, 1, 1, 0, 2), MDRP_MIRP.bind(void 0, 0, 1, 1, 0, 3), MDRP_MIRP.bind(void 0, 0, 1, 1, 1, 0), MDRP_MIRP.bind(void 0, 0, 1, 1, 1, 1), MDRP_MIRP.bind(void 0, 0, 1, 1, 1, 2), MDRP_MIRP.bind(void 0, 0, 1, 1, 1, 3), MDRP_MIRP.bind(void 0, 1, 0, 0, 0, 0), MDRP_MIRP.bind(void 0, 1, 0, 0, 0, 1), MDRP_MIRP.bind(void 0, 1, 0, 0, 0, 2), MDRP_MIRP.bind(void 0, 1, 0, 0, 0, 3), MDRP_MIRP.bind(void 0, 1, 0, 0, 1, 0), MDRP_MIRP.bind(void 0, 1, 0, 0, 1, 1), MDRP_MIRP.bind(void 0, 1, 0, 0, 1, 2), MDRP_MIRP.bind(void 0, 1, 0, 0, 1, 3), MDRP_MIRP.bind(void 0, 1, 0, 1, 0, 0), MDRP_MIRP.bind(void 0, 1, 0, 1, 0, 1), MDRP_MIRP.bind(void 0, 1, 0, 1, 0, 2), MDRP_MIRP.bind(void 0, 1, 0, 1, 0, 3), MDRP_MIRP.bind(void 0, 1, 0, 1, 1, 0), MDRP_MIRP.bind(void 0, 1, 0, 1, 1, 1), MDRP_MIRP.bind(void 0, 1, 0, 1, 1, 2), MDRP_MIRP.bind(void 0, 1, 0, 1, 1, 3), MDRP_MIRP.bind(void 0, 1, 1, 0, 0, 0), MDRP_MIRP.bind(void 0, 1, 1, 0, 0, 1), MDRP_MIRP.bind(void 0, 1, 1, 0, 0, 2), MDRP_MIRP.bind(void 0, 1, 1, 0, 0, 3), MDRP_MIRP.bind(void 0, 1, 1, 0, 1, 0), MDRP_MIRP.bind(void 0, 1, 1, 0, 1, 1), MDRP_MIRP.bind(void 0, 1, 1, 0, 1, 2), MDRP_MIRP.bind(void 0, 1, 1, 0, 1, 3), MDRP_MIRP.bind(void 0, 1, 1, 1, 0, 0), MDRP_MIRP.bind(void 0, 1, 1, 1, 0, 1), MDRP_MIRP.bind(void 0, 1, 1, 1, 0, 2), MDRP_MIRP.bind(void 0, 1, 1, 1, 0, 3), MDRP_MIRP.bind(void 0, 1, 1, 1, 1, 0), MDRP_MIRP.bind(void 0, 1, 1, 1, 1, 1), MDRP_MIRP.bind(void 0, 1, 1, 1, 1, 2), MDRP_MIRP.bind(void 0, 1, 1, 1, 1, 3) ]; function Token(char) { this.char = char; this.state = {}; this.activeState = null; } function ContextRange(startIndex, endOffset, contextName) { this.contextName = contextName; this.startIndex = startIndex; this.endOffset = endOffset; } function ContextChecker(contextName, checkStart, checkEnd) { this.contextName = contextName; this.openRange = null; this.ranges = []; this.checkStart = checkStart; this.checkEnd = checkEnd; } function ContextParams(context, currentIndex) { this.context = context; this.index = currentIndex; this.length = context.length; this.current = context[currentIndex]; this.backtrack = context.slice(0, currentIndex); this.lookahead = context.slice(currentIndex + 1); } function Event(eventId) { this.eventId = eventId; this.subscribers = []; } function initializeCoreEvents(events) { var this$1$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); }); [ "insertToken", "removeToken", "removeRange", "replaceToken", "replaceRange", "composeRUD" ].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(index) { return index >= 0 && index < 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(index, token, silent) { if (!isNaN(index) && this.inboundIndex(index) && token instanceof Token) { var replaced = this.tokens.splice(index, 1, token); if (!silent) this.dispatch("replaceToken", [index, 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(index, silent) { if (!isNaN(index) && this.inboundIndex(index)) { var token = this.tokens.splice(index, 1); if (!silent) this.dispatch("removeToken", [token, index]); return token; } else return { FAIL: "removeToken: invalid token index." }; }; Tokenizer.prototype.insertToken = function(tokens, index, silent) { if (tokens.every(function(token) { return token instanceof Token; })) { this.tokens.splice.apply(this.tokens, [index, 0].concat(tokens)); if (!silent) this.dispatch("insertToken", [tokens, index]); 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(index) { this.index = index; this.current = this.context[index]; this.backtrack = this.context.slice(0, index); this.lookahead = this.context.slice(index + 1); }; ContextParams.prototype.get = function(offset) { switch (true) { case offset === 0: return this.current; case offset < 0 && Math.abs(offset) <= this.backtrack.length: return this.backtrack.slice(offset)[0]; case offset > 0 && offset <= this.lookahead.length: return this.lookahead[offset - 1]; default: return null; } }; Tokenizer.prototype.rangeToText = function(range) { if (range instanceof ContextRange) return this.getRangeTokens(range).map(function(token) { return token.char; }).join(""); }; Tokenizer.prototype.getText = function() { return this.tokens.map(function(token) { return token.char; }).join(""); }; Tokenizer.prototype.getContext = function(contextName) { var context = this.registeredContexts[contextName]; return !!context ? context : null; }; Tokenizer.prototype.on = function(eventName, eventHandler) { var event = this.events[eventName]; if (!!event) return event.subscribe(eventHandler); else return null; }; Tokenizer.prototype.dispatch = function(eventName, args) { var this$1$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 context = this.getContext(contextName); if (!!context) return context.ranges; else return { FAIL: "context checker '" + contextName + "' is not registered." }; }; Tokenizer.prototype.resetContextsRanges = function() { var registeredContexts = this.registeredContexts; for (var contextName in registeredContexts) if (registeredContexts.hasOwnProperty(contextName)) { var context = registeredContexts[contextName]; context.ranges = []; } }; Tokenizer.prototype.updateContextsRanges = function() { this.resetContextsRanges(); var chars = this.tokens.map(function(token) { return token.char; }); for (var i = 0; i < chars.length; i++) { var contextParams = new ContextParams(chars, i); this.runContextCheck(contextParams); } this.dispatch("updateContextsRanges", [this.registeredContexts]); }; Tokenizer.prototype.setEndOffset = function(offset, contextName) { var startIndex = this.getContext(contextName).openRange.startIndex; var range = new ContextRange(startIndex, offset, contextName); var ranges = this.getContext(contextName).ranges; range.rangeId = contextName + "." + ranges.length; ranges.push(range); this.getContext(contextName).openRange = null; return range; }; Tokenizer.prototype.runContextCheck = function(contextParams) { var this$1$1 = this; var index = 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(index, null, contextName); this$1$1.getContext(contextName).openRange = openRange; this$1$1.dispatch("contextStart", [contextName, index]); } if (!!openRange && contextChecker.checkEnd(contextParams)) { var offset = index - 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 i = 0; i < chars.length; i++) { var char = chars[i]; var contextParams = new ContextParams(chars, i); this.dispatch("next", [contextParams]); this.runContextCheck(contextParams); var token = new Token(char); this.tokens.push(token); this.dispatch("newToken", [token, contextParams]); } this.dispatch("end", [this.tokens]); return this.tokens; }; function isArabicChar(c) { return /[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c); } 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(c) { return /[A-z]/.test(c); } function isWhiteSpace(c) { return /\s/.test(c); } function FeatureQuery(font) { this.font = font; this.features = {}; } function SubstitutionAction(action) { this.id = action.id; this.tag = action.tag; this.substitution = action.substitution; } function lookupCoverage(glyphIndex, coverage) { if (!glyphIndex) return -1; switch (coverage.format) { case 1: return coverage.glyphs.indexOf(glyphIndex); case 2: var ranges = coverage.ranges; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (glyphIndex >= range.start && glyphIndex <= range.end) { var offset = glyphIndex - range.start; return range.index + offset; } } break; default: return -1; } return -1; } function singleSubstitutionFormat1(glyphIndex, subtable) { if (lookupCoverage(glyphIndex, subtable.coverage) === -1) return null; return glyphIndex + subtable.deltaGlyphId; } function singleSubstitutionFormat2(glyphIndex, subtable) { var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); if (substituteIndex === -1) return null; return subtable.substitute[substituteIndex]; } function lookupCoverageList(coverageList, contextParams) { var lookupList = []; for (var i = 0; i < coverageList.length; i++) { var coverage = coverageList[i]; var glyphIndex = contextParams.current; glyphIndex = Array.isArray(glyphIndex) ? glyphIndex[0] : glyphIndex; var lookupIndex = lookupCoverage(glyphIndex, coverage); if (lookupIndex !== -1) lookupList.push(lookupIndex); } if (lookupList.length !== coverageList.length) return -1; return lookupList; } function chainingSubstitutionFormat3(contextParams, subtable) { var lookupsCount = subtable.inputCoverage.length + subtable.lookaheadCoverage.length + subtable.backtrackCoverage.length; if (contextParams.context.length < lookupsCount) return []; var inputLookups = lookupCoverageList(subtable.inputCoverage, contextParams); if (inputLookups === -1) return []; var lookaheadOffset = subtable.inputCoverage.length - 1; if (contextParams.lookahead.length < subtable.lookaheadCoverage.length) return []; var lookaheadContext = contextParams.lookahead.slice(lookaheadOffset); while (lookaheadContext.length && isTashkeelArabicChar(lookaheadContext[0].char)) lookaheadContext.shift(); var lookaheadParams = new ContextParams(lookaheadContext, 0); var lookaheadLookups = lookupCoverageList(subtable.lookaheadCoverage, lookaheadParams); var backtrackContext = [].concat(contextParams.backtrack); backtrackContext.reverse(); while (backtrackContext.length && isTashkeelArabicChar(backtrackContext[0].char)) backtrackContext.shift(); if (backtrackContext.length < subtable.backtrackCoverage.length) return []; var backtrackParams = new ContextParams(backtrackContext, 0); var backtrackLookups = lookupCoverageList(subtable.backtrackCoverage, backtrackParams); var contextRulesMatch = inputLookups.length === subtable.inputCoverage.length && lookaheadLookups.length === subtable.lookaheadCoverage.length && backtrackLookups.length === subtable.backtrackCoverage.length; var substitutions = []; if (contextRulesMatch) for (var i = 0; i < subtable.lookupRecords.length; i++) { var lookupListIndex = subtable.lookupRecords[i].lookupListIndex; var lookupTable = this.getLookupByIndex(lookupListIndex); for (var s = 0; s < lookupTable.subtables.length; s++) { var subtable$1 = lookupTable.subtables[s]; var lookup = this.getLookupMethod(lookupTable, subtable$1); if (this.getSubstitutionType(lookupTable, subtable$1) === "12") for (var n = 0; n < inputLookups.length; n++) { var substitution = lookup(contextParams.get(n)); if (substitution) substitutions.push(substitution); } } } return substitutions; } function ligatureSubstitutionFormat1(contextParams, subtable) { var glyphIndex = contextParams.current; var ligSetIndex = lookupCoverage(glyphIndex, subtable.coverage); if (ligSetIndex === -1) return null; var ligature; var ligatureSet = subtable.ligatureSets[ligSetIndex]; for (var s = 0; s < ligatureSet.length; s++) { ligature = ligatureSet[s]; for (var l = 0; l < ligature.components.length; l++) { if (contextParams.lookahead[l] !== ligature.components[l]) break; if (l === ligature.components.length - 1) return ligature; } } return null; } function decompositionSubstitutionFormat1(glyphIndex, subtable) { var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); if (substituteIndex === -1) return null; return subtable.sequences[substituteIndex]; } FeatureQuery.prototype.getDefaultScriptFeaturesIndexes = function() { var scripts = this.font.tables.gsub.scripts; for (var s = 0; s < scripts.length; s++) { var script = scripts[s]; if (script.tag === "DFLT") return script.script.defaultLangSys.featureIndexes; } return []; }; FeatureQuery.prototype.getScriptFeaturesIndexes = function(scriptTag) { if (!this.font.tables.gsub) return []; if (!scriptTag) return this.getDefaultScriptFeaturesIndexes(); var scripts = this.font.tables.gsub.scripts; for (var i = 0; i < scripts.length; i++) { var script = scripts[i]; if (script.tag === scriptTag && script.script.defaultLangSys) return script.script.defaultLangSys.featureIndexes; else { var langSysRecords = script.langSysRecords; if (!!langSysRecords) for (var j = 0; j < langSysRecords.length; j++) { var langSysRecord = langSysRecords[j]; if (langSysRecord.tag === scriptTag) return langSysRecord.langSys.featureIndexes; } } } return this.getDefaultScriptFeaturesIndexes(); }; FeatureQuery.prototype.mapTagsToFeatures = function(features, scriptTag) { var tags = {}; for (var i = 0; i < features.length; i++) { var tag = features[i].tag; tags[tag] = features[i].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(index) { return gsub2.features[index]; }); this.features[scriptTag] = features; this.mapTagsToFeatures(features, scriptTag); return features; }; FeatureQuery.prototype.getSubstitutionType = function(lookupTable, subtable) { return lookupTable.lookupType.toString() + subtable.substFormat.toString(); }; FeatureQuery.prototype.getLookupMethod = function(lookupTable, subtable) { var this$1$1 = this; switch (this.getSubstitutionType(lookupTable, subtable)) { 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 /* @__PURE__ */ 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 l = 0; l < lookups.length; l++) { var lookupTable = lookups[l]; var subtables = this.getLookupSubtables(lookupTable); for (var s = 0; s < subtables.length; s++) { var subtable = subtables[s]; var substType = this.getSubstitutionType(lookupTable, subtable); var lookup = this.getLookupMethod(lookupTable, subtable); var substitution = void 0; switch (substType) { case "11": substitution = lookup(contextParams.current); if (substitution) substitutions.splice(currentIndex, 1, new SubstitutionAction({ id: 11, tag: query.tag, substitution })); break; case "12": substitution = lookup(contextParams.current); if (substitution) substitutions.splice(currentIndex, 1, new SubstitutionAction({ id: 12, tag: query.tag, substitution })); break; case "63": substitution = lookup(contextParams); if (Array.isArray(substitution) && substitution.length) substitutions.splice(currentIndex, 1, new SubstitutionAction({ id: 63, tag: query.tag, substitution })); break; case "41": substitution = lookup(contextParams); if (substitution) substitutions.splice(currentIndex, 1, new SubstitutionAction({ id: 41, tag: query.tag, substitution })); break; case "21": substitution = lookup(contextParams.current); if (substitution) substitutions.splice(currentIndex, 1, new SubstitutionAction({ id: 21, tag: query.tag, substitution })); break; } contextParams = new ContextParams(substitutions, currentIndex); if (Array.isArray(substitution) && !substitution.length) continue; substitution = null; } } return substitutions.length ? substitutions : null; }; FeatureQuery.prototype.supports = function(query) { if (!query.script) return false; this.getScriptFeatures(query.script); var supportedScript = this.features.hasOwnProperty(query.script); if (!query.tag) return supportedScript; var supportedFeature = this.features[query.script].some(function(feature) { return feature.tag === query.tag; }); return supportedScript && supportedFeature; }; FeatureQuery.prototype.getLookupSubtables = function(lookupTable) { return lookupTable.subtables || null; }; FeatureQuery.prototype.getLookupByIndex = function(index) { return this.font.tables.gsub.lookups[index] || 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 prevChar === null && isArabicChar(char) || !isArabicChar(prevChar) && isArabicChar(char); } function arabicWordEndCheck(contextParams) { var nextChar = contextParams.get(1); return nextChar === null || !isArabicChar(nextChar); } var arabicWordCheck = { startCheck: arabicWordStartCheck, endCheck: arabicWordEndCheck }; function arabicSentenceStartCheck(contextParams) { var char = contextParams.current; var prevChar = contextParams.get(-1); return (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(c) { return isArabicChar(c) || isTashkeelArabicChar(c); }); if (!arabicCharAhead) return true; } break; default: return false; } } var arabicSentenceCheck = { startCheck: arabicSentenceStartCheck, endCheck: arabicSentenceEndCheck }; function singleSubstitutionFormat1$1(action, tokens, index) { tokens[index].setState(action.tag, action.substitution); } function singleSubstitutionFormat2$1(action, tokens, index) { tokens[index].setState(action.tag, action.substitution); } function chainingSubstitutionFormat3$1(action, tokens, index) { action.substitution.forEach(function(subst, offset) { tokens[index + offset].setState(action.tag, subst); }); } function ligatureSubstitutionFormat1$1(action, tokens, index) { var token = tokens[index]; token.setState(action.tag, action.substitution.ligGlyph); var compsCount = action.substitution.components.length; for (var i = 0; i < compsCount; i++) { token = tokens[index + i + 1]; token.setState("deleted", true); } } var SUBSTITUTIONS = { 11: singleSubstitutionFormat1$1, 12: singleSubstitutionFormat2$1, 63: chainingSubstitutionFormat3$1, 41: ligatureSubstitutionFormat1$1 }; function applySubstitution(action, tokens, index) { if (action instanceof SubstitutionAction && SUBSTITUTIONS[action.id]) SUBSTITUTIONS[action.id](action, tokens, index); } function willConnectPrev(charContextParams) { var backtrack = [].concat(charContextParams.backtrack); for (var i = backtrack.length - 1; i >= 0; i--) { var prevChar = backtrack[i]; var isolated = isIsolatedArabicChar(prevChar); var tashkeel = isTashkeelArabicChar(prevChar); if (!isolated && !tashkeel) return true; if (isolated) return false; } return false; } function willConnectNext(charContextParams) { if (isIsolatedArabicChar(charContextParams.current)) return false; for (var i = 0; i < charContextParams.lookahead.length; i++) { var nextChar = charContextParams.lookahead[i]; if (!isTashkeelArabicChar(nextChar)) 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, index) { if (isTashkeelArabicChar(token.char)) return; contextParams.setCurrentIndex(index); charContextParams.setCurrentIndex(index); 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, index2) { if (action instanceof SubstitutionAction) { applySubstitution(action, tokens, index2); contextParams.context[index2] = action.substitution; } }); }); } function getContextParams(tokens, index) { return new ContextParams(tokens.map(function(token) { return token.activeState.value; }), index || 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, index) { contextParams.setCurrentIndex(index); var substitutions = this$1$1.query.lookupFeature({ tag: "rlig", script, contextParams }); if (substitutions.length) { substitutions.forEach(function(action) { return applySubstitution(action, tokens, index); }); contextParams = getContextParams(tokens); } }); } function latinWordStartCheck(contextParams) { var char = contextParams.current; var prevChar = contextParams.get(-1); return prevChar === null && isLatinChar(char) || !isLatinChar(prevChar) && isLatinChar(char); } function latinWordEndCheck(contextParams) { var nextChar = contextParams.get(1); return nextChar === null || !isLatinChar(nextChar); } var latinWordCheck = { startCheck: latinWordStartCheck, endCheck: latinWordEndCheck }; function getContextParams$1(tokens, index) { return new ContextParams(tokens.map(function(token) { return token.activeState.value; }), index || 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, index) { contextParams.setCurrentIndex(index); var substitutions = this$1$1.query.lookupFeature({ tag: "liga", script, contextParams }); if (substitutions.length) { substitutions.forEach(function(action) { return applySubstitution(action, tokens, index); }); 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; this.tokenizer.getContextRanges("arabicSentence").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 f = 0; f < features.length; f++) { var feature = features[f]; if (!this.query.supports({ script: feature.script })) continue; this.registerFeatures(feature.script, feature.tags); } }; Bidi.prototype.registerModifier = function(modifierId, condition, modifier) { this.tokenizer.registerModifier(modifierId, condition, modifier); }; function checkGlyphIndexStatus() { if (this.tokenizer.registeredModifiers.indexOf("glyphIndex") === -1) throw new Error("glyphIndex modifier is required to apply arabic presentation features."); } function applyArabicPresentationForms() { var this$1$1 = this; if (!this.featuresTags.hasOwnProperty("arab")) return; checkGlyphIndexStatus.call(this); this.tokenizer.getContextRanges("arabicWord").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; if (this.featuresTags[script].indexOf("rlig") === -1) return; checkGlyphIndexStatus.call(this); this.tokenizer.getContextRanges("arabicWord").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; if (this.featuresTags[script].indexOf("liga") === -1) return; checkGlyphIndexStatus.call(this); this.tokenizer.getContextRanges("latinWord").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 i = 0; i < this.tokenizer.tokens.length; i++) { var token = this.tokenizer.tokens[i]; if (token.state.deleted) continue; var index = token.activeState.value; indexes.push(Array.isArray(index) ? index[0] : index); } return indexes; }; function Font(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: { 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); } }); } Font.prototype.hasChar = function(c) { return this.encoding.charToGlyphIndex(c) !== null; }; Font.prototype.charToGlyphIndex = function(s) { return this.encoding.charToGlyphIndex(s); }; Font.prototype.charToGlyph = function(c) { var glyphIndex = this.charToGlyphIndex(c); var glyph = this.glyphs.get(glyphIndex); if (!glyph) glyph = this.glyphs.get(0); return glyph; }; Font.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; }); }; Font.prototype.stringToGlyphs = function(s, 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(s); var length = indexes.length; var glyphs = new Array(length); var notdef = this.glyphs.get(0); for (var i = 0; i < length; i += 1) glyphs[i] = this.glyphs.get(indexes[i]) || notdef; return glyphs; }; Font.prototype.nameToGlyphIndex = function(name) { return this.glyphNames.nameToGlyphIndex(name); }; Font.prototype.nameToGlyph = function(name) { var glyphIndex = this.nameToGlyphIndex(name); var glyph = this.glyphs.get(glyphIndex); if (!glyph) glyph = this.glyphs.get(0); return glyph; }; Font.prototype.glyphIndexToName = function(gid) { if (!this.glyphNames.glyphIndexToName) return ""; return this.glyphNames.glyphIndexToName(gid); }; Font.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; }; Font.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"] }] }; Font.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 i = 0; i < glyphs.length; i += 1) { var glyph = glyphs[i]; callback.call(this, glyph, x, y, fontSize, options); if (glyph.advanceWidth) x += glyph.advanceWidth * fontScale; if (options.kerning && i < glyphs.length - 1) { var kerningValue = kerningLookups ? this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) : this.getKerningValue(glyph, glyphs[i + 1]); x += kerningValue * fontScale; } if (options.letterSpacing) x += options.letterSpacing * fontSize; else if (options.tracking) x += options.tracking / 1e3 * fontSize; } return x; }; Font.prototype.getPath = function(text, x, y, fontSize, options) { var fullPath = new Path(); 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; }; Font.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; }; Font.prototype.getAdvanceWidth = function(text, fontSize, options) { return this.forEachGlyph(text, 0, 0, fontSize, options, function() {}); }; Font.prototype.draw = function(ctx, text, x, y, fontSize, options) { this.getPath(text, x, y, fontSize, options).draw(ctx); }; Font.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); }); }; Font.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); }); }; Font.prototype.getEnglishName = function(name) { var translations = this.names[name]; if (translations) return translations.en; }; Font.prototype.validate = function() { var _this = this; function assertNamePresent(name) { var englishName = _this.getEnglishName(name); englishName && englishName.trim().length; } assertNamePresent("fontFamily"); assertNamePresent("weightName"); assertNamePresent("manufacturer"); assertNamePresent("copyright"); assertNamePresent("version"); this.unitsPerEm; }; Font.prototype.toTables = function() { return sfnt.fontToTable(this); }; Font.prototype.toBuffer = function() { console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead."); return this.toArrayBuffer(); }; Font.prototype.toArrayBuffer = function() { var bytes = this.toTables().encode(); var buffer = new ArrayBuffer(bytes.length); var intArray = new Uint8Array(buffer); for (var i = 0; i < bytes.length; i++) intArray[i] = bytes[i]; return buffer; }; Font.prototype.fsSelectionValues = { ITALIC: 1, UNDERSCORE: 2, NEGATIVE: 4, OUTLINED: 8, STRIKEOUT: 16, BOLD: 32, REGULAR: 64, USER_TYPO_METRICS: 128, WWS: 256, OBLIQUE: 512 }; Font.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 }; Font.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 n = parseInt(nameKey); if (!n || n < 256) continue; if (JSON.stringify(names[nameKey]) === nameString) return n; if (nameID <= n) nameID = n + 1; } names[nameID] = name; return nameID; } function makeFvarAxis(n, axis, names) { var nameID = addName(axis.name, names); return [ { name: "tag_" + n, type: "TAG", value: axis.tag }, { name: "minValue_" + n, type: "FIXED", value: axis.minValue << 16 }, { name: "defaultValue_" + n, type: "FIXED", value: axis.defaultValue << 16 }, { name: "maxValue_" + n, type: "FIXED", value: axis.maxValue << 16 }, { name: "flags_" + n, type: "USHORT", value: 0 }, { name: "nameID_" + n, type: "USHORT", value: nameID } ]; } function parseFvarAxis(data, start, names) { var axis = {}; var p = new parse.Parser(data, start); axis.tag = p.parseTag(); axis.minValue = p.parseFixed(); axis.defaultValue = p.parseFixed(); axis.maxValue = p.parseFixed(); p.skip("uShort", 1); axis.name = names[p.parseUShort()] || {}; return axis; } function makeFvarInstance(n, inst, axes, names) { var nameID = addName(inst.name, names); var fields = [{ name: "nameID_" + n, type: "USHORT", value: nameID }, { name: "flags_" + n, type: "USHORT", value: 0 }]; for (var i = 0; i < axes.length; ++i) { var axisTag = axes[i].tag; fields.push({ name: "axis_" + n + " " + axisTag, type: "FIXED", value: inst.coordinates[axisTag] << 16 }); } return fields; } function parseFvarInstance(data, start, axes, names) { var inst = {}; var p = new parse.Parser(data, start); inst.name = names[p.parseUShort()] || {}; p.skip("uShort", 1); inst.coordinates = {}; for (var i = 0; i < axes.length; ++i) inst.coordinates[axes[i].tag] = p.parseFixed(); return inst; } function makeFvarTable(fvar2, names) { var result = new table.Table("fvar", [ { name: "version", type: "ULONG", value: 65536 }, { name: "offsetToData", type: "USHORT", value: 0 }, { name: "countSizePairs", type: "USHORT", value: 2 }, { name: "axisCount", type: "USHORT", value: fvar2.axes.length }, { name: "axisSize", type: "USHORT", value: 20 }, { name: "instanceCount", type: "USHORT", value: fvar2.instances.length }, { name: "instanceSize", type: "USHORT", value: 4 + fvar2.axes.length * 4 } ]); result.offsetToData = result.sizeOf(); for (var i = 0; i < fvar2.axes.length; i++) result.fields = result.fields.concat(makeFvarAxis(i, fvar2.axes[i], names)); for (var 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 p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 65536, "Unsupported fvar table version."); var offsetToData = p.parseOffset16(); p.skip("uShort", 1); var axisCount = p.parseUShort(); var axisSize = p.parseUShort(); var instanceCount = p.parseUShort(); var instanceSize = p.parseUShort(); var axes = []; for (var i = 0; i < axisCount; i++) axes.push(parseFvarAxis(data, start + offsetToData + i * 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(Parser.coverage), attachPoints: this.parseList(Parser.pointer(Parser.uShortList)) }; }; var caretValue = function() { var format = this.parseUShort(); check.argument(format === 1 || format === 2 || format === 3, "Unsupported CaretValue table version."); if (format === 1) return { coordinate: this.parseShort() }; else if (format === 2) return { pointindex: this.parseShort() }; else if (format === 3) return { coordinate: this.parseShort() }; }; var ligGlyph = function() { return this.parseList(Parser.pointer(caretValue)); }; var ligCaretList = function() { return { coverage: this.parsePointer(Parser.coverage), ligGlyphs: this.parseList(Parser.pointer(ligGlyph)) }; }; var markGlyphSets = function() { this.parseUShort(); return this.parseList(Parser.pointer(Parser.coverage)); }; function parseGDEFTable(data, start) { start = start || 0; var p = new Parser(data, start); var tableVersion = p.parseVersion(1); check.argument(tableVersion === 1 || tableVersion === 1.2 || tableVersion === 1.3, "Unsupported GDEF table version."); var gdef2 = { version: tableVersion, classDef: p.parsePointer(Parser.classDef), attachList: p.parsePointer(attachList), ligCaretList: p.parsePointer(ligCaretList), markAttachClassDef: p.parsePointer(Parser.classDef) }; if (tableVersion >= 1.2) gdef2.markGlyphSets = p.parsePointer(markGlyphSets); return gdef2; } var gdef = { parse: parseGDEFTable }; var subtableParsers$1 = new Array(10); subtableParsers$1[1] = function parseLookup1() { var start = this.offset + this.relativeOffset; var posformat = this.parseUShort(); if (posformat === 1) return { posFormat: 1, coverage: this.parsePointer(Parser.coverage), value: this.parseValueRecord() }; else if (posformat === 2) return { posFormat: 2, coverage: this.parsePointer(Parser.coverage), values: this.parseValueRecordList() }; check.assert(false, "0x" + start.toString(16) + ": GPOS lookup type 1 format must be 1 or 2."); }; subtableParsers$1[2] = function 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(Parser.coverage); var valueFormat1 = this.parseUShort(); var valueFormat2 = this.parseUShort(); if (posFormat === 1) return { posFormat, coverage, valueFormat1, valueFormat2, pairSets: this.parseList(Parser.pointer(Parser.list(function() { return { secondGlyph: this.parseUShort(), value1: this.parseValueRecord(valueFormat1), value2: this.parseValueRecord(valueFormat2) }; }))) }; else if (posFormat === 2) { var classDef1 = this.parsePointer(Parser.classDef); var classDef2 = this.parsePointer(Parser.classDef); var class1Count = this.parseUShort(); var class2Count = this.parseUShort(); return { posFormat, coverage, valueFormat1, valueFormat2, classDef1, classDef2, class1Count, class2Count, classRecords: this.parseList(class1Count, Parser.list(class2Count, function() { return { value1: this.parseValueRecord(valueFormat1), value2: this.parseValueRecord(valueFormat2) }; })) }; } }; subtableParsers$1[3] = function 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 p = new Parser(data, start); var tableVersion = p.parseVersion(1); check.argument(tableVersion === 1 || tableVersion === 1.1, "Unsupported GPOS table version " + tableVersion); if (tableVersion === 1) return { version: tableVersion, scripts: p.parseScriptList(), features: p.parseFeatureList(), lookups: p.parseLookupList(subtableParsers$1) }; else return { version: tableVersion, scripts: p.parseScriptList(), features: p.parseFeatureList(), lookups: p.parseLookupList(subtableParsers$1), variations: p.parseFeatureVariationsList() }; } var subtableMakers$1 = new Array(10); function makeGposTable(gpos2) { return new table.Table("GPOS", [ { name: "version", type: "ULONG", value: 65536 }, { name: "scripts", type: "TABLE", value: new table.ScriptList(gpos2.scripts) }, { name: "features", type: "TABLE", value: new table.FeatureList(gpos2.features) }, { name: "lookups", type: "TABLE", value: new table.LookupList(gpos2.lookups, subtableMakers$1) } ]); } var gpos = { parse: parseGposTable, make: makeGposTable }; function parseWindowsKernTable(p) { var pairs = {}; p.skip("uShort"); var subtableVersion = p.parseUShort(); check.argument(subtableVersion === 0, "Unsupported kern sub-table version."); p.skip("uShort", 2); var nPairs = p.parseUShort(); p.skip("uShort", 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + "," + rightIndex] = value; } return pairs; } function parseMacKernTable(p) { var pairs = {}; p.skip("uShort"); if (p.parseULong() > 1) console.warn("Only the first kern subtable is supported."); p.skip("uLong"); var subtableVersion = p.parseUShort() & 255; p.skip("uShort"); if (subtableVersion === 0) { var nPairs = p.parseUShort(); p.skip("uShort", 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + "," + rightIndex] = value; } } return pairs; } function parseKernTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseUShort(); if (tableVersion === 0) return parseWindowsKernTable(p); else if (tableVersion === 1) return parseMacKernTable(p); else throw new Error("Unsupported kern table version (" + tableVersion + ")."); } var kern = { parse: parseKernTable }; function parseLocaTable(data, start, numGlyphs, shortVersion) { var p = new parse.Parser(data, start); var parseFn = shortVersion ? p.parseUShort : p.parseULong; var glyphOffsets = []; for (var i = 0; i < numGlyphs + 1; i += 1) { var glyphOffset = parseFn.call(p); if (shortVersion) glyphOffset *= 2; glyphOffsets.push(glyphOffset); } return glyphOffsets; } var loca = { parse: parseLocaTable }; function parseOpenTypeTableEntries(data, numTables) { var tableEntries = []; var p = 12; for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var checksum = parse.getULong(data, p + 4); var offset = parse.getULong(data, p + 8); var length = parse.getULong(data, p + 12); tableEntries.push({ tag, checksum, offset, length, compression: false }); p += 16; } return tableEntries; } function parseWOFFTableEntries(data, numTables) { var tableEntries = []; var p = 44; for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var offset = parse.getULong(data, p + 4); var compLength = parse.getULong(data, p + 8); var origLength = parse.getULong(data, p + 12); var compression = void 0; if (compLength < origLength) compression = "WOFF"; else compression = false; tableEntries.push({ tag, offset, compression, compressedLength: compLength, length: origLength }); p += 20; } return tableEntries; } function uncompressTable(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"); return { data: new DataView(outBuffer.buffer, 0), offset: 0 }; } else return { data, offset: tableEntry.offset }; } function parseBuffer2(buffer, opt) { opt = opt === void 0 || opt === null ? {} : opt; var indexToLocFormat; var ltagTable; var font = new Font({ empty: true }); var data = new DataView(buffer, 0); var numTables; var tableEntries = []; var signature = parse.getTag(data, 0); if (signature === String.fromCharCode(0, 1, 0, 0) || signature === "true" || signature === "typ1") { font.outlinesFormat = "truetype"; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === "OTTO") { font.outlinesFormat = "cff"; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === "wOFF") { var flavor = parse.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 = parse.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 p; for (var i = 0; i < numTables; i += 1) { var tableEntry = tableEntries[i]; 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); p = new parse.Parser(table2.data, table2.offset); font.tables.cvt = p.parseShortList(tableEntry.length / 2); break; case "fvar": fvarTableEntry = tableEntry; break; case "fpgm": table2 = uncompressTable(data, tableEntry); p = new parse.Parser(table2.data, table2.offset); font.tables.fpgm = p.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); p = new parse.Parser(table2.data, table2.offset); font.tables.prep = p.parseByteList(tableEntry.length); break; case "glyf": glyfTableEntry = tableEntry; break; case "loca": locaTableEntry = tableEntry; break; case "CFF ": cffTableEntry = tableEntry; break; case "kern": kernTableEntry = tableEntry; break; case "GDEF": gdefTableEntry = tableEntry; break; case "GPOS": gposTableEntry = tableEntry; break; case "GSUB": gsubTableEntry = tableEntry; break; case "meta": metaTableEntry = tableEntry; break; } } var nameTable = uncompressTable(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 }; })(); //#endregion //#region node_modules/three-stdlib/loaders/TTFLoader.js var TTFLoader = class extends Loader { constructor(manager) { super(manager); this.reversed = false; } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function(buffer) { try { onLoad(parseBuffer(buffer)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(arraybuffer) { function convert(font, reversed) { const round = Math.round; const glyphs = {}; const scale = 1e5 / ((font.unitsPerEm || 2048) * 72); const glyphIndexMap = font.encoding.cmap.glyphIndexMap; const unicodes = Object.keys(glyphIndexMap); for (let i = 0; i < unicodes.length; i++) { const unicode = unicodes[i]; const glyph = font.glyphs.glyphs[glyphIndexMap[unicode]]; if (unicode !== void 0) { const token = { ha: round(glyph.advanceWidth * scale), x_min: round(glyph.xMin * scale), x_max: round(glyph.xMax * scale), o: "" }; if (reversed) glyph.path.commands = reverseCommands(glyph.path.commands); glyph.path.commands.forEach(function(command) { if (command.type.toLowerCase() === "c") command.type = "b"; token.o += command.type.toLowerCase() + " "; if (command.x !== void 0 && command.y !== void 0) token.o += round(command.x * scale) + " " + round(command.y * scale) + " "; if (command.x1 !== void 0 && command.y1 !== void 0) token.o += round(command.x1 * scale) + " " + round(command.y1 * scale) + " "; if (command.x2 !== void 0 && command.y2 !== void 0) token.o += round(command.x2 * scale) + " " + round(command.y2 * scale) + " "; }); glyphs[String.fromCodePoint(glyph.unicode)] = token; } } return { glyphs, familyName: font.getEnglishName("fullName"), ascender: round(font.ascender * scale), descender: round(font.descender * scale), underlinePosition: font.tables.post.underlinePosition, underlineThickness: font.tables.post.underlineThickness, boundingBox: { xMin: font.tables.head.xMin, xMax: font.tables.head.xMax, yMin: font.tables.head.yMin, yMax: font.tables.head.yMax }, resolution: 1e3, original_font_information: font.tables.name }; } function reverseCommands(commands) { const paths = []; let path; commands.forEach(function(c) { if (c.type.toLowerCase() === "m") { path = [c]; paths.push(path); } else if (c.type.toLowerCase() !== "z") path.push(c); }); const reversed = []; paths.forEach(function(p) { const result = { type: "m", x: p[p.length - 1].x, y: p[p.length - 1].y }; reversed.push(result); for (let i = p.length - 1; i > 0; i--) { const command = p[i]; const result2 = { type: command.type }; if (command.x2 !== void 0 && command.y2 !== void 0) { result2.x1 = command.x2; result2.y1 = command.y2; result2.x2 = command.x1; result2.y2 = command.y1; } else if (command.x1 !== void 0 && command.y1 !== void 0) { result2.x1 = command.x1; result2.y1 = command.y1; } result2.x = p[i - 1].x; result2.y = p[i - 1].y; reversed.push(result2); } }); return reversed; } return convert(parseBuffer(arraybuffer), this.reversed); } }; //#endregion //#region node_modules/three-stdlib/loaders/RGBELoader.js var RGBELoader = class extends DataTextureLoader { constructor(manager) { super(manager); this.type = HalfFloatType; } parse(buffer) { const rgbe_read_error = 1, rgbe_write_error = 2, rgbe_format_error = 3, rgbe_memory_error = 4, rgbe_error = function(rgbe_error_code, msg) { switch (rgbe_error_code) { case rgbe_read_error: throw new Error("THREE.RGBELoader: Read Error: " + (msg || "")); case rgbe_write_error: throw new Error("THREE.RGBELoader: Write Error: " + (msg || "")); case rgbe_format_error: throw new Error("THREE.RGBELoader: Bad File Format: " + (msg || "")); default: case rgbe_memory_error: throw new Error("THREE.RGBELoader: Memory Error: " + (msg || "")); } }, RGBE_VALID_PROGRAMTYPE = 1, RGBE_VALID_FORMAT = 2, RGBE_VALID_DIMENSIONS = 4, NEWLINE = "\n", fgets = function(buffer2, lineLimit, consume) { const chunkSize = 128; lineLimit = !lineLimit ? 1024 : lineLimit; let p = buffer2.pos, i = -1, len = 0, s = "", chunk = String.fromCharCode.apply(null, new Uint16Array(buffer2.subarray(p, p + chunkSize))); while (0 > (i = chunk.indexOf(NEWLINE)) && len < lineLimit && p < buffer2.byteLength) { s += chunk; len += chunk.length; p += chunkSize; chunk += String.fromCharCode.apply(null, new Uint16Array(buffer2.subarray(p, p + chunkSize))); } if (-1 < i) { if (false !== consume) buffer2.pos += len + i + 1; return s + chunk.slice(0, i); } return false; }, RGBE_ReadHeader = function(buffer2) { const magic_token_re = /^#\?(\S+)/, gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/, exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/, format_re = /^\s*FORMAT=(\S+)\s*$/, dimensions_re = /^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/, header = { valid: 0, string: "", comments: "", programtype: "RGBE", format: "", gamma: 1, exposure: 1, width: 0, height: 0 }; let line, match; if (buffer2.pos >= buffer2.byteLength || !(line = fgets(buffer2))) 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(buffer2); 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(buffer2, w2, h2) { const scanline_width = w2; if (scanline_width < 8 || scanline_width > 32767 || 2 !== buffer2[0] || 2 !== buffer2[1] || buffer2[2] & 128) return new Uint8Array(buffer2); if (scanline_width !== (buffer2[2] << 8 | buffer2[3])) rgbe_error(rgbe_format_error, "wrong scanline width"); const data_rgba = new Uint8Array(4 * w2 * h2); if (!data_rgba.length) rgbe_error(rgbe_memory_error, "unable to allocate buffer space"); let offset = 0, pos = 0; const ptr_end = 4 * scanline_width; const rgbeStart = new Uint8Array(4); const scanline_buffer = new Uint8Array(ptr_end); let num_scanlines = h2; while (num_scanlines > 0 && pos < buffer2.byteLength) { if (pos + 4 > buffer2.byteLength) rgbe_error(rgbe_read_error); rgbeStart[0] = buffer2[pos++]; rgbeStart[1] = buffer2[pos++]; rgbeStart[2] = buffer2[pos++]; rgbeStart[3] = buffer2[pos++]; if (2 != rgbeStart[0] || 2 != rgbeStart[1] || (rgbeStart[2] << 8 | rgbeStart[3]) != scanline_width) rgbe_error(rgbe_format_error, "bad rgbe scanline format"); let ptr = 0, count; while (ptr < ptr_end && pos < buffer2.byteLength) { count = buffer2[pos++]; const isEncodedRun = count > 128; if (isEncodedRun) count -= 128; if (0 === count || ptr + count > ptr_end) rgbe_error(rgbe_format_error, "bad scanline data"); if (isEncodedRun) { const byteValue = buffer2[pos++]; for (let i = 0; i < count; i++) scanline_buffer[ptr++] = byteValue; } else { scanline_buffer.set(buffer2.subarray(pos, pos + count), ptr); ptr += count; pos += count; } } const l = scanline_width; for (let i = 0; i < l; i++) { let off = 0; data_rgba[offset] = scanline_buffer[i + off]; off += scanline_width; data_rgba[offset + 1] = scanline_buffer[i + off]; off += scanline_width; data_rgba[offset + 2] = scanline_buffer[i + off]; off += scanline_width; data_rgba[offset + 3] = scanline_buffer[i + off]; offset += 4; } num_scanlines--; } return data_rgba; }; const RGBEByteToRGBFloat = function(sourceArray, sourceOffset, destArray, destOffset) { const e = sourceArray[sourceOffset + 3]; const scale = Math.pow(2, e - 128) / 255; destArray[destOffset + 0] = sourceArray[sourceOffset + 0] * scale; destArray[destOffset + 1] = sourceArray[sourceOffset + 1] * scale; destArray[destOffset + 2] = sourceArray[sourceOffset + 2] * scale; destArray[destOffset + 3] = 1; }; const RGBEByteToRGBHalf = function(sourceArray, sourceOffset, destArray, destOffset) { const e = sourceArray[sourceOffset + 3]; const scale = Math.pow(2, e - 128) / 255; destArray[destOffset + 0] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 0] * scale, 65504)); destArray[destOffset + 1] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 1] * scale, 65504)); destArray[destOffset + 2] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 2] * scale, 65504)); destArray[destOffset + 3] = DataUtils.toHalfFloat(1); }; const byteArray = new Uint8Array(buffer); byteArray.pos = 0; const rgbe_header_info = RGBE_ReadHeader(byteArray); const w = rgbe_header_info.width, h = rgbe_header_info.height, image_rgba_data = RGBE_ReadPixels_RLE(byteArray.subarray(byteArray.pos), w, h); let 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); } }; //#endregion //#region node_modules/three-stdlib/loaders/AssimpLoader.js var AssimpLoader = class extends Loader { load(url, onLoad, onProgress, onError) { var scope = this; var path = scope.path === "" ? LoaderUtils.extractUrlBase(url) : scope.path; var loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(buffer) { try { onLoad(scope.parse(buffer, path)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(buffer, path) { var textureLoader = new TextureLoader(this.manager); textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin); var Virtulous = {}; Virtulous.KeyFrame = class { constructor(time, matrix) { this.time = time; this.matrix = matrix.clone(); this.position = new Vector3(); this.quaternion = new Quaternion(); this.scale = new Vector3(1, 1, 1); this.matrix.decompose(this.position, this.quaternion, this.scale); this.clone = function() { return new Virtulous.KeyFrame(this.time, this.matrix); }; this.lerp = function(nextKey, time2) { time2 -= this.time; var dist = nextKey.time - this.time; var l = time2 / dist; var l2 = 1 - l; var keypos = this.position; var keyrot = this.quaternion; var key2pos = nextKey.position; var key2rot = nextKey.quaternion; Virtulous.KeyFrame.tempAniPos.x = keypos.x * l2 + key2pos.x * l; Virtulous.KeyFrame.tempAniPos.y = keypos.y * l2 + key2pos.y * l; Virtulous.KeyFrame.tempAniPos.z = keypos.z * l2 + key2pos.z * l; Virtulous.KeyFrame.tempAniQuat.set(keyrot.x, keyrot.y, keyrot.z, keyrot.w); Virtulous.KeyFrame.tempAniQuat.slerp(key2rot, l); return Virtulous.KeyFrame.tempAniMatrix.compose(Virtulous.KeyFrame.tempAniPos, Virtulous.KeyFrame.tempAniQuat, Virtulous.KeyFrame.tempAniScale); }; } }; Virtulous.KeyFrame.tempAniPos = new Vector3(); Virtulous.KeyFrame.tempAniQuat = new Quaternion(); Virtulous.KeyFrame.tempAniScale = new Vector3(1, 1, 1); Virtulous.KeyFrame.tempAniMatrix = new Matrix4(); Virtulous.KeyFrameTrack = function() { this.keys = []; this.target = null; this.time = 0; this.length = 0; this._accelTable = {}; this.fps = 20; this.addKey = function(key) { this.keys.push(key); }; this.init = function() { this.sortKeys(); if (this.keys.length > 0) this.length = this.keys[this.keys.length - 1].time; else this.length = 0; if (!this.fps) return; for (let j = 0; j < this.length * this.fps; j++) for (let i = 0; i < this.keys.length; i++) if (this.keys[i].time == j) { this._accelTable[j] = i; break; } else if (this.keys[i].time < j / this.fps && this.keys[i + 1] && this.keys[i + 1].time >= j / this.fps) { this._accelTable[j] = i; break; } }; this.parseFromThree = function(data) { var fps = data.fps; this.target = data.node; var track = data.hierarchy[0].keys; for (let i = 0; i < track.length; i++) this.addKey(new Virtulous.KeyFrame(i / fps || track[i].time, track[i].targets[0].data)); this.init(); }; this.parseFromCollada = function(data) { var track = data.keys; var fps = this.fps; for (let i = 0; i < track.length; i++) this.addKey(new Virtulous.KeyFrame(i / fps || track[i].time, track[i].matrix)); this.init(); }; this.sortKeys = function() { this.keys.sort(this.keySortFunc); }; this.keySortFunc = function(a, b) { return a.time - b.time; }; this.clone = function() { var t = new Virtulous.KeyFrameTrack(); t.target = this.target; t.time = this.time; t.length = this.length; for (let i = 0; i < this.keys.length; i++) t.addKey(this.keys[i].clone()); t.init(); return t; }; this.reTarget = function(root, compareitor) { if (!compareitor) compareitor = Virtulous.TrackTargetNodeNameCompare; this.target = compareitor(root, this.target); }; this.keySearchAccel = function(time) { time *= this.fps; time = Math.floor(time); return this._accelTable[time] || 0; }; this.setTime = function(time) { time = Math.abs(time); if (this.length) time = time % this.length + .05; var key0 = null; var key1 = null; for (let i = this.keySearchAccel(time); i < this.keys.length; i++) if (this.keys[i].time == time) { key0 = this.keys[i]; key1 = this.keys[i]; break; } else if (this.keys[i].time < time && this.keys[i + 1] && this.keys[i + 1].time > time) { key0 = this.keys[i]; key1 = this.keys[i + 1]; break; } else if (this.keys[i].time < time && i == this.keys.length - 1) { key0 = this.keys[i]; key1 = this.keys[0].clone(); key1.time += this.length + .05; break; } if (key0 && key1 && key0 !== key1) { this.target.matrixAutoUpdate = false; this.target.matrix.copy(key0.lerp(key1, time)); this.target.matrixWorldNeedsUpdate = true; return; } if (key0 && key1 && key0 == key1) { this.target.matrixAutoUpdate = false; this.target.matrix.copy(key0.matrix); this.target.matrixWorldNeedsUpdate = true; return; } }; }; Virtulous.TrackTargetNodeNameCompare = function(root, target) { function find(node, name) { if (node.name == name) return node; for (let i = 0; i < node.children.length; i++) { var r = find(node.children[i], name); if (r) return r; } return null; } return find(root, target.name); }; Virtulous.Animation = function() { this.tracks = []; this.length = 0; this.addTrack = function(track) { this.tracks.push(track); this.length = Math.max(track.length, this.length); }; this.setTime = function(time) { this.time = time; for (let i = 0; i < this.tracks.length; i++) this.tracks[i].setTime(time); }; this.clone = function(target, compareitor) { if (!compareitor) compareitor = Virtulous.TrackTargetNodeNameCompare; var n = new Virtulous.Animation(); n.target = target; for (let i = 0; i < this.tracks.length; i++) { var track = this.tracks[i].clone(); track.reTarget(target, compareitor); n.addTrack(track); } return n; }; }; var ASSBIN_CHUNK_AICAMERA = 4660; var ASSBIN_CHUNK_AILIGHT = 4661; var ASSBIN_CHUNK_AITEXTURE = 4662; var ASSBIN_CHUNK_AIMESH = 4663; var ASSBIN_CHUNK_AINODEANIM = 4664; var ASSBIN_CHUNK_AISCENE = 4665; var ASSBIN_CHUNK_AIBONE = 4666; var ASSBIN_CHUNK_AIANIMATION = 4667; var ASSBIN_CHUNK_AINODE = 4668; var ASSBIN_CHUNK_AIMATERIAL = 4669; var ASSBIN_CHUNK_AIMATERIALPROPERTY = 4670; var ASSBIN_MESH_HAS_POSITIONS = 1; var ASSBIN_MESH_HAS_NORMALS = 2; var ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS = 4; var ASSBIN_MESH_HAS_TEXCOORD_BASE = 256; var ASSBIN_MESH_HAS_COLOR_BASE = 65536; var AI_MAX_NUMBER_OF_COLOR_SETS = 1; var AI_MAX_NUMBER_OF_TEXTURECOORDS = 4; //! A directional light source has a well-defined direction //! but is infinitely far away. That's quite a good //! approximation for sun light. var aiLightSource_DIRECTIONAL = 1; //! A point light source has a well-defined position //! in space but no direction - it emits light in all //! directions. A normal bulb is a point light. //! A spot light source emits light in a specific //! angle. It has a position and a direction it is pointing to. //! A good example for a spot light is a light spot in //! sport arenas. var aiLightSource_SPOT = 3; //! The generic light level of the world, including the bounces //! of all other lightsources. //! Typically, there's at most one ambient light in a scene. //! This light type doesn't have a valid position, direction, or //! other properties, just a color. var aiTextureType_DIFFUSE = 1; var aiTextureType_NORMALS = 6; var aiTextureType_OPACITY = 8; var aiTextureType_LIGHTMAP = 10; var BONESPERVERT = 4; function ASSBIN_MESH_HAS_TEXCOORD(n) { return ASSBIN_MESH_HAS_TEXCOORD_BASE << n; } function ASSBIN_MESH_HAS_COLOR(n) { return ASSBIN_MESH_HAS_COLOR_BASE << n; } function markBones(scene) { for (let i in scene.mMeshes) { var mesh = scene.mMeshes[i]; for (let k in mesh.mBones) { var boneNode = scene.findNode(mesh.mBones[k].mName); if (boneNode) boneNode.isBone = true; } } } function cloneTreeToBones(root, scene) { var rootBone = new Bone(); rootBone.matrix.copy(root.matrix); rootBone.matrixWorld.copy(root.matrixWorld); rootBone.position.copy(root.position); rootBone.quaternion.copy(root.quaternion); rootBone.scale.copy(root.scale); scene.nodeCount++; rootBone.name = "bone_" + root.name + scene.nodeCount.toString(); if (!scene.nodeToBoneMap[root.name]) scene.nodeToBoneMap[root.name] = []; scene.nodeToBoneMap[root.name].push(rootBone); for (let i in root.children) { var child = cloneTreeToBones(root.children[i], scene); rootBone.add(child); } return rootBone; } function sortWeights(indexes, weights) { var pairs = []; for (let i = 0; i < indexes.length; i++) pairs.push({ i: indexes[i], w: weights[i] }); pairs.sort(function(a, b) { return b.w - a.w; }); while (pairs.length < 4) pairs.push({ i: 0, w: 0 }); if (pairs.length > 4) pairs.length = 4; var sum = 0; for (let i = 0; i < 4; i++) sum += pairs[i].w * pairs[i].w; sum = Math.sqrt(sum); for (let i = 0; i < 4; i++) { pairs[i].w = pairs[i].w / sum; indexes[i] = pairs[i].i; weights[i] = pairs[i].w; } } function findMatchingBone(root, name) { if (root.name.indexOf("bone_" + name) == 0) return root; for (let i in root.children) { var ret = findMatchingBone(root.children[i], name); if (ret) return ret; } } class aiMesh { constructor() { this.mPrimitiveTypes = 0; this.mNumVertices = 0; this.mNumFaces = 0; this.mNumBones = 0; this.mMaterialIndex = 0; this.mVertices = []; this.mNormals = []; this.mTangents = []; this.mBitangents = []; this.mColors = [[]]; this.mTextureCoords = [[]]; this.mFaces = []; this.mBones = []; this.hookupSkeletons = function(scene) { if (this.mBones.length == 0) return; var allBones = []; var offsetMatrix = []; var skeletonRoot = scene.findNode(this.mBones[0].mName); while (skeletonRoot.mParent && skeletonRoot.mParent.isBone) skeletonRoot = skeletonRoot.mParent; var threeSkeletonRoot = skeletonRoot.toTHREE(scene); var threeSkeletonRootBone = cloneTreeToBones(threeSkeletonRoot, scene); this.threeNode.add(threeSkeletonRootBone); for (let i = 0; i < this.mBones.length; i++) { var bone = findMatchingBone(threeSkeletonRootBone, this.mBones[i].mName); if (bone) { var tbone = bone; allBones.push(tbone); offsetMatrix.push(this.mBones[i].mOffsetMatrix.toTHREE()); } else { var skeletonRoot = scene.findNode(this.mBones[i].mName); if (!skeletonRoot) return; var threeSkeletonRoot = skeletonRoot.toTHREE(scene); var threeSkeletonRootBone = cloneTreeToBones(threeSkeletonRoot, scene); this.threeNode.add(threeSkeletonRootBone); var bone = findMatchingBone(threeSkeletonRootBone, this.mBones[i].mName); var tbone = bone; allBones.push(tbone); offsetMatrix.push(this.mBones[i].mOffsetMatrix.toTHREE()); } } var skeleton = new Skeleton(allBones, offsetMatrix); this.threeNode.bind(skeleton, new Matrix4()); this.threeNode.material.skinning = true; }; this.toTHREE = function(scene) { if (this.threeNode) return this.threeNode; var geometry = new BufferGeometry(); var mat; if (scene.mMaterials[this.mMaterialIndex]) mat = scene.mMaterials[this.mMaterialIndex].toTHREE(scene); else mat = new MeshLambertMaterial(); geometry.setIndex(new BufferAttribute(new Uint32Array(this.mIndexArray), 1)); geometry.setAttribute("position", new BufferAttribute(this.mVertexBuffer, 3)); if (this.mNormalBuffer && this.mNormalBuffer.length > 0) geometry.setAttribute("normal", new BufferAttribute(this.mNormalBuffer, 3)); if (this.mColorBuffer && this.mColorBuffer.length > 0) geometry.setAttribute("color", new BufferAttribute(this.mColorBuffer, 4)); if (this.mTexCoordsBuffers[0] && this.mTexCoordsBuffers[0].length > 0) geometry.setAttribute("uv", new BufferAttribute(new Float32Array(this.mTexCoordsBuffers[0]), 2)); if (this.mTexCoordsBuffers[1] && this.mTexCoordsBuffers[1].length > 0) geometry.setAttribute("uv1", new BufferAttribute(new Float32Array(this.mTexCoordsBuffers[1]), 2)); if (this.mTangentBuffer && this.mTangentBuffer.length > 0) geometry.setAttribute("tangents", new BufferAttribute(this.mTangentBuffer, 3)); if (this.mBitangentBuffer && this.mBitangentBuffer.length > 0) geometry.setAttribute("bitangents", new BufferAttribute(this.mBitangentBuffer, 3)); if (this.mBones.length > 0) { var weights = []; var bones = []; for (let i = 0; i < this.mBones.length; i++) for (let j = 0; j < this.mBones[i].mWeights.length; j++) { var weight = this.mBones[i].mWeights[j]; if (weight) { if (!weights[weight.mVertexId]) weights[weight.mVertexId] = []; if (!bones[weight.mVertexId]) bones[weight.mVertexId] = []; weights[weight.mVertexId].push(weight.mWeight); bones[weight.mVertexId].push(parseInt(i)); } } for (let i in bones) sortWeights(bones[i], weights[i]); var _weights = []; var _bones = []; for (let i = 0; i < weights.length; i++) for (let j = 0; j < 4; j++) if (weights[i] && bones[i]) { _weights.push(weights[i][j]); _bones.push(bones[i][j]); } else { _weights.push(0); _bones.push(0); } geometry.setAttribute("skinWeight", new BufferAttribute(new Float32Array(_weights), BONESPERVERT)); geometry.setAttribute("skinIndex", new BufferAttribute(new Float32Array(_bones), BONESPERVERT)); } var mesh; if (this.mBones.length == 0) mesh = new Mesh(geometry, mat); if (this.mBones.length > 0) { mesh = new SkinnedMesh(geometry, mat); mesh.normalizeSkinWeights(); } this.threeNode = mesh; return mesh; }; } } class aiFace { constructor() { this.mNumIndices = 0; this.mIndices = []; } } class aiVector3D { constructor() { this.x = 0; this.y = 0; this.z = 0; this.toTHREE = function() { return new Vector3(this.x, this.y, this.z); }; } } class aiColor3D { constructor() { this.r = 0; this.g = 0; this.b = 0; this.a = 0; this.toTHREE = function() { return new Color(this.r, this.g, this.b); }; } } class aiQuaternion { constructor() { this.x = 0; this.y = 0; this.z = 0; this.w = 0; this.toTHREE = function() { return new Quaternion(this.x, this.y, this.z, this.w); }; } } class aiVertexWeight { constructor() { this.mVertexId = 0; this.mWeight = 0; } } class aiString { constructor() { this.data = []; this.toString = function() { var str = ""; this.data.forEach(function(i) { str += String.fromCharCode(i); }); return str.replace(/[^\x20-\x7E]+/g, ""); }; } } class aiVectorKey { constructor() { this.mTime = 0; this.mValue = null; } } class aiQuatKey { constructor() { this.mTime = 0; this.mValue = null; } } class aiNode { constructor() { this.mName = ""; this.mTransformation = []; this.mNumChildren = 0; this.mNumMeshes = 0; this.mMeshes = []; this.mChildren = []; this.toTHREE = function(scene) { if (this.threeNode) return this.threeNode; var o = new Object3D(); o.name = this.mName; o.matrix = this.mTransformation.toTHREE(); for (let i = 0; i < this.mChildren.length; i++) o.add(this.mChildren[i].toTHREE(scene)); for (let i = 0; i < this.mMeshes.length; i++) o.add(scene.mMeshes[this.mMeshes[i]].toTHREE(scene)); this.threeNode = o; o.matrix.decompose(o.position, o.quaternion, o.scale); return o; }; } } class aiBone { constructor() { this.mName = ""; this.mNumWeights = 0; this.mOffsetMatrix = 0; } } class aiMaterialProperty { constructor() { this.mKey = ""; this.mSemantic = 0; this.mIndex = 0; this.mData = []; this.mDataLength = 0; this.mType = 0; this.dataAsColor = function() { var array = new Uint8Array(this.mData).buffer; var reader = new DataView(array); return new Color(reader.getFloat32(0, true), reader.getFloat32(4, true), reader.getFloat32(8, true)); }; this.dataAsFloat = function() { var array = new Uint8Array(this.mData).buffer; return new DataView(array).getFloat32(0, true); }; this.dataAsBool = function() { var array = new Uint8Array(this.mData).buffer; return !!new DataView(array).getFloat32(0, true); }; this.dataAsString = function() { var s = new aiString(); s.data = this.mData; return s.toString(); }; this.dataAsMap = function() { var s = new aiString(); s.data = this.mData; var path2 = s.toString(); path2 = path2.replace(/\\/g, "/"); if (path2.indexOf("/") != -1) path2 = path2.substr(path2.lastIndexOf("/") + 1); return textureLoader.load(path2); }; } } var namePropMapping = { "?mat.name": "name", "$mat.shadingm": "shading", "$mat.twosided": "twoSided", "$mat.wireframe": "wireframe", "$clr.ambient": "ambient", "$clr.diffuse": "color", "$clr.specular": "specular", "$clr.emissive": "emissive", "$clr.transparent": "transparent", "$clr.reflective": "reflect", "$mat.shininess": "shininess", "$mat.reflectivity": "reflectivity", "$mat.refracti": "refraction", "$tex.file": "map" }; var nameTypeMapping = { "?mat.name": "string", "$mat.shadingm": "bool", "$mat.twosided": "bool", "$mat.wireframe": "bool", "$clr.ambient": "color", "$clr.diffuse": "color", "$clr.specular": "color", "$clr.emissive": "color", "$clr.transparent": "color", "$clr.reflective": "color", "$mat.shininess": "float", "$mat.reflectivity": "float", "$mat.refracti": "float", "$tex.file": "map" }; class aiMaterial { constructor() { this.mNumAllocated = 0; this.mNumProperties = 0; this.mProperties = []; this.toTHREE = function() { var mat = new MeshPhongMaterial(); for (let i = 0; i < this.mProperties.length; i++) { if (nameTypeMapping[this.mProperties[i].mKey] == "float") mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsFloat(); if (nameTypeMapping[this.mProperties[i].mKey] == "color") mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsColor(); if (nameTypeMapping[this.mProperties[i].mKey] == "bool") mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsBool(); if (nameTypeMapping[this.mProperties[i].mKey] == "string") mat[namePropMapping[this.mProperties[i].mKey]] = this.mProperties[i].dataAsString(); if (nameTypeMapping[this.mProperties[i].mKey] == "map") { var prop = this.mProperties[i]; if (prop.mSemantic == aiTextureType_DIFFUSE) mat.map = this.mProperties[i].dataAsMap(); if (prop.mSemantic == aiTextureType_NORMALS) mat.normalMap = this.mProperties[i].dataAsMap(); if (prop.mSemantic == aiTextureType_LIGHTMAP) mat.lightMap = this.mProperties[i].dataAsMap(); if (prop.mSemantic == aiTextureType_OPACITY) mat.alphaMap = this.mProperties[i].dataAsMap(); } } mat.ambient.r = .53; mat.ambient.g = .53; mat.ambient.b = .53; mat.color.r = 1; mat.color.g = 1; mat.color.b = 1; return mat; }; } } function veclerp(v1, v2, l) { var v = new Vector3(); var lm1 = 1 - l; v.x = v1.x * l + v2.x * lm1; v.y = v1.y * l + v2.y * lm1; v.z = v1.z * l + v2.z * lm1; return v; } function quatlerp(q1, q2, l) { return q1.clone().slerp(q2, 1 - l); } function sampleTrack(keys, time, lne, lerp) { if (keys.length == 1) return keys[0].mValue.toTHREE(); var dist = Infinity; var key = null; var nextKey = null; for (let i = 0; i < keys.length; i++) { var timeDist = Math.abs(keys[i].mTime - time); if (timeDist < dist && keys[i].mTime <= time) { dist = timeDist; key = keys[i]; nextKey = keys[i + 1]; } } if (!key) return null; else if (nextKey) { var dT = nextKey.mTime - key.mTime; var T = key.mTime - time; var l = T / dT; return lerp(key.mValue.toTHREE(), nextKey.mValue.toTHREE(), l); } else { nextKey = keys[0].clone(); nextKey.mTime += lne; var dT = nextKey.mTime - key.mTime; var T = key.mTime - time; var l = T / dT; return lerp(key.mValue.toTHREE(), nextKey.mValue.toTHREE(), l); } } class aiNodeAnim { constructor() { this.mNodeName = ""; this.mNumPositionKeys = 0; this.mNumRotationKeys = 0; this.mNumScalingKeys = 0; this.mPositionKeys = []; this.mRotationKeys = []; this.mScalingKeys = []; this.mPreState = ""; this.mPostState = ""; this.init = function(tps) { if (!tps) tps = 1; function t(t2) { t2.mTime /= tps; } this.mPositionKeys.forEach(t); this.mRotationKeys.forEach(t); this.mScalingKeys.forEach(t); }; this.sortKeys = function() { function comp(a, b) { return a.mTime - b.mTime; } this.mPositionKeys.sort(comp); this.mRotationKeys.sort(comp); this.mScalingKeys.sort(comp); }; this.getLength = function() { return Math.max(Math.max.apply(null, this.mPositionKeys.map(function(a) { return a.mTime; })), Math.max.apply(null, this.mRotationKeys.map(function(a) { return a.mTime; })), Math.max.apply(null, this.mScalingKeys.map(function(a) { return a.mTime; }))); }; this.toTHREE = function(o) { this.sortKeys(); var length = this.getLength(); var track = new Virtulous.KeyFrameTrack(); for (let i = 0; i < length; i += .05) { var matrix = new Matrix4(); var time = i; var pos = sampleTrack(this.mPositionKeys, time, length, veclerp); var scale = sampleTrack(this.mScalingKeys, time, length, veclerp); var rotation = sampleTrack(this.mRotationKeys, time, length, quatlerp); matrix.compose(pos, rotation, scale); var key = new Virtulous.KeyFrame(time, matrix); track.addKey(key); } track.target = o.findNode(this.mNodeName).toTHREE(); var tracks = [track]; if (o.nodeToBoneMap[this.mNodeName]) for (let i = 0; i < o.nodeToBoneMap[this.mNodeName].length; i++) { var t2 = track.clone(); t2.target = o.nodeToBoneMap[this.mNodeName][i]; tracks.push(t2); } return tracks; }; } } class aiAnimation { constructor() { this.mName = ""; this.mDuration = 0; this.mTicksPerSecond = 0; this.mNumChannels = 0; this.mChannels = []; this.toTHREE = function(root) { var animationHandle = new Virtulous.Animation(); for (let i in this.mChannels) { this.mChannels[i].init(this.mTicksPerSecond); var tracks = this.mChannels[i].toTHREE(root); for (let j in tracks) { tracks[j].init(); animationHandle.addTrack(tracks[j]); } } animationHandle.length = Math.max.apply(null, animationHandle.tracks.map(function(e) { return e.length; })); return animationHandle; }; } } class aiTexture { constructor() { this.mWidth = 0; this.mHeight = 0; this.texAchFormatHint = []; this.pcData = []; } } class aiLight { constructor() { this.mName = ""; this.mType = 0; this.mAttenuationConstant = 0; this.mAttenuationLinear = 0; this.mAttenuationQuadratic = 0; this.mAngleInnerCone = 0; this.mAngleOuterCone = 0; this.mColorDiffuse = null; this.mColorSpecular = null; this.mColorAmbient = null; } } class aiCamera { constructor() { this.mName = ""; this.mPosition = null; this.mLookAt = null; this.mUp = null; this.mHorizontalFOV = 0; this.mClipPlaneNear = 0; this.mClipPlaneFar = 0; this.mAspect = 0; } } class aiScene { constructor() { this.versionMajor = 0; this.versionMinor = 0; this.versionRevision = 0; this.compileFlags = 0; this.mFlags = 0; this.mNumMeshes = 0; this.mNumMaterials = 0; this.mNumAnimations = 0; this.mNumTextures = 0; this.mNumLights = 0; this.mNumCameras = 0; this.mRootNode = null; this.mMeshes = []; this.mMaterials = []; this.mAnimations = []; this.mLights = []; this.mCameras = []; this.nodeToBoneMap = {}; this.findNode = function(name, root) { if (!root) root = this.mRootNode; if (root.mName == name) return root; for (let i = 0; i < root.mChildren.length; i++) { var ret = this.findNode(name, root.mChildren[i]); if (ret) return ret; } return null; }; this.toTHREE = function() { this.nodeCount = 0; markBones(this); var o = this.mRootNode.toTHREE(this); for (let i in this.mMeshes) this.mMeshes[i].hookupSkeletons(this); if (this.mAnimations.length > 0) var a = this.mAnimations[0].toTHREE(this); return { object: o, animation: a }; }; } } class aiMatrix4 { constructor() { this.elements = [ [], [], [], [] ]; this.toTHREE = function() { var m = new Matrix4(); for (let i = 0; i < 4; ++i) for (let i2 = 0; i2 < 4; ++i2) m.elements[i * 4 + i2] = this.elements[i2][i]; return m; }; } } var littleEndian = true; function readFloat(dataview) { var val = dataview.getFloat32(dataview.readOffset, littleEndian); dataview.readOffset += 4; return val; } function Read_double(dataview) { var val = dataview.getFloat64(dataview.readOffset, littleEndian); dataview.readOffset += 8; return val; } function Read_uint8_t(dataview) { var val = dataview.getUint8(dataview.readOffset); dataview.readOffset += 1; return val; } function Read_uint16_t(dataview) { var val = dataview.getUint16(dataview.readOffset, littleEndian); dataview.readOffset += 2; return val; } function Read_unsigned_int(dataview) { var val = dataview.getUint32(dataview.readOffset, littleEndian); dataview.readOffset += 4; return val; } function Read_uint32_t(dataview) { var val = dataview.getUint32(dataview.readOffset, littleEndian); dataview.readOffset += 4; return val; } function Read_aiVector3D(stream) { var v = new aiVector3D(); v.x = readFloat(stream); v.y = readFloat(stream); v.z = readFloat(stream); return v; } function Read_aiColor3D(stream) { var c = new aiColor3D(); c.r = readFloat(stream); c.g = readFloat(stream); c.b = readFloat(stream); return c; } function Read_aiQuaternion(stream) { var v = new aiQuaternion(); v.w = readFloat(stream); v.x = readFloat(stream); v.y = readFloat(stream); v.z = readFloat(stream); return v; } function Read_aiString(stream) { var s = new aiString(); var stringlengthbytes = Read_unsigned_int(stream); stream.ReadBytes(s.data, 1, stringlengthbytes); return s.toString(); } function Read_aiVertexWeight(stream) { var w = new aiVertexWeight(); w.mVertexId = Read_unsigned_int(stream); w.mWeight = readFloat(stream); return w; } function Read_aiMatrix4x4(stream) { var m = new aiMatrix4(); for (let i = 0; i < 4; ++i) for (let i2 = 0; i2 < 4; ++i2) m.elements[i][i2] = readFloat(stream); return m; } function Read_aiVectorKey(stream) { var v = new aiVectorKey(); v.mTime = Read_double(stream); v.mValue = Read_aiVector3D(stream); return v; } function Read_aiQuatKey(stream) { var v = new aiQuatKey(); v.mTime = Read_double(stream); v.mValue = Read_aiQuaternion(stream); return v; } function ReadArray_aiVertexWeight(stream, data, size) { for (let i = 0; i < size; i++) data[i] = Read_aiVertexWeight(stream); } function ReadArray_aiVectorKey(stream, data, size) { for (let i = 0; i < size; i++) data[i] = Read_aiVectorKey(stream); } function ReadArray_aiQuatKey(stream, data, size) { for (let i = 0; i < size; i++) data[i] = Read_aiQuatKey(stream); } function ReadBounds(stream, T, n) { return stream.Seek(sizeof(T) * n, aiOrigin_CUR); } function ai_assert(bool) { if (!bool) throw "asset failed"; } function ReadBinaryNode(stream, parent, depth) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AINODE); Read_uint32_t(stream); var node = new aiNode(); node.mParent = parent; node.mDepth = depth; node.mName = Read_aiString(stream); node.mTransformation = Read_aiMatrix4x4(stream); node.mNumChildren = Read_unsigned_int(stream); node.mNumMeshes = Read_unsigned_int(stream); if (node.mNumMeshes) { node.mMeshes = []; for (let i = 0; i < node.mNumMeshes; ++i) node.mMeshes[i] = Read_unsigned_int(stream); } if (node.mNumChildren) { node.mChildren = []; for (let i = 0; i < node.mNumChildren; ++i) { var node2 = ReadBinaryNode(stream, node, depth++); node.mChildren[i] = node2; } } return node; } function ReadBinaryBone(stream, b) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AIBONE); Read_uint32_t(stream); b.mName = Read_aiString(stream); b.mNumWeights = Read_unsigned_int(stream); b.mOffsetMatrix = Read_aiMatrix4x4(stream); if (shortened) ReadBounds(stream, b.mWeights, b.mNumWeights); else { b.mWeights = []; ReadArray_aiVertexWeight(stream, b.mWeights, b.mNumWeights); } return b; } function ReadBinaryMesh(stream, mesh) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AIMESH); Read_uint32_t(stream); mesh.mPrimitiveTypes = Read_unsigned_int(stream); mesh.mNumVertices = Read_unsigned_int(stream); mesh.mNumFaces = Read_unsigned_int(stream); mesh.mNumBones = Read_unsigned_int(stream); mesh.mMaterialIndex = Read_unsigned_int(stream); mesh.mNumUVComponents = []; var c = Read_unsigned_int(stream); if (c & ASSBIN_MESH_HAS_POSITIONS) if (shortened) ReadBounds(stream, mesh.mVertices, mesh.mNumVertices); else { mesh.mVertices = []; mesh.mVertexBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); } if (c & ASSBIN_MESH_HAS_NORMALS) if (shortened) ReadBounds(stream, mesh.mNormals, mesh.mNumVertices); else { mesh.mNormals = []; mesh.mNormalBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); } if (c & ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS) if (shortened) { ReadBounds(stream, mesh.mTangents, mesh.mNumVertices); ReadBounds(stream, mesh.mBitangents, mesh.mNumVertices); } else { mesh.mTangents = []; mesh.mTangentBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); mesh.mBitangents = []; mesh.mBitangentBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4); stream.Seek(mesh.mNumVertices * 3 * 4, aiOrigin_CUR); } for (let n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) { if (!(c & ASSBIN_MESH_HAS_COLOR(n))) break; if (shortened) ReadBounds(stream, mesh.mColors[n], mesh.mNumVertices); else { mesh.mColors[n] = []; mesh.mColorBuffer = stream.subArray32(stream.readOffset, stream.readOffset + mesh.mNumVertices * 4 * 4); stream.Seek(mesh.mNumVertices * 4 * 4, aiOrigin_CUR); } } mesh.mTexCoordsBuffers = []; for (let n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) { if (!(c & ASSBIN_MESH_HAS_TEXCOORD(n))) break; mesh.mNumUVComponents[n] = Read_unsigned_int(stream); if (shortened) ReadBounds(stream, mesh.mTextureCoords[n], mesh.mNumVertices); else { mesh.mTextureCoords[n] = []; mesh.mTexCoordsBuffers[n] = []; for (let uv = 0; uv < mesh.mNumVertices; uv++) { mesh.mTexCoordsBuffers[n].push(readFloat(stream)); mesh.mTexCoordsBuffers[n].push(readFloat(stream)); readFloat(stream); } } } if (shortened) Read_unsigned_int(stream); else { mesh.mFaces = []; mesh.mIndexArray = []; for (let i = 0; i < mesh.mNumFaces; ++i) { var f = mesh.mFaces[i] = new aiFace(); f.mNumIndices = Read_uint16_t(stream); f.mIndices = []; for (let a = 0; a < f.mNumIndices; ++a) if (mesh.mNumVertices < 65536) f.mIndices[a] = Read_uint16_t(stream); else f.mIndices[a] = Read_unsigned_int(stream); if (f.mNumIndices === 3) { mesh.mIndexArray.push(f.mIndices[0]); mesh.mIndexArray.push(f.mIndices[1]); mesh.mIndexArray.push(f.mIndices[2]); } else if (f.mNumIndices === 4) { mesh.mIndexArray.push(f.mIndices[0]); mesh.mIndexArray.push(f.mIndices[1]); mesh.mIndexArray.push(f.mIndices[2]); mesh.mIndexArray.push(f.mIndices[2]); mesh.mIndexArray.push(f.mIndices[3]); mesh.mIndexArray.push(f.mIndices[0]); } else throw new Error("Sorry, can't currently triangulate polys. Use the triangulate preprocessor in Assimp."); } } if (mesh.mNumBones) { mesh.mBones = []; for (let a = 0; a < mesh.mNumBones; ++a) { mesh.mBones[a] = new aiBone(); ReadBinaryBone(stream, mesh.mBones[a]); } } } function ReadBinaryMaterialProperty(stream, prop) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AIMATERIALPROPERTY); Read_uint32_t(stream); prop.mKey = Read_aiString(stream); prop.mSemantic = Read_unsigned_int(stream); prop.mIndex = Read_unsigned_int(stream); prop.mDataLength = Read_unsigned_int(stream); prop.mType = Read_unsigned_int(stream); prop.mData = []; stream.ReadBytes(prop.mData, 1, prop.mDataLength); } function ReadBinaryMaterial(stream, mat) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AIMATERIAL); Read_uint32_t(stream); mat.mNumAllocated = mat.mNumProperties = Read_unsigned_int(stream); if (mat.mNumProperties) { if (mat.mProperties) delete mat.mProperties; mat.mProperties = []; for (let i = 0; i < mat.mNumProperties; ++i) { mat.mProperties[i] = new aiMaterialProperty(); ReadBinaryMaterialProperty(stream, mat.mProperties[i]); } } } function ReadBinaryNodeAnim(stream, nd) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AINODEANIM); Read_uint32_t(stream); nd.mNodeName = Read_aiString(stream); nd.mNumPositionKeys = Read_unsigned_int(stream); nd.mNumRotationKeys = Read_unsigned_int(stream); nd.mNumScalingKeys = Read_unsigned_int(stream); nd.mPreState = Read_unsigned_int(stream); nd.mPostState = Read_unsigned_int(stream); if (nd.mNumPositionKeys) if (shortened) ReadBounds(stream, nd.mPositionKeys, nd.mNumPositionKeys); else { nd.mPositionKeys = []; ReadArray_aiVectorKey(stream, nd.mPositionKeys, nd.mNumPositionKeys); } if (nd.mNumRotationKeys) if (shortened) ReadBounds(stream, nd.mRotationKeys, nd.mNumRotationKeys); else { nd.mRotationKeys = []; ReadArray_aiQuatKey(stream, nd.mRotationKeys, nd.mNumRotationKeys); } if (nd.mNumScalingKeys) if (shortened) ReadBounds(stream, nd.mScalingKeys, nd.mNumScalingKeys); else { nd.mScalingKeys = []; ReadArray_aiVectorKey(stream, nd.mScalingKeys, nd.mNumScalingKeys); } } function ReadBinaryAnim(stream, anim) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AIANIMATION); Read_uint32_t(stream); anim.mName = Read_aiString(stream); anim.mDuration = Read_double(stream); anim.mTicksPerSecond = Read_double(stream); anim.mNumChannels = Read_unsigned_int(stream); if (anim.mNumChannels) { anim.mChannels = []; for (let a = 0; a < anim.mNumChannels; ++a) { anim.mChannels[a] = new aiNodeAnim(); ReadBinaryNodeAnim(stream, anim.mChannels[a]); } } } function ReadBinaryTexture(stream, tex) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AITEXTURE); Read_uint32_t(stream); tex.mWidth = Read_unsigned_int(stream); tex.mHeight = Read_unsigned_int(stream); stream.ReadBytes(tex.achFormatHint, 1, 4); if (!shortened) if (!tex.mHeight) { tex.pcData = []; stream.ReadBytes(tex.pcData, 1, tex.mWidth); } else { tex.pcData = []; stream.ReadBytes(tex.pcData, 1, tex.mWidth * tex.mHeight * 4); } } function ReadBinaryLight(stream, l) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AILIGHT); Read_uint32_t(stream); l.mName = Read_aiString(stream); l.mType = Read_unsigned_int(stream); if (l.mType != aiLightSource_DIRECTIONAL) { l.mAttenuationConstant = readFloat(stream); l.mAttenuationLinear = readFloat(stream); l.mAttenuationQuadratic = readFloat(stream); } l.mColorDiffuse = Read_aiColor3D(stream); l.mColorSpecular = Read_aiColor3D(stream); l.mColorAmbient = Read_aiColor3D(stream); if (l.mType == aiLightSource_SPOT) { l.mAngleInnerCone = readFloat(stream); l.mAngleOuterCone = readFloat(stream); } } function ReadBinaryCamera(stream, cam) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AICAMERA); Read_uint32_t(stream); cam.mName = Read_aiString(stream); cam.mPosition = Read_aiVector3D(stream); cam.mLookAt = Read_aiVector3D(stream); cam.mUp = Read_aiVector3D(stream); cam.mHorizontalFOV = readFloat(stream); cam.mClipPlaneNear = readFloat(stream); cam.mClipPlaneFar = readFloat(stream); cam.mAspect = readFloat(stream); } function ReadBinaryScene(stream, scene) { ai_assert(Read_uint32_t(stream) == ASSBIN_CHUNK_AISCENE); Read_uint32_t(stream); scene.mFlags = Read_unsigned_int(stream); scene.mNumMeshes = Read_unsigned_int(stream); scene.mNumMaterials = Read_unsigned_int(stream); scene.mNumAnimations = Read_unsigned_int(stream); scene.mNumTextures = Read_unsigned_int(stream); scene.mNumLights = Read_unsigned_int(stream); scene.mNumCameras = Read_unsigned_int(stream); scene.mRootNode = new aiNode(); scene.mRootNode = ReadBinaryNode(stream, null, 0); if (scene.mNumMeshes) { scene.mMeshes = []; for (let i = 0; i < scene.mNumMeshes; ++i) { scene.mMeshes[i] = new aiMesh(); ReadBinaryMesh(stream, scene.mMeshes[i]); } } if (scene.mNumMaterials) { scene.mMaterials = []; for (let i = 0; i < scene.mNumMaterials; ++i) { scene.mMaterials[i] = new aiMaterial(); ReadBinaryMaterial(stream, scene.mMaterials[i]); } } if (scene.mNumAnimations) { scene.mAnimations = []; for (let i = 0; i < scene.mNumAnimations; ++i) { scene.mAnimations[i] = new aiAnimation(); ReadBinaryAnim(stream, scene.mAnimations[i]); } } if (scene.mNumTextures) { scene.mTextures = []; for (let i = 0; i < scene.mNumTextures; ++i) { scene.mTextures[i] = new aiTexture(); ReadBinaryTexture(stream, scene.mTextures[i]); } } if (scene.mNumLights) { scene.mLights = []; for (let i = 0; i < scene.mNumLights; ++i) { scene.mLights[i] = new aiLight(); ReadBinaryLight(stream, scene.mLights[i]); } } if (scene.mNumCameras) { scene.mCameras = []; for (let i = 0; i < scene.mNumCameras; ++i) { scene.mCameras[i] = new aiCamera(); ReadBinaryCamera(stream, scene.mCameras[i]); } } } var aiOrigin_CUR = 0; var aiOrigin_BEG = 1; function extendStream(stream) { stream.readOffset = 0; stream.Seek = function(off, ori) { if (ori == aiOrigin_CUR) stream.readOffset += off; if (ori == aiOrigin_BEG) stream.readOffset = off; }; stream.ReadBytes = function(buff, size, n) { var bytes = size * n; for (let i = 0; i < bytes; i++) buff[i] = Read_uint8_t(this); }; stream.subArray32 = function(start, end) { var newbuff = this.buffer.slice(start, end); return new Float32Array(newbuff); }; stream.subArrayUint16 = function(start, end) { var newbuff = this.buffer.slice(start, end); return new Uint16Array(newbuff); }; stream.subArrayUint8 = function(start, end) { var newbuff = this.buffer.slice(start, end); return new Uint8Array(newbuff); }; stream.subArrayUint32 = function(start, end) { var newbuff = this.buffer.slice(start, end); return new Uint32Array(newbuff); }; } var shortened, compressed; function InternReadFile(pFiledata) { var pScene = new aiScene(); var stream = new DataView(pFiledata); extendStream(stream); stream.Seek(44, aiOrigin_CUR); pScene.versionMajor = Read_unsigned_int(stream); pScene.versionMinor = Read_unsigned_int(stream); pScene.versionRevision = Read_unsigned_int(stream); pScene.compileFlags = Read_unsigned_int(stream); shortened = Read_uint16_t(stream) > 0; compressed = Read_uint16_t(stream) > 0; if (shortened) throw "Shortened binaries are not supported!"; stream.Seek(256, aiOrigin_CUR); stream.Seek(128, aiOrigin_CUR); stream.Seek(64, aiOrigin_CUR); if (compressed) { var uncompressedSize = Read_uint32_t(stream); var compressedSize = stream.FileSize() - stream.Tell(); var compressedData = []; stream.Read(compressedData, 1, compressedSize); var uncompressedData = []; uncompress(uncompressedData, uncompressedSize, compressedData, compressedSize); ReadBinaryScene(new ArrayBuffer(uncompressedData), pScene); } else ReadBinaryScene(stream, pScene); return pScene.toTHREE(); } return InternReadFile(buffer); } }; //#endregion //#region node_modules/three-stdlib/loaders/MDDLoader.js var MDDLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.load(url, function(data) { onLoad(scope.parse(data)); }, onProgress, onError); } parse(data) { const view = new DataView(data); const totalFrames = view.getUint32(0); const totalPoints = view.getUint32(4); let offset = 8; const times = new Float32Array(totalFrames); const values = new Float32Array(totalFrames * totalFrames).fill(0); for (let i = 0; i < totalFrames; i++) { times[i] = view.getFloat32(offset); offset += 4; values[totalFrames * i + i] = 1; } const track = new NumberKeyframeTrack(".morphTargetInfluences", times, values); const clip = new AnimationClip("default", times[times.length - 1], [track]); const morphTargets = []; for (let i = 0; i < totalFrames; i++) { const morphTarget = new Float32Array(totalPoints * 3); for (let j = 0; j < totalPoints; j++) { const stride = j * 3; morphTarget[stride + 0] = view.getFloat32(offset); offset += 4; morphTarget[stride + 1] = view.getFloat32(offset); offset += 4; morphTarget[stride + 2] = view.getFloat32(offset); offset += 4; } const attribute = new BufferAttribute(morphTarget, 3); attribute.name = "morph_" + i; morphTargets.push(attribute); } return { morphTargets, clip }; } }; //#endregion //#region node_modules/three-stdlib/loaders/EXRLoader.js var hasColorSpace = version >= 152; var EXRLoader = class extends DataTextureLoader { constructor(manager) { super(manager); this.type = HalfFloatType; } parse(buffer) { const USHORT_RANGE = 65536; const BITMAP_SIZE = 8192; const HUF_DECBITS = 14; const HUF_ENCSIZE = 65537; 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 = 65 - 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 i = 0; i < USHORT_RANGE; ++i) if (i == 0 || bitmap[i >> 3] & 1 << (i & 7)) lut[k++] = i; var n = k - 1; while (k < USHORT_RANGE) lut[k++] = 0; return n; } function hufClearDecTable(hdec) { for (var i = 0; i < HUF_DECSIZE; i++) { hdec[i] = {}; hdec[i].len = 0; hdec[i].lit = 0; hdec[i].p = null; } } const getBitsReturn = { l: 0, c: 0, lc: 0 }; function getBits(nBits, c, lc, uInt8Array2, inOffset) { while (lc < nBits) { c = c << 8 | parseUint8Array(uInt8Array2, inOffset); lc += 8; } lc -= nBits; getBitsReturn.l = c >> lc & (1 << nBits) - 1; getBitsReturn.c = c; getBitsReturn.lc = lc; } const hufTableBuffer = new Array(59); function hufCanonicalCodeTable(hcode) { for (var i = 0; i <= 58; ++i) hufTableBuffer[i] = 0; for (var i = 0; i < HUF_ENCSIZE; ++i) hufTableBuffer[hcode[i]] += 1; var c = 0; for (var i = 58; i > 0; --i) { var nc = c + hufTableBuffer[i] >> 1; hufTableBuffer[i] = c; c = nc; } for (var i = 0; i < HUF_ENCSIZE; ++i) { var l = hcode[i]; if (l > 0) hcode[i] = l | hufTableBuffer[l]++ << 6; } } function hufUnpackEncTable(uInt8Array2, inDataView, inOffset, ni, im, iM, hcode) { var p = inOffset; var c = 0; var lc = 0; for (; im <= iM; im++) { if (p.value - inOffset.value > ni) return false; getBits(6, c, lc, uInt8Array2, p); var l = getBitsReturn.l; c = getBitsReturn.c; lc = getBitsReturn.lc; hcode[im] = l; if (l == LONG_ZEROCODE_RUN) { if (p.value - inOffset.value > ni) throw "Something wrong with hufUnpackEncTable"; getBits(8, c, lc, uInt8Array2, p); var zerun = getBitsReturn.l + SHORTEST_LONG_RUN; c = getBitsReturn.c; lc = getBitsReturn.lc; if (im + zerun > iM + 1) throw "Something wrong with hufUnpackEncTable"; while (zerun--) hcode[im++] = 0; im--; } else if (l >= SHORT_ZEROCODE_RUN) { var zerun = l - 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 c = hufCode(hcode[im]); var l = hufLength(hcode[im]); if (c >> l) throw "Invalid table entry"; if (l > HUF_DECBITS) { var pl = hdecod[c >> l - HUF_DECBITS]; if (pl.len) throw "Invalid table entry"; pl.lit++; if (pl.p) { var p = pl.p; pl.p = new Array(pl.lit); for (var i = 0; i < pl.lit - 1; ++i) pl.p[i] = p[i]; } else pl.p = new Array(1); pl.p[pl.lit - 1] = im; } else if (l) { var plOffset = 0; for (var i = 1 << HUF_DECBITS - l; i > 0; i--) { var pl = hdecod[(c << HUF_DECBITS - l) + plOffset]; if (pl.len || pl.p) throw "Invalid table entry"; pl.len = l; pl.lit = im; plOffset++; } } } return true; } const getCharReturn = { c: 0, lc: 0 }; function getChar(c, lc, uInt8Array2, inOffset) { c = c << 8 | parseUint8Array(uInt8Array2, inOffset); lc += 8; getCharReturn.c = c; getCharReturn.lc = lc; } const getCodeReturn = { c: 0, lc: 0 }; function getCode(po, rlc, c, lc, uInt8Array2, inDataView, inOffset, outBuffer, outBufferOffset, outBufferEndOffset) { if (po == rlc) { if (lc < 8) { getChar(c, lc, uInt8Array2, inOffset); c = getCharReturn.c; lc = getCharReturn.lc; } lc -= 8; var cs = c >> lc; var cs = new Uint8Array([cs])[0]; if (outBufferOffset.value + cs > outBufferEndOffset) return false; var s = outBuffer[outBufferOffset.value - 1]; while (cs-- > 0) outBuffer[outBufferOffset.value++] = s; } else if (outBufferOffset.value < outBufferEndOffset) outBuffer[outBufferOffset.value++] = po; else return false; getCodeReturn.c = c; getCodeReturn.lc = lc; } 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(l, h) { var ls = Int16(l); var hi = Int16(h); var ai = ls + (hi & 1) + (hi >> 1); var as = ai; var bs = ai - hi; wdec14Return.a = as; wdec14Return.b = bs; } function wdec16(l, h) { var m = UInt16(l); var d = UInt16(h); var bb = m - (d >> 1) & MOD_MASK; wdec14Return.a = d + bb - A_OFFSET & MOD_MASK; wdec14Return.b = bb; } function wav2Decode(buffer2, j, nx, ox, ny, oy, mx) { var w14 = mx < 16384; var n = nx > ny ? ny : nx; var p = 1; var p2; while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; while (p >= 1) { var py = 0; var ey = py + oy * (ny - p2); var oy1 = oy * p; var oy2 = oy * p2; var ox1 = ox * p; var ox2 = ox * p2; var i00, i01, i10, i11; for (; py <= ey; py += oy2) { var px = py; var ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { var p01 = px + ox1; var p10 = px + oy1; var p11 = p10 + ox1; if (w14) { wdec14(buffer2[px + j], buffer2[p10 + j]); i00 = wdec14Return.a; i10 = wdec14Return.b; wdec14(buffer2[p01 + j], buffer2[p11 + j]); i01 = wdec14Return.a; i11 = wdec14Return.b; wdec14(i00, i01); buffer2[px + j] = wdec14Return.a; buffer2[p01 + j] = wdec14Return.b; wdec14(i10, i11); buffer2[p10 + j] = wdec14Return.a; buffer2[p11 + j] = wdec14Return.b; } else { wdec16(buffer2[px + j], buffer2[p10 + j]); i00 = wdec14Return.a; i10 = wdec14Return.b; wdec16(buffer2[p01 + j], buffer2[p11 + j]); i01 = wdec14Return.a; i11 = wdec14Return.b; wdec16(i00, i01); buffer2[px + j] = wdec14Return.a; buffer2[p01 + j] = wdec14Return.b; wdec16(i10, i11); buffer2[p10 + j] = wdec14Return.a; buffer2[p11 + j] = wdec14Return.b; } } if (nx & p) { var p10 = px + oy1; if (w14) wdec14(buffer2[px + j], buffer2[p10 + j]); else wdec16(buffer2[px + j], buffer2[p10 + j]); i00 = wdec14Return.a; buffer2[p10 + j] = wdec14Return.b; buffer2[px + j] = i00; } } if (ny & p) { var px = py; var ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { var p01 = px + ox1; if (w14) wdec14(buffer2[px + j], buffer2[p01 + j]); else wdec16(buffer2[px + j], buffer2[p01 + j]); i00 = wdec14Return.a; buffer2[p01 + j] = wdec14Return.b; buffer2[px + j] = i00; } } p2 = p; p >>= 1; } return py; } function hufDecode(encodingTable, decodingTable, uInt8Array2, inDataView, inOffset, ni, rlc, no, outBuffer, outOffset) { var c = 0; var lc = 0; var outBufferEndOffset = no; var inOffsetEnd = Math.trunc(inOffset.value + (ni + 7) / 8); while (inOffset.value < inOffsetEnd) { getChar(c, lc, uInt8Array2, inOffset); c = getCharReturn.c; lc = getCharReturn.lc; while (lc >= HUF_DECBITS) { var pl = decodingTable[c >> lc - HUF_DECBITS & HUF_DECMASK]; if (pl.len) { lc -= pl.len; getCode(pl.lit, rlc, c, lc, uInt8Array2, inDataView, inOffset, outBuffer, outOffset, outBufferEndOffset); c = getCodeReturn.c; lc = getCodeReturn.lc; } else { if (!pl.p) throw "hufDecode issues"; var j; for (j = 0; j < pl.lit; j++) { var l = hufLength(encodingTable[pl.p[j]]); while (lc < l && inOffset.value < inOffsetEnd) { getChar(c, lc, uInt8Array2, inOffset); c = getCharReturn.c; lc = getCharReturn.lc; } if (lc >= l) { if (hufCode(encodingTable[pl.p[j]]) == (c >> lc - l & (1 << l) - 1)) { lc -= l; getCode(pl.p[j], rlc, c, lc, uInt8Array2, inDataView, inOffset, outBuffer, outOffset, outBufferEndOffset); c = getCodeReturn.c; lc = getCodeReturn.lc; break; } } } if (j == pl.lit) throw "hufDecode issues"; } } } var i = 8 - ni & 7; c >>= i; lc -= i; while (lc > 0) { var pl = decodingTable[c << HUF_DECBITS - lc & HUF_DECMASK]; if (pl.len) { lc -= pl.len; getCode(pl.lit, rlc, c, lc, uInt8Array2, inDataView, inOffset, outBuffer, outOffset, outBufferEndOffset); c = getCodeReturn.c; lc = 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); hufUnpackEncTable(uInt8Array2, inDataView, inOffset, nCompressed - (inOffset.value - initialInOffset), 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 i = 0; i < nData; ++i) data[i] = lut[data[i]]; } function predictor(source) { for (var t = 1; t < source.length; t++) source[t] = source[t - 1] + source[t] - 128; } function interleaveScalar(source, out) { var t1 = 0; var t2 = Math.floor((source.length + 1) / 2); var s = 0; var stop = source.length - 1; while (true) { if (s > stop) break; out[s++] = source[t1++]; if (s > stop) break; out[s++] = source[t2++]; } } function decodeRunLength(source) { var size = source.byteLength; var out = new Array(); var p = 0; var reader = new DataView(source); while (size > 0) { var l = reader.getInt8(p++); if (l < 0) { var count = -l; size -= count + 1; for (var i = 0; i < count; i++) out.push(reader.getUint8(p++)); } else { var count = l; size -= 2; var value = reader.getUint8(p++); for (var i = 0; i < count + 1; i++) out.push(value); } } return out; } 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 a = .5 * Math.cos(3.14159 / 4); const b = .5 * Math.cos(3.14159 / 16); const c = .5 * Math.cos(3.14159 / 8); const d = .5 * Math.cos(3 * 3.14159 / 16); const e = .5 * Math.cos(5 * 3.14159 / 16); const f = .5 * Math.cos(3 * 3.14159 / 8); const g = .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] = c * data[rowPtr + 2]; alpha[1] = f * data[rowPtr + 2]; alpha[2] = c * data[rowPtr + 6]; alpha[3] = f * data[rowPtr + 6]; beta[0] = b * data[rowPtr + 1] + d * data[rowPtr + 3] + e * data[rowPtr + 5] + g * data[rowPtr + 7]; beta[1] = d * data[rowPtr + 1] - g * data[rowPtr + 3] - b * data[rowPtr + 5] - e * data[rowPtr + 7]; beta[2] = e * data[rowPtr + 1] - b * data[rowPtr + 3] + g * data[rowPtr + 5] + d * data[rowPtr + 7]; beta[3] = g * data[rowPtr + 1] - e * data[rowPtr + 3] + d * data[rowPtr + 5] - b * data[rowPtr + 7]; theta[0] = a * (data[rowPtr + 0] + data[rowPtr + 4]); theta[3] = a * (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] = c * data[16 + column]; alpha[1] = f * data[16 + column]; alpha[2] = c * data[48 + column]; alpha[3] = f * data[48 + column]; beta[0] = b * data[8 + column] + d * data[24 + column] + e * data[40 + column] + g * data[56 + column]; beta[1] = d * data[8 + column] - g * data[24 + column] - b * data[40 + column] - e * data[56 + column]; beta[2] = e * data[8 + column] - b * data[24 + column] + g * data[40 + column] + d * data[56 + column]; beta[3] = g * data[8 + column] - e * data[24 + column] + d * data[40 + column] - b * data[56 + column]; theta[0] = a * (data[column] + data[32 + column]); theta[3] = a * (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 i = 0; i < 64; ++i) { var y = data[0][i]; var cb = data[1][i]; var cr = data[2][i]; data[0][i] = y + 1.5747 * cr; data[1][i] = y - .1873 * cb - .4682 * cr; data[2][i] = y + 1.8556 * cb; } } function convertToHalf(src, dst, idx) { for (var i = 0; i < 64; ++i) dst[idx + i] = DataUtils.toHalfFloat(toLinear(src[i])); } function toLinear(float) { if (float <= 1) return Math.sign(float) * Math.pow(Math.abs(float), 2.2); else return Math.sign(float) * Math.pow(logBase, Math.abs(float) - 1); } function uncompressRAW(info) { return new DataView(info.array.buffer, info.offset.value, info.size); } function uncompressRLE(info) { 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 rawBuffer = unzlibSync(info.array.slice(info.offset.value, info.offset.value + info.size)); 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 i = 0; i < info.channels; i++) { pizChannelData[i] = {}; pizChannelData[i]["start"] = outBufferEnd; pizChannelData[i]["end"] = pizChannelData[i]["start"]; pizChannelData[i]["nx"] = info.width; pizChannelData[i]["ny"] = info.lines; pizChannelData[i]["size"] = info.type; outBufferEnd += pizChannelData[i].nx * pizChannelData[i].ny * pizChannelData[i].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 i = 0; i < maxNonZero - minNonZero + 1; i++) bitmap[i + minNonZero] = parseUint8(inDataView, inOffset); var lut = new Uint16Array(USHORT_RANGE); var maxValue = reverseLutFromBitmap(bitmap, lut); var length = parseUint32(inDataView, inOffset); hufUncompress(info.array, inDataView, inOffset, length, outBuffer, outBufferEnd); for (var i = 0; i < info.channels; ++i) { var cd = pizChannelData[i]; for (var j = 0; j < pizChannelData[i].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 c = 0; c < info.channels; c++) { var cd = pizChannelData[c]; var n = cd.nx * cd.size; var cp = new Uint8Array(outBuffer.buffer, cd.end * INT16_SIZE, n * INT16_SIZE); tmpBuffer.set(cp, tmpOffset2); tmpOffset2 += n * INT16_SIZE; cd.end += n; } return new DataView(tmpBuffer.buffer); } function uncompressPXR(info) { var rawBuffer = unzlibSync(info.array.slice(info.offset.value, info.offset.value + info.size)); 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 c = 0; c < info.channels; c++) { 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 index = new Int8Array([csc])[0]; var type = parseUint8(inDataView, inOffset); channelRules.push({ name, index, type, compression }); ruleSize -= name.length + 3; } var channels = EXRHeader.channels; var channelData = new Array(info.channels); for (var i = 0; i < info.channels; ++i) { var cd = channelData[i] = {}; var channel = channels[i]; 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 i = 0; i < channelRules.length; ++i) { var rule = channelRules[i]; 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 i = 0; i < rowOffsets.length; ++i) rowOffsets[i] = 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 i = 0; i < channelData.length; ++i) { var cd = channelData[i]; 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[i][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(buffer2, offset2) { var uintBuffer = new Uint8Array(buffer2); 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(buffer2, offset2, size) { var stringValue = new TextDecoder().decode(new Uint8Array(buffer2).slice(offset2.value, offset2.value + size)); offset2.value = offset2.value + size; return stringValue; } function parseRational(dataView, offset2) { return [parseInt32(dataView, offset2), parseUint32(dataView, offset2)]; } function parseTimecode(dataView, offset2) { return [parseUint32(dataView, offset2), parseUint32(dataView, offset2)]; } 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(buffer2, offset2) { return decodeFloat16(parseUint16(buffer2, offset2)); } function parseChlist(dataView, buffer2, offset2, size) { var startOffset = offset2.value; var channels = []; while (offset2.value < startOffset + size - 1) { var name = parseNullTerminatedString(buffer2, 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) { return { redX: parseFloat32(dataView, offset2), redY: parseFloat32(dataView, offset2), greenX: parseFloat32(dataView, offset2), greenY: parseFloat32(dataView, offset2), blueX: parseFloat32(dataView, offset2), blueY: parseFloat32(dataView, offset2), whiteX: parseFloat32(dataView, offset2), whiteY: parseFloat32(dataView, offset2) }; } function parseCompression(dataView, offset2) { return [ "NO_COMPRESSION", "RLE_COMPRESSION", "ZIPS_COMPRESSION", "ZIP_COMPRESSION", "PIZ_COMPRESSION", "PXR24_COMPRESSION", "B44_COMPRESSION", "B44A_COMPRESSION", "DWAA_COMPRESSION", "DWAB_COMPRESSION" ][parseUint8(dataView, offset2)]; } function parseBox2i(dataView, offset2) { return { xMin: parseUint32(dataView, offset2), yMin: parseUint32(dataView, offset2), xMax: parseUint32(dataView, offset2), yMax: parseUint32(dataView, offset2) }; } function parseLineOrder(dataView, offset2) { return ["INCREASING_Y"][parseUint8(dataView, offset2)]; } function parseV2f(dataView, offset2) { return [parseFloat32(dataView, offset2), parseFloat32(dataView, offset2)]; } function parseV3f(dataView, offset2) { return [ parseFloat32(dataView, offset2), parseFloat32(dataView, offset2), parseFloat32(dataView, offset2) ]; } function parseValue(dataView, buffer2, offset2, type, size) { if (type === "string" || type === "stringvector" || type === "iccProfile") return parseFixedLengthString(buffer2, offset2, size); else if (type === "chlist") return parseChlist(dataView, buffer2, offset2, size); 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 += size; return "skipped"; } else { offset2.value += size; return; } } function parseHeader(dataView, buffer2, 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(buffer2, offset2); if (attributeName == 0) keepReading = false; else { var attributeType = parseNullTerminatedString(buffer2, offset2); var attributeValue = parseValue(dataView, buffer2, offset2, attributeType, parseUint32(dataView, offset2)); if (attributeValue === void 0) console.warn(`EXRLoader.parse: skipped unknown header attribute type '${attributeType}'.`); else EXRHeader2[attributeName] = attributeValue; } } if ((spec & -5) != 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 i = 0; i < EXRDecoder2.blockCount; i++) parseInt64(dataView, offset2); EXRDecoder2.outputChannels = EXRDecoder2.channels == 3 ? 4 : EXRDecoder2.channels; const size = EXRDecoder2.width * EXRDecoder2.height * EXRDecoder2.outputChannels; switch (outputType) { case FloatType: EXRDecoder2.byteArray = new Float32Array(size); if (EXRDecoder2.channels < EXRDecoder2.outputChannels) EXRDecoder2.byteArray.fill(1, 0, size); break; case HalfFloatType: EXRDecoder2.byteArray = new Uint16Array(size); if (EXRDecoder2.channels < EXRDecoder2.outputChannels) EXRDecoder2.byteArray.fill(15360, 0, size); 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(buffer); const uInt8Array = new Uint8Array(buffer); const offset = { value: 0 }; const EXRHeader = parseHeader(bufferDataView, buffer, 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 viewer = EXRDecoder.size < EXRDecoder.lines * EXRDecoder.bytesPerLine ? 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); } }; //#endregion //#region node_modules/three-stdlib/loaders/3MFLoader.js var ThreeMFLoader = class extends Loader { constructor(manager) { super(manager); this.availableExtensions = []; } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(buffer) { try { onLoad(scope.parse(buffer)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(data) { const scope = this; const textureLoader = new TextureLoader(this.manager); function loadDocument(data2) { let zip = null; let file = null; let relsName; let modelRelsName; const modelPartNames = []; const texturesPartNames = []; let modelRels; const modelParts = {}; const printTicketParts = {}; const texturesParts = {}; const otherParts = {}; try { zip = unzipSync(new Uint8Array(data2)); } catch (e) { if (e instanceof ReferenceError) { console.error("THREE.3MFLoader: fflate missing and file is compressed."); return null; } } for (file in zip) if (file.match(/\_rels\/.rels$/)) relsName = file; else if (file.match(/3D\/_rels\/.*\.model\.rels$/)) modelRelsName = file; else if (file.match(/^3D\/.*\.model$/)) modelPartNames.push(file); else if (file.match(/^3D\/Metadata\/.*\.xml$/)); else if (file.match(/^3D\/Textures?\/.*/)) texturesPartNames.push(file); else if (file.match(/^3D\/Other\/.*/)); const relsView = zip[relsName]; const rels = parseRelsXml(decodeText$1(relsView)); if (modelRelsName) { const relsView2 = zip[modelRelsName]; modelRels = parseRelsXml(decodeText$1(relsView2)); } for (let i = 0; i < modelPartNames.length; i++) { const modelPart = modelPartNames[i]; const view = zip[modelPart]; const fileText = decodeText$1(view); const xmlData = new DOMParser().parseFromString(fileText, "application/xml"); if (xmlData.documentElement.nodeName.toLowerCase() !== "model") console.error("THREE.3MFLoader: Error loading 3MF - no 3MF document found: ", modelPart); const modelNode = xmlData.querySelector("model"); const extensions = {}; for (let i2 = 0; i2 < modelNode.attributes.length; i2++) { const attr = modelNode.attributes[i2]; if (attr.name.match(/^xmlns:(.+)$/)) extensions[attr.value] = RegExp.$1; } const modelData = parseModelNode(modelNode); modelData["xml"] = modelNode; if (0 < Object.keys(extensions).length) modelData["extensions"] = extensions; modelParts[modelPart] = modelData; } for (let i = 0; i < texturesPartNames.length; i++) { const texturesPartName = texturesPartNames[i]; texturesParts[texturesPartName] = zip[texturesPartName].buffer; } return { rels, modelRels, model: modelParts, printTicket: printTicketParts, texture: texturesParts, other: otherParts }; } function parseRelsXml(relsFileText) { const relationships = []; const relsNodes = new DOMParser().parseFromString(relsFileText, "application/xml").querySelectorAll("Relationship"); for (let i = 0; i < relsNodes.length; i++) { const relsNode = relsNodes[i]; const relationship = { target: relsNode.getAttribute("Target"), id: relsNode.getAttribute("Id"), type: relsNode.getAttribute("Type") }; relationships.push(relationship); } return relationships; } function parseMetadataNodes(metadataNodes) { const metadataData = {}; for (let i = 0; i < metadataNodes.length; i++) { const metadataNode = metadataNodes[i]; const name = metadataNode.getAttribute("name"); if (0 <= [ "Title", "Designer", "Description", "Copyright", "LicenseTerms", "Rating", "CreationDate", "ModificationDate" ].indexOf(name)) metadataData[name] = metadataNode.textContent; } return metadataData; } function parseBasematerialsNode(basematerialsNode) { const basematerialsData = { id: basematerialsNode.getAttribute("id"), basematerials: [] }; const basematerialNodes = basematerialsNode.querySelectorAll("base"); for (let i = 0; i < basematerialNodes.length; i++) { const basematerialNode = basematerialNodes[i]; const basematerialData = parseBasematerialNode(basematerialNode); basematerialData.index = i; basematerialsData.basematerials.push(basematerialData); } return basematerialsData; } function parseTexture2DNode(texture2DNode) { return { id: texture2DNode.getAttribute("id"), path: texture2DNode.getAttribute("path"), contenttype: texture2DNode.getAttribute("contenttype"), tilestyleu: texture2DNode.getAttribute("tilestyleu"), tilestylev: texture2DNode.getAttribute("tilestylev"), filter: texture2DNode.getAttribute("filter") }; } function parseTextures2DGroupNode(texture2DGroupNode) { const texture2DGroupData = { id: texture2DGroupNode.getAttribute("id"), texid: texture2DGroupNode.getAttribute("texid"), displaypropertiesid: texture2DGroupNode.getAttribute("displaypropertiesid") }; const tex2coordNodes = texture2DGroupNode.querySelectorAll("tex2coord"); const uvs = []; for (let i = 0; i < tex2coordNodes.length; i++) { const tex2coordNode = tex2coordNodes[i]; const u = tex2coordNode.getAttribute("u"); const v = tex2coordNode.getAttribute("v"); uvs.push(parseFloat(u), parseFloat(v)); } texture2DGroupData["uvs"] = new Float32Array(uvs); return texture2DGroupData; } function parseColorGroupNode(colorGroupNode) { const colorGroupData = { id: colorGroupNode.getAttribute("id"), displaypropertiesid: colorGroupNode.getAttribute("displaypropertiesid") }; const colorNodes = colorGroupNode.querySelectorAll("color"); const colors = []; const colorObject = new Color(); for (let i = 0; i < colorNodes.length; i++) { const color = colorNodes[i].getAttribute("color"); colorObject.setStyle(color.substring(0, 7)); colorObject.convertSRGBToLinear(); colors.push(colorObject.r, colorObject.g, colorObject.b); } colorGroupData["colors"] = new Float32Array(colors); return colorGroupData; } function parseMetallicDisplaypropertiesNode(metallicDisplaypropetiesNode) { const metallicDisplaypropertiesData = { id: metallicDisplaypropetiesNode.getAttribute("id") }; const metallicNodes = metallicDisplaypropetiesNode.querySelectorAll("pbmetallic"); const metallicData = []; for (let i = 0; i < metallicNodes.length; i++) { const metallicNode = metallicNodes[i]; metallicData.push({ name: metallicNode.getAttribute("name"), metallicness: parseFloat(metallicNode.getAttribute("metallicness")), roughness: parseFloat(metallicNode.getAttribute("roughness")) }); } metallicDisplaypropertiesData.data = metallicData; return metallicDisplaypropertiesData; } function parseBasematerialNode(basematerialNode) { const basematerialData = {}; basematerialData["name"] = basematerialNode.getAttribute("name"); basematerialData["displaycolor"] = basematerialNode.getAttribute("displaycolor"); basematerialData["displaypropertiesid"] = basematerialNode.getAttribute("displaypropertiesid"); return basematerialData; } function parseMeshNode(meshNode) { const meshData = {}; const vertices = []; const vertexNodes = meshNode.querySelectorAll("vertices vertex"); for (let i = 0; i < vertexNodes.length; i++) { const vertexNode = vertexNodes[i]; const x = vertexNode.getAttribute("x"); const y = vertexNode.getAttribute("y"); const z = vertexNode.getAttribute("z"); vertices.push(parseFloat(x), parseFloat(y), parseFloat(z)); } meshData["vertices"] = new Float32Array(vertices); const triangleProperties = []; const triangles = []; const triangleNodes = meshNode.querySelectorAll("triangles triangle"); for (let i = 0; i < triangleNodes.length; i++) { const triangleNode = triangleNodes[i]; const v1 = triangleNode.getAttribute("v1"); const v2 = triangleNode.getAttribute("v2"); const v3 = triangleNode.getAttribute("v3"); const p1 = triangleNode.getAttribute("p1"); const p2 = triangleNode.getAttribute("p2"); const p3 = triangleNode.getAttribute("p3"); const pid = triangleNode.getAttribute("pid"); const triangleProperty = {}; triangleProperty["v1"] = parseInt(v1, 10); triangleProperty["v2"] = parseInt(v2, 10); triangleProperty["v3"] = parseInt(v3, 10); triangles.push(triangleProperty["v1"], triangleProperty["v2"], triangleProperty["v3"]); if (p1) triangleProperty["p1"] = parseInt(p1, 10); if (p2) triangleProperty["p2"] = parseInt(p2, 10); if (p3) triangleProperty["p3"] = parseInt(p3, 10); if (pid) triangleProperty["pid"] = pid; if (0 < Object.keys(triangleProperty).length) triangleProperties.push(triangleProperty); } meshData["triangleProperties"] = triangleProperties; meshData["triangles"] = new Uint32Array(triangles); return meshData; } function parseComponentsNode(componentsNode) { const components = []; const componentNodes = componentsNode.querySelectorAll("component"); for (let i = 0; i < componentNodes.length; i++) { const componentNode = componentNodes[i]; const componentData = parseComponentNode(componentNode); components.push(componentData); } return components; } function parseComponentNode(componentNode) { const componentData = {}; componentData["objectId"] = componentNode.getAttribute("objectid"); const transform = componentNode.getAttribute("transform"); if (transform) componentData["transform"] = parseTransform(transform); return componentData; } function parseTransform(transform) { const t = []; transform.split(" ").forEach(function(s) { t.push(parseFloat(s)); }); const matrix = new Matrix4(); matrix.set(t[0], t[3], t[6], t[9], t[1], t[4], t[7], t[10], t[2], t[5], t[8], t[11], 0, 0, 0, 1); return matrix; } function parseObjectNode(objectNode) { const objectData = { type: objectNode.getAttribute("type") }; const id = objectNode.getAttribute("id"); if (id) objectData["id"] = id; const pid = objectNode.getAttribute("pid"); if (pid) objectData["pid"] = pid; const pindex = objectNode.getAttribute("pindex"); if (pindex) objectData["pindex"] = pindex; const thumbnail = objectNode.getAttribute("thumbnail"); if (thumbnail) objectData["thumbnail"] = thumbnail; const partnumber = objectNode.getAttribute("partnumber"); if (partnumber) objectData["partnumber"] = partnumber; const name = objectNode.getAttribute("name"); if (name) objectData["name"] = name; const meshNode = objectNode.querySelector("mesh"); if (meshNode) objectData["mesh"] = parseMeshNode(meshNode); const componentsNode = objectNode.querySelector("components"); if (componentsNode) objectData["components"] = parseComponentsNode(componentsNode); return objectData; } function parseResourcesNode(resourcesNode) { const resourcesData = {}; resourcesData["basematerials"] = {}; const basematerialsNodes = resourcesNode.querySelectorAll("basematerials"); for (let i = 0; i < basematerialsNodes.length; i++) { const basematerialsNode = basematerialsNodes[i]; const basematerialsData = parseBasematerialsNode(basematerialsNode); resourcesData["basematerials"][basematerialsData["id"]] = basematerialsData; } resourcesData["texture2d"] = {}; const textures2DNodes = resourcesNode.querySelectorAll("texture2d"); for (let i = 0; i < textures2DNodes.length; i++) { const textures2DNode = textures2DNodes[i]; const texture2DData = parseTexture2DNode(textures2DNode); resourcesData["texture2d"][texture2DData["id"]] = texture2DData; } resourcesData["colorgroup"] = {}; const colorGroupNodes = resourcesNode.querySelectorAll("colorgroup"); for (let i = 0; i < colorGroupNodes.length; i++) { const colorGroupNode = colorGroupNodes[i]; const colorGroupData = parseColorGroupNode(colorGroupNode); resourcesData["colorgroup"][colorGroupData["id"]] = colorGroupData; } resourcesData["pbmetallicdisplayproperties"] = {}; const pbmetallicdisplaypropertiesNodes = resourcesNode.querySelectorAll("pbmetallicdisplayproperties"); for (let i = 0; i < pbmetallicdisplaypropertiesNodes.length; i++) { const pbmetallicdisplaypropertiesNode = pbmetallicdisplaypropertiesNodes[i]; const pbmetallicdisplaypropertiesData = parseMetallicDisplaypropertiesNode(pbmetallicdisplaypropertiesNode); resourcesData["pbmetallicdisplayproperties"][pbmetallicdisplaypropertiesData["id"]] = pbmetallicdisplaypropertiesData; } resourcesData["texture2dgroup"] = {}; const textures2DGroupNodes = resourcesNode.querySelectorAll("texture2dgroup"); for (let i = 0; i < textures2DGroupNodes.length; i++) { const textures2DGroupNode = textures2DGroupNodes[i]; const textures2DGroupData = parseTextures2DGroupNode(textures2DGroupNode); resourcesData["texture2dgroup"][textures2DGroupData["id"]] = textures2DGroupData; } resourcesData["object"] = {}; const objectNodes = resourcesNode.querySelectorAll("object"); for (let i = 0; i < objectNodes.length; i++) { const objectNode = objectNodes[i]; const objectData = parseObjectNode(objectNode); resourcesData["object"][objectData["id"]] = objectData; } return resourcesData; } function parseBuildNode(buildNode) { const buildData = []; const itemNodes = buildNode.querySelectorAll("item"); for (let i = 0; i < itemNodes.length; i++) { const itemNode = itemNodes[i]; const buildItem = { objectId: itemNode.getAttribute("objectid") }; const transform = itemNode.getAttribute("transform"); if (transform) buildItem["transform"] = parseTransform(transform); buildData.push(buildItem); } return buildData; } function parseModelNode(modelNode) { const modelData = { unit: modelNode.getAttribute("unit") || "millimeter" }; const metadataNodes = modelNode.querySelectorAll("metadata"); if (metadataNodes) modelData["metadata"] = parseMetadataNodes(metadataNodes); const resourcesNode = modelNode.querySelector("resources"); if (resourcesNode) modelData["resources"] = parseResourcesNode(resourcesNode); const buildNode = modelNode.querySelector("build"); if (buildNode) modelData["build"] = parseBuildNode(buildNode); return modelData; } function buildTexture(texture2dgroup, objects2, modelData, textureData) { const texid = texture2dgroup.texid; const texture2d = modelData.resources.texture2d[texid]; if (texture2d) { const data2 = textureData[texture2d.path]; const type = texture2d.contenttype; const blob = new Blob([data2], { type }); const sourceURI = URL.createObjectURL(blob); const texture = textureLoader.load(sourceURI, function() { URL.revokeObjectURL(sourceURI); }); if ("colorSpace" in texture) texture.colorSpace = "srgb"; else texture.encoding = 3001; switch (texture2d.tilestyleu) { case "wrap": texture.wrapS = RepeatWrapping; break; case "mirror": texture.wrapS = MirroredRepeatWrapping; break; case "none": case "clamp": texture.wrapS = ClampToEdgeWrapping; break; default: texture.wrapS = RepeatWrapping; } switch (texture2d.tilestylev) { case "wrap": texture.wrapT = RepeatWrapping; break; case "mirror": texture.wrapT = MirroredRepeatWrapping; break; case "none": case "clamp": texture.wrapT = ClampToEdgeWrapping; break; default: texture.wrapT = RepeatWrapping; } switch (texture2d.filter) { case "auto": texture.magFilter = LinearFilter; texture.minFilter = LinearMipmapLinearFilter; break; case "linear": texture.magFilter = LinearFilter; texture.minFilter = LinearFilter; break; case "nearest": texture.magFilter = NearestFilter; texture.minFilter = NearestFilter; break; default: texture.magFilter = LinearFilter; texture.minFilter = LinearMipmapLinearFilter; } return texture; } else return null; } function buildBasematerialsMeshes(basematerials, triangleProperties, meshData, objects2, modelData, textureData, objectData) { const objectPindex = objectData.pindex; const materialMap = {}; for (let i = 0, l = triangleProperties.length; i < l; i++) { const triangleProperty = triangleProperties[i]; const pindex = triangleProperty.p1 !== void 0 ? triangleProperty.p1 : objectPindex; if (materialMap[pindex] === void 0) materialMap[pindex] = []; materialMap[pindex].push(triangleProperty); } const keys = Object.keys(materialMap); const meshes = []; for (let i = 0, l = keys.length; i < l; i++) { const materialIndex = keys[i]; const trianglePropertiesProps = materialMap[materialIndex]; const basematerialData = basematerials.basematerials[materialIndex]; const material = getBuild(basematerialData, objects2, modelData, textureData, objectData, buildBasematerial); const geometry = new BufferGeometry(); const positionData = []; const vertices = meshData.vertices; for (let j = 0, jl = trianglePropertiesProps.length; j < jl; j++) { const triangleProperty = trianglePropertiesProps[j]; positionData.push(vertices[triangleProperty.v1 * 3 + 0]); positionData.push(vertices[triangleProperty.v1 * 3 + 1]); positionData.push(vertices[triangleProperty.v1 * 3 + 2]); positionData.push(vertices[triangleProperty.v2 * 3 + 0]); positionData.push(vertices[triangleProperty.v2 * 3 + 1]); positionData.push(vertices[triangleProperty.v2 * 3 + 2]); positionData.push(vertices[triangleProperty.v3 * 3 + 0]); positionData.push(vertices[triangleProperty.v3 * 3 + 1]); positionData.push(vertices[triangleProperty.v3 * 3 + 2]); } geometry.setAttribute("position", new Float32BufferAttribute(positionData, 3)); const mesh = new Mesh(geometry, material); meshes.push(mesh); } return meshes; } function buildTexturedMesh(texture2dgroup, triangleProperties, meshData, objects2, modelData, textureData, objectData) { const geometry = new BufferGeometry(); const positionData = []; const uvData = []; const vertices = meshData.vertices; const uvs = texture2dgroup.uvs; for (let i = 0, l = triangleProperties.length; i < l; i++) { const triangleProperty = triangleProperties[i]; positionData.push(vertices[triangleProperty.v1 * 3 + 0]); positionData.push(vertices[triangleProperty.v1 * 3 + 1]); positionData.push(vertices[triangleProperty.v1 * 3 + 2]); positionData.push(vertices[triangleProperty.v2 * 3 + 0]); positionData.push(vertices[triangleProperty.v2 * 3 + 1]); positionData.push(vertices[triangleProperty.v2 * 3 + 2]); positionData.push(vertices[triangleProperty.v3 * 3 + 0]); positionData.push(vertices[triangleProperty.v3 * 3 + 1]); positionData.push(vertices[triangleProperty.v3 * 3 + 2]); uvData.push(uvs[triangleProperty.p1 * 2 + 0]); uvData.push(uvs[triangleProperty.p1 * 2 + 1]); uvData.push(uvs[triangleProperty.p2 * 2 + 0]); uvData.push(uvs[triangleProperty.p2 * 2 + 1]); uvData.push(uvs[triangleProperty.p3 * 2 + 0]); uvData.push(uvs[triangleProperty.p3 * 2 + 1]); } geometry.setAttribute("position", new Float32BufferAttribute(positionData, 3)); geometry.setAttribute("uv", new Float32BufferAttribute(uvData, 2)); return new Mesh(geometry, new MeshPhongMaterial({ map: getBuild(texture2dgroup, objects2, modelData, textureData, objectData, buildTexture), flatShading: true })); } function buildVertexColorMesh(colorgroup, triangleProperties, meshData, objects2, modelData, objectData) { const geometry = new BufferGeometry(); const positionData = []; const colorData = []; const vertices = meshData.vertices; const colors = colorgroup.colors; for (let i = 0, l = triangleProperties.length; i < l; i++) { const triangleProperty = triangleProperties[i]; const v1 = triangleProperty.v1; const v2 = triangleProperty.v2; const v3 = triangleProperty.v3; positionData.push(vertices[v1 * 3 + 0]); positionData.push(vertices[v1 * 3 + 1]); positionData.push(vertices[v1 * 3 + 2]); positionData.push(vertices[v2 * 3 + 0]); positionData.push(vertices[v2 * 3 + 1]); positionData.push(vertices[v2 * 3 + 2]); positionData.push(vertices[v3 * 3 + 0]); positionData.push(vertices[v3 * 3 + 1]); positionData.push(vertices[v3 * 3 + 2]); const p1 = triangleProperty.p1 !== void 0 ? triangleProperty.p1 : objectData.pindex; const p2 = triangleProperty.p2 !== void 0 ? triangleProperty.p2 : p1; const p3 = triangleProperty.p3 !== void 0 ? triangleProperty.p3 : p1; colorData.push(colors[p1 * 3 + 0]); colorData.push(colors[p1 * 3 + 1]); colorData.push(colors[p1 * 3 + 2]); colorData.push(colors[p2 * 3 + 0]); colorData.push(colors[p2 * 3 + 1]); colorData.push(colors[p2 * 3 + 2]); colorData.push(colors[p3 * 3 + 0]); colorData.push(colors[p3 * 3 + 1]); colorData.push(colors[p3 * 3 + 2]); } geometry.setAttribute("position", new Float32BufferAttribute(positionData, 3)); geometry.setAttribute("color", new Float32BufferAttribute(colorData, 3)); return new Mesh(geometry, new MeshPhongMaterial({ vertexColors: true, flatShading: true })); } function buildDefaultMesh(meshData) { const geometry = new BufferGeometry(); geometry.setIndex(new BufferAttribute(meshData["triangles"], 1)); geometry.setAttribute("position", new BufferAttribute(meshData["vertices"], 3)); return new Mesh(geometry, new MeshPhongMaterial({ color: 11184895, flatShading: true })); } function buildMeshes(resourceMap, meshData, objects2, modelData, textureData, objectData) { const keys = Object.keys(resourceMap); const meshes = []; for (let i = 0, il = keys.length; i < il; i++) { const resourceId = keys[i]; const triangleProperties = resourceMap[resourceId]; switch (getResourceType(resourceId, modelData)) { case "material": const basematerials = modelData.resources.basematerials[resourceId]; const newMeshes = buildBasematerialsMeshes(basematerials, triangleProperties, meshData, objects2, modelData, textureData, objectData); for (let j = 0, jl = newMeshes.length; j < jl; j++) meshes.push(newMeshes[j]); break; case "texture": const texture2dgroup = modelData.resources.texture2dgroup[resourceId]; meshes.push(buildTexturedMesh(texture2dgroup, triangleProperties, meshData, objects2, modelData, textureData, objectData)); break; case "vertexColors": const colorgroup = modelData.resources.colorgroup[resourceId]; meshes.push(buildVertexColorMesh(colorgroup, triangleProperties, meshData, objects2, modelData, objectData)); break; case "default": meshes.push(buildDefaultMesh(meshData)); break; default: console.error("THREE.3MFLoader: Unsupported resource type."); } } return meshes; } function getResourceType(pid, modelData) { if (modelData.resources.texture2dgroup[pid] !== void 0) return "texture"; else if (modelData.resources.basematerials[pid] !== void 0) return "material"; else if (modelData.resources.colorgroup[pid] !== void 0) return "vertexColors"; else if (pid === "default") return "default"; else return; } function analyzeObject(modelData, meshData, objectData) { const resourceMap = {}; const triangleProperties = meshData["triangleProperties"]; const objectPid = objectData.pid; for (let i = 0, l = triangleProperties.length; i < l; i++) { const triangleProperty = triangleProperties[i]; let pid = triangleProperty.pid !== void 0 ? triangleProperty.pid : objectPid; if (pid === void 0) pid = "default"; if (resourceMap[pid] === void 0) resourceMap[pid] = []; resourceMap[pid].push(triangleProperty); } return resourceMap; } function buildGroup(meshData, objects2, modelData, textureData, objectData) { const group = new Group(); const meshes = buildMeshes(analyzeObject(modelData, meshData, objectData), meshData, objects2, modelData, textureData, objectData); for (let i = 0, l = meshes.length; i < l; i++) group.add(meshes[i]); return group; } function applyExtensions(extensions, meshData, modelXml) { if (!extensions) return; const availableExtensions = []; const keys = Object.keys(extensions); for (let i = 0; i < keys.length; i++) { const ns = keys[i]; for (let j = 0; j < scope.availableExtensions.length; j++) { const extension = scope.availableExtensions[j]; if (extension.ns === ns) availableExtensions.push(extension); } } for (let i = 0; i < availableExtensions.length; i++) { const extension = availableExtensions[i]; extension.apply(modelXml, extensions[extension["ns"]], meshData); } } function getBuild(data2, objects2, modelData, textureData, objectData, builder) { if (data2.build !== void 0) return data2.build; data2.build = builder(data2, objects2, modelData, textureData, objectData); return data2.build; } function buildBasematerial(materialData, objects2, modelData) { let material; const displaypropertiesid = materialData.displaypropertiesid; const pbmetallicdisplayproperties = modelData.resources.pbmetallicdisplayproperties; if (displaypropertiesid !== null && pbmetallicdisplayproperties[displaypropertiesid] !== void 0) { const metallicData = pbmetallicdisplayproperties[displaypropertiesid].data[materialData.index]; material = new MeshStandardMaterial({ flatShading: true, roughness: metallicData.roughness, metalness: metallicData.metallicness }); } else material = new MeshPhongMaterial({ flatShading: true }); material.name = materialData.name; const displaycolor = materialData.displaycolor; const color = displaycolor.substring(0, 7); material.color.setStyle(color); material.color.convertSRGBToLinear(); if (displaycolor.length === 9) material.opacity = parseInt(displaycolor.charAt(7) + displaycolor.charAt(8), 16) / 255; return material; } function buildComposite(compositeData, objects2, modelData, textureData) { const composite = new Group(); for (let j = 0; j < compositeData.length; j++) { const component = compositeData[j]; let build2 = objects2[component.objectId]; if (build2 === void 0) { buildObject(component.objectId, objects2, modelData, textureData); build2 = objects2[component.objectId]; } const object3D = build2.clone(); const transform = component.transform; if (transform) object3D.applyMatrix4(transform); composite.add(object3D); } return composite; } function buildObject(objectId, objects2, modelData, textureData) { const objectData = modelData["resources"]["object"][objectId]; if (objectData["mesh"]) { const meshData = objectData["mesh"]; const extensions = modelData["extensions"]; const modelXml = modelData["xml"]; applyExtensions(extensions, meshData, modelXml); objects2[objectData.id] = getBuild(meshData, objects2, modelData, textureData, objectData, buildGroup); } else { const compositeData = objectData["components"]; objects2[objectData.id] = getBuild(compositeData, objects2, modelData, textureData, objectData, buildComposite); } } function buildObjects(data3mf2) { const modelsData = data3mf2.model; const modelRels = data3mf2.modelRels; const objects2 = {}; const modelsKeys = Object.keys(modelsData); const textureData = {}; if (modelRels) for (let i = 0, l = modelRels.length; i < l; i++) { const modelRel = modelRels[i]; const textureKey = modelRel.target.substring(1); if (data3mf2.texture[textureKey]) textureData[modelRel.target] = data3mf2.texture[textureKey]; } for (let i = 0; i < modelsKeys.length; i++) { const modelData = modelsData[modelsKeys[i]]; const objectIds = Object.keys(modelData["resources"]["object"]); for (let j = 0; j < objectIds.length; j++) { const objectId = objectIds[j]; buildObject(objectId, objects2, modelData, textureData); } } return objects2; } function fetch3DModelPart(rels) { for (let i = 0; i < rels.length; i++) { const rel = rels[i]; if (rel.target.split(".").pop().toLowerCase() === "model") return rel; } } function build(objects2, data3mf2) { const group = new Group(); const relationship = fetch3DModelPart(data3mf2["rels"]); const buildData = data3mf2.model[relationship["target"].substring(1)]["build"]; for (let i = 0; i < buildData.length; i++) { const buildItem = buildData[i]; const object3D = objects2[buildItem["objectId"]]; const transform = buildItem["transform"]; if (transform) object3D.applyMatrix4(transform); group.add(object3D); } return group; } const data3mf = loadDocument(data); return build(buildObjects(data3mf), data3mf); } addExtension(extension) { this.availableExtensions.push(extension); } }; //#endregion //#region node_modules/three-stdlib/loaders/XYZLoader.js var XYZLoader = class extends Loader { load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(text) { const lines = text.split("\n"); const vertices = []; const colors = []; for (let line of lines) { line = line.trim(); if (line.charAt(0) === "#") continue; const lineValues = line.split(/\s+/); if (lineValues.length === 3) { vertices.push(parseFloat(lineValues[0])); vertices.push(parseFloat(lineValues[1])); vertices.push(parseFloat(lineValues[2])); } if (lineValues.length === 6) { vertices.push(parseFloat(lineValues[0])); vertices.push(parseFloat(lineValues[1])); vertices.push(parseFloat(lineValues[2])); colors.push(parseFloat(lineValues[3]) / 255); colors.push(parseFloat(lineValues[4]) / 255); colors.push(parseFloat(lineValues[5]) / 255); } } const geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); if (colors.length > 0) geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); return geometry; } }; //#endregion //#region node_modules/three-stdlib/loaders/VTKLoader.js var VTKLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(data) { function parseASCII(data2) { var indices = []; var positions = []; var colors = []; var normals = []; var result; var patWord = /^[^\d.\s-]+/; var pat3Floats = /(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)/g; var patConnectivity = /^(\d+)\s+([\s\d]*)/; var patPOINTS = /^POINTS /; var patPOLYGONS = /^POLYGONS /; var patTRIANGLE_STRIPS = /^TRIANGLE_STRIPS /; var patPOINT_DATA = /^POINT_DATA[ ]+(\d+)/; var patCELL_DATA = /^CELL_DATA[ ]+(\d+)/; var patCOLOR_SCALARS = /^COLOR_SCALARS[ ]+(\w+)[ ]+3/; var patNORMALS = /^NORMALS[ ]+(\w+)[ ]+(\w+)/; var inPointsSection = false; var inPolygonsSection = false; var inTriangleStripSection = false; var inPointDataSection = false; var inCellDataSection = false; var inColorSection = false; var inNormalsSection = false; var lines = data2.split("\n"); for (var i in lines) { var line = lines[i].trim(); if (line.indexOf("DATASET") === 0) { var dataset = line.split(" ")[1]; if (dataset !== "POLYDATA") throw new Error("Unsupported DATASET type: " + dataset); } else if (inPointsSection) while ((result = pat3Floats.exec(line)) !== null) { if (patWord.exec(line) !== null) break; var x = parseFloat(result[1]); var y = parseFloat(result[2]); var z = parseFloat(result[3]); positions.push(x, y, z); } else if (inPolygonsSection) { if ((result = patConnectivity.exec(line)) !== null) { var numVertices = parseInt(result[1]); var inds = result[2].split(/\s+/); if (numVertices >= 3) { var i0 = parseInt(inds[0]); var i1, i2; var k = 1; for (var j = 0; j < numVertices - 2; ++j) { i1 = parseInt(inds[k]); i2 = parseInt(inds[k + 1]); indices.push(i0, i1, i2); k++; } } } } else if (inTriangleStripSection) { if ((result = patConnectivity.exec(line)) !== null) { var numVertices = parseInt(result[1]); var inds = result[2].split(/\s+/); if (numVertices >= 3) { var i0, i1, i2; for (var j = 0; j < numVertices - 2; j++) if (j % 2 === 1) { i0 = parseInt(inds[j]); i1 = parseInt(inds[j + 2]); i2 = parseInt(inds[j + 1]); indices.push(i0, i1, i2); } else { i0 = parseInt(inds[j]); i1 = parseInt(inds[j + 1]); i2 = parseInt(inds[j + 2]); indices.push(i0, i1, i2); } } } } else if (inPointDataSection || inCellDataSection) { if (inColorSection) while ((result = pat3Floats.exec(line)) !== null) { if (patWord.exec(line) !== null) break; var r = parseFloat(result[1]); var g = parseFloat(result[2]); var b = parseFloat(result[3]); colors.push(r, g, b); } else if (inNormalsSection) while ((result = pat3Floats.exec(line)) !== null) { if (patWord.exec(line) !== null) break; var nx = parseFloat(result[1]); var ny = parseFloat(result[2]); var nz = parseFloat(result[3]); normals.push(nx, ny, nz); } } if (patPOLYGONS.exec(line) !== null) { inPolygonsSection = true; inPointsSection = false; inTriangleStripSection = false; } else if (patPOINTS.exec(line) !== null) { inPolygonsSection = false; inPointsSection = true; inTriangleStripSection = false; } else if (patTRIANGLE_STRIPS.exec(line) !== null) { inPolygonsSection = false; inPointsSection = false; inTriangleStripSection = true; } else if (patPOINT_DATA.exec(line) !== null) { inPointDataSection = true; inPointsSection = false; inPolygonsSection = false; inTriangleStripSection = false; } else if (patCELL_DATA.exec(line) !== null) { inCellDataSection = true; inPointsSection = false; inPolygonsSection = false; inTriangleStripSection = false; } else if (patCOLOR_SCALARS.exec(line) !== null) { inColorSection = true; inNormalsSection = false; inPointsSection = false; inPolygonsSection = false; inTriangleStripSection = false; } else if (patNORMALS.exec(line) !== null) { inNormalsSection = true; inColorSection = false; inPointsSection = false; inPolygonsSection = false; inTriangleStripSection = false; } } var geometry = new BufferGeometry(); geometry.setIndex(indices); geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); if (normals.length === positions.length) geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); if (colors.length !== indices.length) { if (colors.length === positions.length) geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); } else { geometry = geometry.toNonIndexed(); var numTriangles = geometry.attributes.position.count / 3; if (colors.length === numTriangles * 3) { var newColors = []; for (var i = 0; i < numTriangles; i++) { var r = colors[3 * i + 0]; var g = colors[3 * i + 1]; var b = colors[3 * i + 2]; newColors.push(r, g, b); newColors.push(r, g, b); newColors.push(r, g, b); } geometry.setAttribute("color", new Float32BufferAttribute(newColors, 3)); } } return geometry; } function parseBinary(data2) { var count, pointIndex, i, numberOfPoints, s; var buffer = new Uint8Array(data2); var dataView = new DataView(data2); var points = []; var normals = []; var indices = []; var index = 0; function findString(buffer2, start) { var index2 = start; var c = buffer2[index2]; var s2 = []; while (c !== 10) { s2.push(String.fromCharCode(c)); index2++; c = buffer2[index2]; } return { start, end: index2, next: index2 + 1, parsedString: s2.join("") }; } var state, line; while (true) { state = findString(buffer, index); line = state.parsedString; if (line.indexOf("DATASET") === 0) { var dataset = line.split(" ")[1]; if (dataset !== "POLYDATA") throw new Error("Unsupported DATASET type: " + dataset); } else if (line.indexOf("POINTS") === 0) { numberOfPoints = parseInt(line.split(" ")[1], 10); count = numberOfPoints * 4 * 3; points = new Float32Array(numberOfPoints * 3); pointIndex = state.next; for (i = 0; i < numberOfPoints; i++) { points[3 * i] = dataView.getFloat32(pointIndex, false); points[3 * i + 1] = dataView.getFloat32(pointIndex + 4, false); points[3 * i + 2] = dataView.getFloat32(pointIndex + 8, false); pointIndex = pointIndex + 12; } state.next = state.next + count + 1; } else if (line.indexOf("TRIANGLE_STRIPS") === 0) { var numberOfStrips = parseInt(line.split(" ")[1], 10); var size = parseInt(line.split(" ")[2], 10); count = size * 4; indices = new Uint32Array(3 * size - 9 * numberOfStrips); var indicesIndex = 0; pointIndex = state.next; for (i = 0; i < numberOfStrips; i++) { var indexCount = dataView.getInt32(pointIndex, false); var strip = []; pointIndex += 4; for (s = 0; s < indexCount; s++) { strip.push(dataView.getInt32(pointIndex, false)); pointIndex += 4; } for (var j = 0; j < indexCount - 2; j++) if (j % 2) { indices[indicesIndex++] = strip[j]; indices[indicesIndex++] = strip[j + 2]; indices[indicesIndex++] = strip[j + 1]; } else { indices[indicesIndex++] = strip[j]; indices[indicesIndex++] = strip[j + 1]; indices[indicesIndex++] = strip[j + 2]; } } state.next = state.next + count + 1; } else if (line.indexOf("POLYGONS") === 0) { var numberOfStrips = parseInt(line.split(" ")[1], 10); var size = parseInt(line.split(" ")[2], 10); count = size * 4; indices = new Uint32Array(3 * size - 9 * numberOfStrips); var indicesIndex = 0; pointIndex = state.next; for (i = 0; i < numberOfStrips; i++) { var indexCount = dataView.getInt32(pointIndex, false); var strip = []; pointIndex += 4; for (s = 0; s < indexCount; s++) { strip.push(dataView.getInt32(pointIndex, false)); pointIndex += 4; } for (var j = 1; j < indexCount - 1; j++) { indices[indicesIndex++] = strip[0]; indices[indicesIndex++] = strip[j]; indices[indicesIndex++] = strip[j + 1]; } } state.next = state.next + count + 1; } else if (line.indexOf("POINT_DATA") === 0) { numberOfPoints = parseInt(line.split(" ")[1], 10); state = findString(buffer, state.next); count = numberOfPoints * 4 * 3; normals = new Float32Array(numberOfPoints * 3); pointIndex = state.next; for (i = 0; i < numberOfPoints; i++) { normals[3 * i] = dataView.getFloat32(pointIndex, false); normals[3 * i + 1] = dataView.getFloat32(pointIndex + 4, false); normals[3 * i + 2] = dataView.getFloat32(pointIndex + 8, false); pointIndex += 12; } state.next = state.next + count; } index = state.next; if (index >= buffer.byteLength) break; } var geometry = new BufferGeometry(); geometry.setIndex(new BufferAttribute(indices, 1)); geometry.setAttribute("position", new BufferAttribute(points, 3)); if (normals.length === points.length) geometry.setAttribute("normal", new BufferAttribute(normals, 3)); return geometry; } function Float32Concat(first, second) { const firstLength = first.length, result = new Float32Array(firstLength + second.length); result.set(first); result.set(second, firstLength); return result; } function Int32Concat(first, second) { var firstLength = first.length, result = new Int32Array(firstLength + second.length); result.set(first); result.set(second, firstLength); return result; } function parseXML(stringFile) { function xmlToJson(xml) { var obj = {}; if (xml.nodeType === 1) { if (xml.attributes) { if (xml.attributes.length > 0) { obj["attributes"] = {}; for (var j2 = 0; j2 < xml.attributes.length; j2++) { var attribute = xml.attributes.item(j2); obj["attributes"][attribute.nodeName] = attribute.nodeValue.trim(); } } } } else if (xml.nodeType === 3) obj = xml.nodeValue.trim(); if (xml.hasChildNodes()) for (var i2 = 0; i2 < xml.childNodes.length; i2++) { var item = xml.childNodes.item(i2); var nodeName = item.nodeName; if (typeof obj[nodeName] === "undefined") { var tmp = xmlToJson(item); if (tmp !== "") obj[nodeName] = tmp; } else { if (typeof obj[nodeName].push === "undefined") { var old = obj[nodeName]; obj[nodeName] = [old]; } var tmp = xmlToJson(item); if (tmp !== "") obj[nodeName].push(tmp); } } return obj; } function Base64toByteArray(b64) { var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; var i2; var revLookup = []; var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var len2 = code.length; for (i2 = 0; i2 < len2; i2++); for (i2 = 0; i2 < len2; ++i2) revLookup[code.charCodeAt(i2)] = i2; revLookup["-".charCodeAt(0)] = 62; revLookup["_".charCodeAt(0)] = 63; var j2, l, tmp, placeHolders, arr2; var len2 = b64.length; if (len2 % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4"); placeHolders = b64[len2 - 2] === "=" ? 2 : b64[len2 - 1] === "=" ? 1 : 0; arr2 = new Arr(len2 * 3 / 4 - placeHolders); l = placeHolders > 0 ? len2 - 4 : len2; var L = 0; for (i2 = 0, j2 = 0; i2 < l; i2 += 4, j2 += 3) { tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; arr2[L++] = (tmp & 16711680) >> 16; arr2[L++] = (tmp & 65280) >> 8; arr2[L++] = tmp & 255; } if (placeHolders === 2) { tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; arr2[L++] = tmp & 255; } else if (placeHolders === 1) { tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; arr2[L++] = tmp >> 8 & 255; arr2[L++] = tmp & 255; } return arr2; } function parseDataArray(ele, compressed2) { var numBytes = 0; if (json.attributes.header_type === "UInt64") numBytes = 8; else if (json.attributes.header_type === "UInt32") numBytes = 4; if (ele.attributes.format === "binary" && compressed2) { var rawData, content, byteData, blocks, cSizeStart, headerSize, padding, dataOffsets, currentOffset; if (ele.attributes.type === "Float32") var txt = new Float32Array(); else if (ele.attributes.type === "Int64") var txt = new Int32Array(); rawData = ele["#text"]; byteData = Base64toByteArray(rawData); blocks = byteData[0]; for (var i2 = 1; i2 < numBytes - 1; i2++) blocks = blocks | byteData[i2] << i2 * numBytes; headerSize = (blocks + 3) * numBytes; padding = headerSize % 3 > 0 ? 3 - headerSize % 3 : 0; headerSize = headerSize + padding; dataOffsets = []; currentOffset = headerSize; dataOffsets.push(currentOffset); cSizeStart = 3 * numBytes; for (var i2 = 0; i2 < blocks; i2++) { var currentBlockSize = byteData[i2 * numBytes + cSizeStart]; for (var j2 = 1; j2 < numBytes - 1; j2++) currentBlockSize = currentBlockSize | byteData[i2 * numBytes + cSizeStart + j2] << j2 * 8; currentOffset = currentOffset + currentBlockSize; dataOffsets.push(currentOffset); } for (var i2 = 0; i2 < dataOffsets.length - 1; i2++) { content = unzlibSync(byteData.slice(dataOffsets[i2], dataOffsets[i2 + 1])).buffer; if (ele.attributes.type === "Float32") { content = new Float32Array(content); txt = Float32Concat(txt, content); } else if (ele.attributes.type === "Int64") { content = new Int32Array(content); txt = Int32Concat(txt, content); } } delete ele["#text"]; if (ele.attributes.type === "Int64") { if (ele.attributes.format === "binary") txt = txt.filter(function(el, idx) { if (idx % 2 !== 1) return true; }); } } else { if (ele.attributes.format === "binary" && !compressed2) { var content = Base64toByteArray(ele["#text"]); content = content.slice(numBytes).buffer; } else if (ele["#text"]) var content = ele["#text"].split(/\s+/).filter(function(el) { if (el !== "") return el; }); else var content = new Int32Array(0).buffer; delete ele["#text"]; if (ele.attributes.type === "Float32") var txt = new Float32Array(content); else if (ele.attributes.type === "Int32") var txt = new Int32Array(content); else if (ele.attributes.type === "Int64") { var txt = new Int32Array(content); if (ele.attributes.format === "binary") txt = txt.filter(function(el, idx) { if (idx % 2 !== 1) return true; }); } } return txt; } var dom = null; if (window.DOMParser) try { dom = new DOMParser().parseFromString(stringFile, "text/xml"); } catch (e) { dom = null; } else if (window.ActiveXObject) try { dom = new ActiveXObject("Microsoft.XMLDOM"); dom.async = false; if (!dom.loadXML()) throw new Error(dom.parseError.reason + dom.parseError.srcText); } catch (e) { dom = null; } else throw new Error("Cannot parse xml string!"); var doc = dom.documentElement; var json = xmlToJson(doc); var points = []; var normals = []; var indices = []; if (json.PolyData) { var piece = json.PolyData.Piece; var compressed = json.attributes.hasOwnProperty("compressor"); var sections = [ "PointData", "Points", "Strips", "Polys" ]; var sectionIndex = 0, numberOfSections = sections.length; while (sectionIndex < numberOfSections) { var section = piece[sections[sectionIndex]]; if (section && section.DataArray) { if (Object.prototype.toString.call(section.DataArray) === "[object Array]") var arr = section.DataArray; else var arr = [section.DataArray]; var dataArrayIndex = 0, numberOfDataArrays = arr.length; while (dataArrayIndex < numberOfDataArrays) { if ("#text" in arr[dataArrayIndex] && arr[dataArrayIndex]["#text"].length > 0) arr[dataArrayIndex].text = parseDataArray(arr[dataArrayIndex], compressed); dataArrayIndex++; } switch (sections[sectionIndex]) { case "PointData": var numberOfPoints = parseInt(piece.attributes.NumberOfPoints); var normalsName = section.attributes.Normals; if (numberOfPoints > 0) { for (var i = 0, len = arr.length; i < len; i++) if (normalsName === arr[i].attributes.Name) { var components = arr[i].attributes.NumberOfComponents; normals = new Float32Array(numberOfPoints * components); normals.set(arr[i].text, 0); } } break; case "Points": var numberOfPoints = parseInt(piece.attributes.NumberOfPoints); if (numberOfPoints > 0) { var components = section.DataArray.attributes.NumberOfComponents; points = new Float32Array(numberOfPoints * components); points.set(section.DataArray.text, 0); } break; case "Strips": var numberOfStrips = parseInt(piece.attributes.NumberOfStrips); if (numberOfStrips > 0) { var connectivity = new Int32Array(section.DataArray[0].text.length); var offset = new Int32Array(section.DataArray[1].text.length); connectivity.set(section.DataArray[0].text, 0); offset.set(section.DataArray[1].text, 0); var size = numberOfStrips + connectivity.length; indices = new Uint32Array(3 * size - 9 * numberOfStrips); var indicesIndex = 0; for (var i = 0, len = numberOfStrips; i < len; i++) { var strip = []; for (var s = 0, len1 = offset[i], len0 = 0; s < len1 - len0; s++) { strip.push(connectivity[s]); if (i > 0) len0 = offset[i - 1]; } for (var j = 0, len1 = offset[i], len0 = 0; j < len1 - len0 - 2; j++) { if (j % 2) { indices[indicesIndex++] = strip[j]; indices[indicesIndex++] = strip[j + 2]; indices[indicesIndex++] = strip[j + 1]; } else { indices[indicesIndex++] = strip[j]; indices[indicesIndex++] = strip[j + 1]; indices[indicesIndex++] = strip[j + 2]; } if (i > 0) len0 = offset[i - 1]; } } } break; case "Polys": var numberOfPolys = parseInt(piece.attributes.NumberOfPolys); if (numberOfPolys > 0) { var connectivity = new Int32Array(section.DataArray[0].text.length); var offset = new Int32Array(section.DataArray[1].text.length); connectivity.set(section.DataArray[0].text, 0); offset.set(section.DataArray[1].text, 0); var size = numberOfPolys + connectivity.length; indices = new Uint32Array(3 * size - 9 * numberOfPolys); var indicesIndex = 0, connectivityIndex = 0; var i = 0, len = numberOfPolys, len0 = 0; while (i < len) { var poly = []; var s = 0, len1 = offset[i]; while (s < len1 - len0) { poly.push(connectivity[connectivityIndex++]); s++; } var j = 1; while (j < len1 - len0 - 1) { indices[indicesIndex++] = poly[0]; indices[indicesIndex++] = poly[j]; indices[indicesIndex++] = poly[j + 1]; j++; } i++; len0 = offset[i - 1]; } } break; } } sectionIndex++; } var geometry = new BufferGeometry(); geometry.setIndex(new BufferAttribute(indices, 1)); geometry.setAttribute("position", new BufferAttribute(points, 3)); if (normals.length === points.length) geometry.setAttribute("normal", new BufferAttribute(normals, 3)); return geometry; } else throw new Error("Unsupported DATASET type"); } var meta = decodeText$1(new Uint8Array(data, 0, 250)).split("\n"); if (meta[0].indexOf("xml") !== -1) return parseXML(decodeText$1(data)); else if (meta[2].includes("ASCII")) return parseASCII(decodeText$1(data)); else return parseBinary(data); } }; //#endregion //#region node_modules/three-stdlib/loaders/LUT3dlLoader.js var LUT3dlLoader = class extends Loader { load(url, onLoad, onProgress, onError) { const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("text"); loader.load(url, (text) => { try { onLoad(this.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); this.manager.itemError(url); } }, onProgress, onError); } parse(str) { str = str.replace(/^#.*?(\n|\r)/gm, "").replace(/^\s*?(\n|\r)/gm, "").trim(); const lines = str.split(/[\n\r]+/g); const gridLines = lines[0].trim().split(/\s+/g).map((e) => parseFloat(e)); const gridStep = gridLines[1] - gridLines[0]; const size = gridLines.length; for (let i = 1, l = gridLines.length; i < l; i++) if (gridStep !== gridLines[i] - gridLines[i - 1]) throw new Error("LUT3dlLoader: Inconsistent grid size not supported."); const dataArray = new Array(size * size * size * 4); let index = 0; let maxOutputValue = 0; for (let i = 1, l = lines.length; i < l; i++) { const split = lines[i].trim().split(/\s/g); const r = parseFloat(split[0]); const g = parseFloat(split[1]); const b = parseFloat(split[2]); maxOutputValue = Math.max(maxOutputValue, r, g, b); const bLayer = index % size; const gLayer = Math.floor(index / size) % size; const rLayer = Math.floor(index / (size * size)) % size; const pixelIndex = bLayer * size * size + gLayer * size + rLayer; dataArray[4 * pixelIndex + 0] = r; dataArray[4 * pixelIndex + 1] = g; dataArray[4 * pixelIndex + 2] = b; dataArray[4 * pixelIndex + 3] = 1; index += 1; } const maxBitValue = Math.pow(2, Math.ceil(Math.log2(maxOutputValue))); for (let i = 0, l = dataArray.length; i < l; i += 4) { const r = dataArray[i + 0]; const g = dataArray[i + 1]; const b = dataArray[i + 2]; dataArray[i + 0] = 255 * r / maxBitValue; dataArray[i + 1] = 255 * g / maxBitValue; dataArray[i + 2] = 255 * b / maxBitValue; } const data = new Uint8Array(dataArray); const texture = new DataTexture(); texture.image.data = data; texture.image.width = size; texture.image.height = size * size; texture.format = RGBAFormat; texture.type = UnsignedByteType; texture.magFilter = LinearFilter; texture.minFilter = LinearFilter; texture.wrapS = ClampToEdgeWrapping; texture.wrapT = ClampToEdgeWrapping; texture.generateMipmaps = false; texture.needsUpdate = true; const texture3D = new Data3DTexture(); texture3D.image.data = data; texture3D.image.width = size; texture3D.image.height = size; texture3D.image.depth = size; texture3D.format = RGBAFormat; texture3D.type = UnsignedByteType; texture3D.magFilter = LinearFilter; texture3D.minFilter = LinearFilter; texture3D.wrapS = ClampToEdgeWrapping; texture3D.wrapT = ClampToEdgeWrapping; texture3D.wrapR = ClampToEdgeWrapping; texture3D.generateMipmaps = false; texture3D.needsUpdate = true; return { size, texture, texture3D }; } }; //#endregion //#region node_modules/three-stdlib/loaders/DDSLoader.js var DDSLoader = class extends CompressedTextureLoader { constructor(manager) { super(manager); } parse(buffer, loadMipmaps) { const dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 }; const DDS_MAGIC = 542327876; const DDSD_MIPMAPCOUNT = 131072; const DDSCAPS2_CUBEMAP = 512; const DDSCAPS2_CUBEMAP_POSITIVEX = 1024; const DDSCAPS2_CUBEMAP_NEGATIVEX = 2048; const DDSCAPS2_CUBEMAP_POSITIVEY = 4096; const DDSCAPS2_CUBEMAP_NEGATIVEY = 8192; const DDSCAPS2_CUBEMAP_POSITIVEZ = 16384; const DDSCAPS2_CUBEMAP_NEGATIVEZ = 32768; const DDPF_FOURCC = 4; function fourCCToInt32(value) { return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24); } function int32ToFourCC(value) { return String.fromCharCode(value & 255, value >> 8 & 255, value >> 16 & 255, value >> 24 & 255); } function loadARGBMip(buffer2, dataOffset2, width, height) { const dataLength = width * height * 4; const srcBuffer = new Uint8Array(buffer2, dataOffset2, dataLength); const byteArray = new Uint8Array(dataLength); let dst = 0; let src = 0; for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) { const b = srcBuffer[src]; src++; const g = srcBuffer[src]; src++; const r = srcBuffer[src]; src++; const a = srcBuffer[src]; src++; byteArray[dst] = r; dst++; byteArray[dst] = g; dst++; byteArray[dst] = b; dst++; byteArray[dst] = a; dst++; } return byteArray; } const FOURCC_DXT1 = fourCCToInt32("DXT1"); const FOURCC_DXT3 = fourCCToInt32("DXT3"); const FOURCC_DXT5 = fourCCToInt32("DXT5"); const FOURCC_ETC1 = fourCCToInt32("ETC1"); const headerLengthInt = 31; const off_magic = 0; const off_size = 1; const off_flags = 2; const off_height = 3; const off_width = 4; const off_mipmapCount = 7; const off_pfFlags = 20; const off_pfFourCC = 21; const off_RGBBitCount = 22; const off_RBitMask = 23; const off_GBitMask = 24; const off_BBitMask = 25; const off_ABitMask = 26; const off_caps2 = 28; const header = new Int32Array(buffer, 0, headerLengthInt); if (header[off_magic] !== DDS_MAGIC) { console.error("THREE.DDSLoader.parse: Invalid magic number in DDS header."); return dds; } if (!header[off_pfFlags] & DDPF_FOURCC) { console.error("THREE.DDSLoader.parse: Unsupported format, must contain a FourCC code."); return dds; } let blockBytes; const fourCC = header[off_pfFourCC]; let isRGBAUncompressed = false; switch (fourCC) { case FOURCC_DXT1: blockBytes = 8; dds.format = RGB_S3TC_DXT1_Format; break; case FOURCC_DXT3: blockBytes = 16; dds.format = RGBA_S3TC_DXT3_Format; break; case FOURCC_DXT5: blockBytes = 16; dds.format = RGBA_S3TC_DXT5_Format; break; case FOURCC_ETC1: blockBytes = 8; dds.format = RGB_ETC1_Format; break; default: if (header[off_RGBBitCount] === 32 && header[off_RBitMask] & 16711680 && header[off_GBitMask] & 65280 && header[off_BBitMask] & 255 && header[off_ABitMask] & 4278190080) { isRGBAUncompressed = true; blockBytes = 64; dds.format = RGBAFormat; } else { console.error("THREE.DDSLoader.parse: Unsupported FourCC code ", int32ToFourCC(fourCC)); return dds; } } dds.mipmapCount = 1; if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) dds.mipmapCount = Math.max(1, header[off_mipmapCount]); const caps2 = header[off_caps2]; dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false; if (dds.isCubemap && (!(caps2 & DDSCAPS2_CUBEMAP_POSITIVEX) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) || !(caps2 & DDSCAPS2_CUBEMAP_POSITIVEY) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) || !(caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ))) { console.error("THREE.DDSLoader.parse: Incomplete cubemap faces"); return dds; } dds.width = header[off_width]; dds.height = header[off_height]; let dataOffset = header[off_size] + 4; const faces = dds.isCubemap ? 6 : 1; for (let face = 0; face < faces; face++) { let width = dds.width; let height = dds.height; for (let i = 0; i < dds.mipmapCount; i++) { let byteArray, dataLength; if (isRGBAUncompressed) { byteArray = loadARGBMip(buffer, dataOffset, width, height); dataLength = byteArray.length; } else { dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes; byteArray = new Uint8Array(buffer, dataOffset, dataLength); } const mipmap = { data: byteArray, width, height }; dds.mipmaps.push(mipmap); dataOffset += dataLength; width = Math.max(width >> 1, 1); height = Math.max(height >> 1, 1); } } return dds; } }; //#endregion //#region node_modules/three-stdlib/loaders/PVRLoader.js var PVRLoader = class extends CompressedTextureLoader { constructor(manager) { super(manager); } parse(buffer, loadMipmaps) { const header = new Uint32Array(buffer, 0, 13); const pvrDatas = { buffer, header, loadMipmaps }; if (header[0] === 55727696) return _parseV3(pvrDatas); else if (header[11] === 559044176) return _parseV2(pvrDatas); else console.error("THREE.PVRLoader: Unknown PVR format."); } }; function _parseV3(pvrDatas) { const header = pvrDatas.header; let bpp, format; const metaLen = header[12], pixelFormat = header[2], height = header[6], width = header[7], numFaces = header[10], numMipmaps = header[11]; switch (pixelFormat) { case 0: bpp = 2; format = RGB_PVRTC_2BPPV1_Format; break; case 1: bpp = 2; format = RGBA_PVRTC_2BPPV1_Format; break; case 2: bpp = 4; format = RGB_PVRTC_4BPPV1_Format; break; case 3: bpp = 4; format = RGBA_PVRTC_4BPPV1_Format; break; default: console.error("THREE.PVRLoader: Unsupported PVR format:", pixelFormat); } pvrDatas.dataPtr = 52 + metaLen; pvrDatas.bpp = bpp; pvrDatas.format = format; pvrDatas.width = width; pvrDatas.height = height; pvrDatas.numSurfaces = numFaces; pvrDatas.numMipmaps = numMipmaps; pvrDatas.isCubemap = numFaces === 6; return _extract(pvrDatas); } function _parseV2(pvrDatas) { const header = pvrDatas.header; const headerLength = header[0], height = header[1], width = header[2], numMipmaps = header[3], flags = header[4], bitmaskAlpha = header[10], numSurfs = header[12]; const TYPE_MASK = 255; const PVRTC_2 = 24, PVRTC_4 = 25; const formatFlags = flags & TYPE_MASK; let bpp, format; const _hasAlpha = bitmaskAlpha > 0; if (formatFlags === PVRTC_4) { format = _hasAlpha ? RGBA_PVRTC_4BPPV1_Format : RGB_PVRTC_4BPPV1_Format; bpp = 4; } else if (formatFlags === PVRTC_2) { format = _hasAlpha ? RGBA_PVRTC_2BPPV1_Format : RGB_PVRTC_2BPPV1_Format; bpp = 2; } else console.error("THREE.PVRLoader: Unknown PVR format:", formatFlags); pvrDatas.dataPtr = headerLength; pvrDatas.bpp = bpp; pvrDatas.format = format; pvrDatas.width = width; pvrDatas.height = height; pvrDatas.numSurfaces = numSurfs; pvrDatas.numMipmaps = numMipmaps + 1; pvrDatas.isCubemap = numSurfs === 6; return _extract(pvrDatas); } function _extract(pvrDatas) { const pvr = { mipmaps: [], width: pvrDatas.width, height: pvrDatas.height, format: pvrDatas.format, mipmapCount: pvrDatas.numMipmaps, isCubemap: pvrDatas.isCubemap }; const buffer = pvrDatas.buffer; let dataOffset = pvrDatas.dataPtr, dataSize = 0, blockSize = 0, blockWidth = 0, blockHeight = 0, widthBlocks = 0, heightBlocks = 0; const bpp = pvrDatas.bpp, numSurfs = pvrDatas.numSurfaces; if (bpp === 2) { blockWidth = 8; blockHeight = 4; } else { blockWidth = 4; blockHeight = 4; } blockSize = blockWidth * blockHeight * bpp / 8; pvr.mipmaps.length = pvrDatas.numMipmaps * numSurfs; let mipLevel = 0; while (mipLevel < pvrDatas.numMipmaps) { const sWidth = pvrDatas.width >> mipLevel, sHeight = pvrDatas.height >> mipLevel; widthBlocks = sWidth / blockWidth; heightBlocks = sHeight / blockHeight; if (widthBlocks < 2) widthBlocks = 2; if (heightBlocks < 2) heightBlocks = 2; dataSize = widthBlocks * heightBlocks * blockSize; for (let surfIndex = 0; surfIndex < numSurfs; surfIndex++) { const mipmap = { data: new Uint8Array(buffer, dataOffset, dataSize), width: sWidth, height: sHeight }; pvr.mipmaps[surfIndex * pvrDatas.numMipmaps + mipLevel] = mipmap; dataOffset += dataSize; } mipLevel++; } return pvr; } //#endregion //#region node_modules/three-stdlib/loaders/GCodeLoader.js var GCodeLoader = class extends Loader { constructor(manager) { super(manager); this.splitLayer = false; } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(data) { let state = { x: 0, y: 0, z: 0, e: 0, f: 0, extruding: false, relative: false }; let layers = []; let currentLayer = void 0; const pathMaterial = new LineBasicMaterial({ color: 16711680 }); pathMaterial.name = "path"; const extrudingMaterial = new LineBasicMaterial({ color: 65280 }); extrudingMaterial.name = "extruded"; function newLayer(line) { currentLayer = { vertex: [], pathVertex: [], z: line.z }; layers.push(currentLayer); } function addSegment(p1, p2) { if (currentLayer === void 0) newLayer(p1); if (state.extruding) { currentLayer.vertex.push(p1.x, p1.y, p1.z); currentLayer.vertex.push(p2.x, p2.y, p2.z); } else { currentLayer.pathVertex.push(p1.x, p1.y, p1.z); currentLayer.pathVertex.push(p2.x, p2.y, p2.z); } } function delta(v1, v2) { return state.relative ? v2 : v2 - v1; } function absolute(v1, v2) { return state.relative ? v1 + v2 : v2; } let lines = data.replace(/;.+/g, "").split("\n"); for (let i = 0; i < lines.length; i++) { let tokens = lines[i].split(" "); let cmd = tokens[0].toUpperCase(); let args = {}; tokens.splice(1).forEach(function(token) { if (token[0] !== void 0) { let key = token[0].toLowerCase(); args[key] = parseFloat(token.substring(1)); } }); if (cmd === "G0" || cmd === "G1") { let line = { x: args.x !== void 0 ? absolute(state.x, args.x) : state.x, y: args.y !== void 0 ? absolute(state.y, args.y) : state.y, z: args.z !== void 0 ? absolute(state.z, args.z) : state.z, e: args.e !== void 0 ? absolute(state.e, args.e) : state.e, f: args.f !== void 0 ? absolute(state.f, args.f) : state.f }; if (delta(state.e, line.e) > 0) { line.extruding = delta(state.e, line.e) > 0; if (currentLayer == void 0 || line.z != currentLayer.z) newLayer(line); } addSegment(state, line); state = line; } else if (cmd === "G2" || cmd === "G3"); else if (cmd === "G90") state.relative = false; else if (cmd === "G91") state.relative = true; else if (cmd === "G92") { let line = state; line.x = args.x !== void 0 ? args.x : line.x; line.y = args.y !== void 0 ? args.y : line.y; line.z = args.z !== void 0 ? args.z : line.z; line.e = args.e !== void 0 ? args.e : line.e; state = line; } } function addObject(vertex, extruding, i) { let geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute(vertex, 3)); let segments = new LineSegments(geometry, extruding ? extrudingMaterial : pathMaterial); segments.name = "layer" + i; object.add(segments); } const object = new Group(); object.name = "gcode"; if (this.splitLayer) for (let i = 0; i < layers.length; i++) { let layer = layers[i]; addObject(layer.vertex, true, i); addObject(layer.pathVertex, false, i); } else { const vertex = [], pathVertex = []; for (let i = 0; i < layers.length; i++) { let layer = layers[i]; let layerVertex = layer.vertex; let layerPathVertex = layer.pathVertex; for (let j = 0; j < layerVertex.length; j++) vertex.push(layerVertex[j]); for (let j = 0; j < layerPathVertex.length; j++) pathVertex.push(layerPathVertex[j]); } addObject(vertex, true, layers.length); addObject(pathVertex, false, layers.length); } object.quaternion.setFromEuler(new Euler(-Math.PI / 2, 0, 0)); return object; } }; //#endregion //#region node_modules/three-stdlib/loaders/BasisTextureLoader.js var __defProp$1 = Object.defineProperty; var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$1 = (obj, key, value) => { __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var _taskCache$2 = /* @__PURE__ */ new WeakMap(); var BasisTextureLoader = /* @__PURE__ */ (() => { 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 loader = new FileLoader(this.manager); loader.setResponseType("arraybuffer"); loader.setWithCredentials(this.withCredentials); const texture = new CompressedTexture(); loader.load(url, (buffer) => { if (_taskCache$2.has(buffer)) return _taskCache$2.get(buffer).promise.then(onLoad).catch(onError); this._createTexture([buffer]).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 i = 0; i < levels.length; i++) buffers.add(levels[i].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 i = 0; i < buffers.length; i++) taskCost += buffers[i].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]; } }); _taskCache$2.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(e) { const message = e.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(a, b) { return a._taskLoad > b._taskLoad ? -1 : 1; }); const worker = this.workerPool[this.workerPool.length - 1]; worker._taskLoad += taskCost; return worker; }); } dispose() { for (let i = 0; i < this.workerPool.length; i++) this.workerPool[i].terminate(); this.workerPool.length = 0; return this; } }; let BasisTextureLoader2 = _BasisTextureLoader; __publicField$1(BasisTextureLoader2, "BasisFormat", { ETC1S: 0, UASTC_4x4: 1 }); __publicField$1(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 }); __publicField$1(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 }); __publicField$1(BasisTextureLoader2, "BasisWorker", function() { let config; let transcoderPending; let BasisModule; const EngineFormat = _EngineFormat; const TranscoderFormat = _TranscoderFormat; const BasisFormat = _BasisFormat; onmessage = function(e) { const message = e.data; switch (message.type) { case "init": config = message.config; init(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 i = 0; i < mipmaps.length; ++i) buffers.push(mipmaps[i].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 init(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 i = 0; i < taskConfig.levels.length; i++) { const level = taskConfig.levels[i]; const imageDesc = taskConfig.globalData.imageDescs[i]; 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 i = 0; i < taskConfig.levels.length; i++) { const level = taskConfig.levels[i]; const dstByteLength = getTranscodedImageByteLength(transcoderFormat, level.width, level.height); const dst = new Uint8Array(dstByteLength); assert(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), "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(buffer) { const basisFile = new BasisModule.BasisFile(new Uint8Array(buffer)); 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)); if (!basisFile.transcodeImage(dst, 0, mip, transcoderFormat, 0, hasAlpha)) { 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(a, b) { return a.priorityETC1S - b.priorityETC1S; }); const UASTC_OPTIONS = FORMAT_OPTIONS.sort(function(a, b) { return a.priorityUASTC - b.priorityUASTC; }); function getTranscoderFormat(basisFormat, width, height, hasAlpha) { let transcoderFormat; let engineFormat; const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; for (let i = 0; i < options.length; i++) { const opt = options[i]; 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 & -4; const paddedHeight = height + 3 & -4; 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; })(); //#endregion //#region node_modules/three-stdlib/loaders/TDSLoader.js var TDSLoader = class extends Loader { constructor(manager) { super(manager); this.debug = false; this.group = null; this.position = 0; this.materials = []; this.meshes = []; } /** * Load 3ds file from url. * * @method load * @param {[type]} url URL for the file. * @param {Function} onLoad onLoad callback, receives group Object3D as argument. * @param {Function} onProgress onProgress callback. * @param {Function} onError onError callback. */ load(url, onLoad, onProgress, onError) { const scope = this; const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function(data) { try { onLoad(scope.parse(data, path)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } /** * Parse arraybuffer data and load 3ds file. * * @method parse * @param {ArrayBuffer} arraybuffer Arraybuffer data to be loaded. * @param {String} path Path for external resources. * @return {Group} Group loaded from 3ds file. */ parse(arraybuffer, path) { this.group = new Group(); this.position = 0; this.materials = []; this.meshes = []; this.readFile(arraybuffer, path); for (let i = 0; i < this.meshes.length; i++) this.group.add(this.meshes[i]); return this.group; } /** * Decode file content to read 3ds data. * * @method readFile * @param {ArrayBuffer} arraybuffer Arraybuffer data to be loaded. * @param {String} path Path for external resources. */ readFile(arraybuffer, path) { const data = new DataView(arraybuffer); const chunk = this.readChunk(data); if (chunk.id === MLIBMAGIC || chunk.id === CMAGIC || chunk.id === M3DMAGIC) { let next = this.nextChunk(data, chunk); while (next !== 0) { if (next === M3D_VERSION) { const version = this.readDWord(data); this.debugMessage("3DS file version: " + version); } else if (next === MDATA) { this.resetPosition(data); this.readMeshData(data, path); } else this.debugMessage("Unknown main chunk: " + next.toString(16)); next = this.nextChunk(data, chunk); } } this.debugMessage("Parsed " + this.meshes.length + " meshes"); } /** * Read mesh data chunk. * * @method readMeshData * @param {Dataview} data Dataview in use. * @param {String} path Path for external resources. */ readMeshData(data, path) { const chunk = this.readChunk(data); let next = this.nextChunk(data, chunk); while (next !== 0) { if (next === MESH_VERSION) { const version = +this.readDWord(data); this.debugMessage("Mesh Version: " + version); } else if (next === MASTER_SCALE) { const scale = this.readFloat(data); this.debugMessage("Master scale: " + scale); this.group.scale.set(scale, scale, scale); } else if (next === NAMED_OBJECT) { this.debugMessage("Named Object"); this.resetPosition(data); this.readNamedObject(data); } else if (next === MAT_ENTRY) { this.debugMessage("Material"); this.resetPosition(data); this.readMaterialEntry(data, path); } else this.debugMessage("Unknown MDATA chunk: " + next.toString(16)); next = this.nextChunk(data, chunk); } } /** * Read named object chunk. * * @method readNamedObject * @param {Dataview} data Dataview in use. */ readNamedObject(data) { const chunk = this.readChunk(data); const name = this.readString(data, 64); chunk.cur = this.position; let next = this.nextChunk(data, chunk); while (next !== 0) { if (next === N_TRI_OBJECT) { this.resetPosition(data); const mesh = this.readMesh(data); mesh.name = name; this.meshes.push(mesh); } else this.debugMessage("Unknown named object chunk: " + next.toString(16)); next = this.nextChunk(data, chunk); } this.endChunk(chunk); } /** * Read material data chunk and add it to the material list. * * @method readMaterialEntry * @param {Dataview} data Dataview in use. * @param {String} path Path for external resources. */ readMaterialEntry(data, path) { const chunk = this.readChunk(data); let next = this.nextChunk(data, chunk); const material = new MeshPhongMaterial(); while (next !== 0) { if (next === MAT_NAME) { material.name = this.readString(data, 64); this.debugMessage(" Name: " + material.name); } else if (next === MAT_WIRE) { this.debugMessage(" Wireframe"); material.wireframe = true; } else if (next === MAT_WIRE_SIZE) { const value = this.readByte(data); material.wireframeLinewidth = value; this.debugMessage(" Wireframe Thickness: " + value); } else if (next === MAT_TWO_SIDE) { material.side = 2; this.debugMessage(" DoubleSided"); } else if (next === MAT_ADDITIVE) { this.debugMessage(" Additive Blending"); material.blending = 2; } else if (next === MAT_DIFFUSE) { this.debugMessage(" Diffuse Color"); material.color = this.readColor(data); } else if (next === MAT_SPECULAR) { this.debugMessage(" Specular Color"); material.specular = this.readColor(data); } else if (next === MAT_AMBIENT) { this.debugMessage(" Ambient color"); material.color = this.readColor(data); } else if (next === MAT_SHININESS) { const shininess = this.readPercentage(data); material.shininess = shininess * 100; this.debugMessage(" Shininess : " + shininess); } else if (next === MAT_TRANSPARENCY) { const transparency = this.readPercentage(data); material.opacity = 1 - transparency; this.debugMessage(" Transparency : " + transparency); material.transparent = material.opacity < 1 ? true : false; } else if (next === MAT_TEXMAP) { this.debugMessage(" ColorMap"); this.resetPosition(data); material.map = this.readMap(data, path); } else if (next === MAT_BUMPMAP) { this.debugMessage(" BumpMap"); this.resetPosition(data); material.bumpMap = this.readMap(data, path); } else if (next === MAT_OPACMAP) { this.debugMessage(" OpacityMap"); this.resetPosition(data); material.alphaMap = this.readMap(data, path); } else if (next === MAT_SPECMAP) { this.debugMessage(" SpecularMap"); this.resetPosition(data); material.specularMap = this.readMap(data, path); } else this.debugMessage(" Unknown material chunk: " + next.toString(16)); next = this.nextChunk(data, chunk); } this.endChunk(chunk); this.materials[material.name] = material; } /** * Read mesh data chunk. * * @method readMesh * @param {Dataview} data Dataview in use. * @return {Mesh} The parsed mesh. */ readMesh(data) { const chunk = this.readChunk(data); let next = this.nextChunk(data, chunk); const geometry = new BufferGeometry(); const mesh = new Mesh(geometry, new MeshPhongMaterial()); mesh.name = "mesh"; while (next !== 0) { if (next === POINT_ARRAY) { const points = this.readWord(data); this.debugMessage(" Vertex: " + points); const vertices = []; for (let i = 0; i < points; i++) { vertices.push(this.readFloat(data)); vertices.push(this.readFloat(data)); vertices.push(this.readFloat(data)); } geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); } else if (next === FACE_ARRAY) { this.resetPosition(data); this.readFaceArray(data, mesh); } else if (next === TEX_VERTS) { const texels = this.readWord(data); this.debugMessage(" UV: " + texels); const uvs = []; for (let i = 0; i < texels; i++) { uvs.push(this.readFloat(data)); uvs.push(this.readFloat(data)); } geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } else if (next === MESH_MATRIX) { this.debugMessage(" Tranformation Matrix (TODO)"); const values = []; for (let i = 0; i < 12; i++) values[i] = this.readFloat(data); const matrix = new Matrix4(); matrix.elements[0] = values[0]; matrix.elements[1] = values[6]; matrix.elements[2] = values[3]; matrix.elements[3] = values[9]; matrix.elements[4] = values[2]; matrix.elements[5] = values[8]; matrix.elements[6] = values[5]; matrix.elements[7] = values[11]; matrix.elements[8] = values[1]; matrix.elements[9] = values[7]; matrix.elements[10] = values[4]; matrix.elements[11] = values[10]; matrix.elements[12] = 0; matrix.elements[13] = 0; matrix.elements[14] = 0; matrix.elements[15] = 1; matrix.transpose(); const inverse = new Matrix4(); inverse.copy(matrix).invert(); geometry.applyMatrix4(inverse); matrix.decompose(mesh.position, mesh.quaternion, mesh.scale); } else this.debugMessage(" Unknown mesh chunk: " + next.toString(16)); next = this.nextChunk(data, chunk); } this.endChunk(chunk); geometry.computeVertexNormals(); return mesh; } /** * Read face array data chunk. * * @method readFaceArray * @param {Dataview} data Dataview in use. * @param {Mesh} mesh Mesh to be filled with the data read. */ readFaceArray(data, mesh) { const chunk = this.readChunk(data); const faces = this.readWord(data); this.debugMessage(" Faces: " + faces); const index = []; for (let i = 0; i < faces; ++i) { index.push(this.readWord(data), this.readWord(data), this.readWord(data)); this.readWord(data); } mesh.geometry.setIndex(index); let materialIndex = 0; let start = 0; while (this.position < chunk.end) { const subchunk = this.readChunk(data); if (subchunk.id === MSH_MAT_GROUP) { this.debugMessage(" Material Group"); this.resetPosition(data); const group = this.readMaterialGroup(data); const count = group.index.length * 3; mesh.geometry.addGroup(start, count, materialIndex); start += count; materialIndex++; const material = this.materials[group.name]; if (Array.isArray(mesh.material) === false) mesh.material = []; if (material !== void 0) mesh.material.push(material); } else this.debugMessage(" Unknown face array chunk: " + subchunk.toString(16)); this.endChunk(subchunk); } if (mesh.material.length === 1) mesh.material = mesh.material[0]; this.endChunk(chunk); } /** * Read texture map data chunk. * * @method readMap * @param {Dataview} data Dataview in use. * @param {String} path Path for external resources. * @return {Texture} Texture read from this data chunk. */ readMap(data, path) { const chunk = this.readChunk(data); let next = this.nextChunk(data, chunk); let texture = {}; const loader = new TextureLoader(this.manager); loader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin); while (next !== 0) { if (next === MAT_MAPNAME) { const name = this.readString(data, 128); texture = loader.load(name); this.debugMessage(" File: " + path + name); } else if (next === MAT_MAP_UOFFSET) { texture.offset.x = this.readFloat(data); this.debugMessage(" OffsetX: " + texture.offset.x); } else if (next === MAT_MAP_VOFFSET) { texture.offset.y = this.readFloat(data); this.debugMessage(" OffsetY: " + texture.offset.y); } else if (next === MAT_MAP_USCALE) { texture.repeat.x = this.readFloat(data); this.debugMessage(" RepeatX: " + texture.repeat.x); } else if (next === MAT_MAP_VSCALE) { texture.repeat.y = this.readFloat(data); this.debugMessage(" RepeatY: " + texture.repeat.y); } else this.debugMessage(" Unknown map chunk: " + next.toString(16)); next = this.nextChunk(data, chunk); } this.endChunk(chunk); return texture; } /** * Read material group data chunk. * * @method readMaterialGroup * @param {Dataview} data Dataview in use. * @return {Object} Object with name and index of the object. */ readMaterialGroup(data) { this.readChunk(data); const name = this.readString(data, 64); const numFaces = this.readWord(data); this.debugMessage(" Name: " + name); this.debugMessage(" Faces: " + numFaces); const index = []; for (let i = 0; i < numFaces; ++i) index.push(this.readWord(data)); return { name, index }; } /** * Read a color value. * * @method readColor * @param {DataView} data Dataview. * @return {Color} Color value read.. */ readColor(data) { const chunk = this.readChunk(data); const color = new Color(); if (chunk.id === COLOR_24 || chunk.id === LIN_COLOR_24) { const r = this.readByte(data); const g = this.readByte(data); const b = this.readByte(data); color.setRGB(r / 255, g / 255, b / 255); this.debugMessage(" Color: " + color.r + ", " + color.g + ", " + color.b); } else if (chunk.id === COLOR_F || chunk.id === LIN_COLOR_F) { const r = this.readFloat(data); const g = this.readFloat(data); const b = this.readFloat(data); color.setRGB(r, g, b); this.debugMessage(" Color: " + color.r + ", " + color.g + ", " + color.b); } else this.debugMessage(" Unknown color chunk: " + chunk.toString(16)); this.endChunk(chunk); return color; } /** * Read next chunk of data. * * @method readChunk * @param {DataView} data Dataview. * @return {Object} Chunk of data read. */ readChunk(data) { const chunk = {}; chunk.cur = this.position; chunk.id = this.readWord(data); chunk.size = this.readDWord(data); chunk.end = chunk.cur + chunk.size; chunk.cur += 6; return chunk; } /** * Set position to the end of the current chunk of data. * * @method endChunk * @param {Object} chunk Data chunk. */ endChunk(chunk) { this.position = chunk.end; } /** * Move to the next data chunk. * * @method nextChunk * @param {DataView} data Dataview. * @param {Object} chunk Data chunk. */ nextChunk(data, chunk) { if (chunk.cur >= chunk.end) return 0; this.position = chunk.cur; try { const next = this.readChunk(data); chunk.cur += next.size; return next.id; } catch (e) { this.debugMessage("Unable to read chunk at " + this.position); return 0; } } /** * Reset dataview position. * * @method resetPosition */ resetPosition() { this.position -= 6; } /** * Read byte value. * * @method readByte * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ readByte(data) { const v = data.getUint8(this.position, true); this.position += 1; return v; } /** * Read 32 bit float value. * * @method readFloat * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ readFloat(data) { try { const v = data.getFloat32(this.position, true); this.position += 4; return v; } catch (e) { this.debugMessage(e + " " + this.position + " " + data.byteLength); } } /** * Read 32 bit signed integer value. * * @method readInt * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ readInt(data) { const v = data.getInt32(this.position, true); this.position += 4; return v; } /** * Read 16 bit signed integer value. * * @method readShort * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ readShort(data) { const v = data.getInt16(this.position, true); this.position += 2; return v; } /** * Read 64 bit unsigned integer value. * * @method readDWord * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ readDWord(data) { const v = data.getUint32(this.position, true); this.position += 4; return v; } /** * Read 32 bit unsigned integer value. * * @method readWord * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ readWord(data) { const v = data.getUint16(this.position, true); this.position += 2; return v; } /** * Read string value. * * @method readString * @param {DataView} data Dataview to read data from. * @param {Number} maxLength Max size of the string to be read. * @return {String} Data read from the dataview. */ readString(data, maxLength) { let s = ""; for (let i = 0; i < maxLength; i++) { const c = this.readByte(data); if (!c) break; s += String.fromCharCode(c); } return s; } /** * Read percentage value. * * @method readPercentage * @param {DataView} data Dataview to read data from. * @return {Number} Data read from the dataview. */ readPercentage(data) { const chunk = this.readChunk(data); let value; switch (chunk.id) { case INT_PERCENTAGE: value = this.readShort(data) / 100; break; case FLOAT_PERCENTAGE: value = this.readFloat(data); break; default: this.debugMessage(" Unknown percentage chunk: " + chunk.toString(16)); } this.endChunk(chunk); return value; } /** * Print debug message to the console. * * Is controlled by a flag to show or hide debug messages. * * @method debugMessage * @param {Object} message Debug message to print to the console. */ debugMessage(message) { if (this.debug) console.log(message); } }; var M3DMAGIC = 19789; var MLIBMAGIC = 15786; var CMAGIC = 49725; var M3D_VERSION = 2; var COLOR_F = 16; var COLOR_24 = 17; var LIN_COLOR_24 = 18; var LIN_COLOR_F = 19; var INT_PERCENTAGE = 48; var FLOAT_PERCENTAGE = 49; var MDATA = 15677; var MESH_VERSION = 15678; var MASTER_SCALE = 256; var MAT_ENTRY = 45055; var MAT_NAME = 40960; var MAT_AMBIENT = 40976; var MAT_DIFFUSE = 40992; var MAT_SPECULAR = 41008; var MAT_SHININESS = 41024; var MAT_TRANSPARENCY = 41040; var MAT_TWO_SIDE = 41089; var MAT_ADDITIVE = 41091; var MAT_WIRE = 41093; var MAT_WIRE_SIZE = 41095; var MAT_TEXMAP = 41472; var MAT_OPACMAP = 41488; var MAT_BUMPMAP = 41520; var MAT_SPECMAP = 41476; var MAT_MAPNAME = 41728; var MAT_MAP_USCALE = 41812; var MAT_MAP_VSCALE = 41814; var MAT_MAP_UOFFSET = 41816; var MAT_MAP_VOFFSET = 41818; var NAMED_OBJECT = 16384; var N_TRI_OBJECT = 16640; var POINT_ARRAY = 16656; var FACE_ARRAY = 16672; var MSH_MAT_GROUP = 16688; var TEX_VERTS = 16704; var MESH_MATRIX = 16736; //#endregion //#region node_modules/three-stdlib/loaders/LDrawLoader.js var FINISH_TYPE_DEFAULT = 0; var FINISH_TYPE_CHROME = 1; var FINISH_TYPE_PEARLESCENT = 2; var FINISH_TYPE_RUBBER = 3; var FINISH_TYPE_MATTE_METALLIC = 4; var FINISH_TYPE_METAL = 5; var FILE_LOCATION_AS_IS = 0; var FILE_LOCATION_TRY_PARTS = 1; var FILE_LOCATION_TRY_P = 2; var FILE_LOCATION_TRY_MODELS = 3; var FILE_LOCATION_TRY_RELATIVE = 4; var FILE_LOCATION_TRY_ABSOLUTE = 5; var FILE_LOCATION_NOT_FOUND = 6; var MAIN_COLOUR_CODE = "16"; var MAIN_EDGE_COLOUR_CODE = "24"; var _tempVec0 = /* @__PURE__ */ new Vector3(); var _tempVec1 = /* @__PURE__ */ new Vector3(); var LDrawConditionalLineMaterial = class extends ShaderMaterial { constructor(parameters) { super({ uniforms: UniformsUtils.merge([UniformsLib.fog, { diffuse: { value: new Color() }, opacity: { value: 1 } }]), vertexShader: ` attribute vec3 control0; attribute vec3 control1; attribute vec3 direction; varying float discardFlag; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); gl_Position = projectionMatrix * mvPosition; // Transform the line segment ends and control points into camera clip space vec4 c0 = projectionMatrix * modelViewMatrix * vec4(control0, 1.0); vec4 c1 = projectionMatrix * modelViewMatrix * vec4(control1, 1.0); vec4 p0 = projectionMatrix * modelViewMatrix * vec4(position, 1.0); vec4 p1 = projectionMatrix * modelViewMatrix * vec4(position + direction, 1.0); c0.xy /= c0.w; c1.xy /= c1.w; p0.xy /= p0.w; p1.xy /= p1.w; // Get the direction of the segment and an orthogonal vector vec2 dir = p1.xy - p0.xy; vec2 norm = vec2(-dir.y, dir.x); // Get control point directions from the line vec2 c0dir = c0.xy - p1.xy; vec2 c1dir = c1.xy - p1.xy; // If the vectors to the controls points are pointed in different directions away // from the line segment then the line should not be drawn. float d0 = dot(normalize(norm), normalize(c0dir)); float d1 = dot(normalize(norm), normalize(c1dir)); discardFlag = float(sign(d0) != sign(d1)); #include #include #include } `, fragmentShader: ` uniform vec3 diffuse; uniform float opacity; varying float discardFlag; #include #include #include #include #include void main() { if (discardFlag > 0.5) discard; #include vec3 outgoingLight = vec3(0.0); vec4 diffuseColor = vec4(diffuse, opacity); #include #include outgoingLight = diffuseColor.rgb; // simple shader gl_FragColor = vec4(outgoingLight, diffuseColor.a); #include #include <${version >= 154 ? "colorspace_fragment" : "encodings_fragment"}> #include #include } ` }); Object.defineProperties(this, { opacity: { get: function() { return this.uniforms.opacity.value; }, set: function(value) { this.uniforms.opacity.value = value; } }, color: { get: function() { return this.uniforms.diffuse.value; } } }); this.setValues(parameters); this.isLDrawConditionalLineMaterial = true; } }; var ConditionalLineSegments = class extends LineSegments { constructor(geometry, material) { super(geometry, material); this.isConditionalLine = true; } }; function generateFaceNormals(faces) { for (let i = 0, l = faces.length; i < l; i++) { const face = faces[i]; const vertices = face.vertices; const v0 = vertices[0]; const v1 = vertices[1]; const v2 = vertices[2]; _tempVec0.subVectors(v1, v0); _tempVec1.subVectors(v2, v1); face.faceNormal = new Vector3().crossVectors(_tempVec0, _tempVec1).normalize(); } } var _ray$1 = /* @__PURE__ */ new Ray(); function smoothNormals(faces, lineSegments, checkSubSegments = false) { const hashMultiplier = 1.0000000001 * 100; function hashVertex(v) { return `${~~(v.x * hashMultiplier)},${~~(v.y * hashMultiplier)},${~~(v.z * hashMultiplier)}`; } function hashEdge(v0, v1) { return `${hashVertex(v0)}_${hashVertex(v1)}`; } function toNormalizedRay(v0, v1, targetRay) { targetRay.direction.subVectors(v1, v0).normalize(); const scalar = v0.dot(targetRay.direction); targetRay.origin.copy(v0).addScaledVector(targetRay.direction, -scalar); return targetRay; } function hashRay(ray) { return hashEdge(ray.origin, ray.direction); } const hardEdges = /* @__PURE__ */ new Set(); const hardEdgeRays = /* @__PURE__ */ new Map(); const halfEdgeList = {}; const normals = []; for (let i = 0, l = lineSegments.length; i < l; i++) { const vertices = lineSegments[i].vertices; const v0 = vertices[0]; const v1 = vertices[1]; hardEdges.add(hashEdge(v0, v1)); hardEdges.add(hashEdge(v1, v0)); if (checkSubSegments) { const ray = toNormalizedRay(v0, v1, new Ray()); const rh1 = hashRay(ray); if (!hardEdgeRays.has(rh1)) { toNormalizedRay(v1, v0, ray); const rh2 = hashRay(ray); const info2 = { ray, distances: [] }; hardEdgeRays.set(rh1, info2); hardEdgeRays.set(rh2, info2); } const info = hardEdgeRays.get(rh1); let d0 = info.ray.direction.dot(v0); let d1 = info.ray.direction.dot(v1); if (d0 > d1) [d0, d1] = [d1, d0]; info.distances.push(d0, d1); } } for (let i = 0, l = faces.length; i < l; i++) { const tri = faces[i]; const vertices = tri.vertices; const vertCount = vertices.length; for (let i2 = 0; i2 < vertCount; i2++) { const index = i2; const next = (i2 + 1) % vertCount; const v0 = vertices[index]; const v1 = vertices[next]; const hash = hashEdge(v0, v1); if (hardEdges.has(hash)) continue; if (checkSubSegments) { toNormalizedRay(v0, v1, _ray$1); const rayHash = hashRay(_ray$1); if (hardEdgeRays.has(rayHash)) { const { ray, distances } = hardEdgeRays.get(rayHash); let d0 = ray.direction.dot(v0); let d1 = ray.direction.dot(v1); if (d0 > d1) [d0, d1] = [d1, d0]; let found = false; for (let i3 = 0, l2 = distances.length; i3 < l2; i3 += 2) if (d0 >= distances[i3] && d1 <= distances[i3 + 1]) { found = true; break; } if (found) continue; } } halfEdgeList[hash] = { index, tri }; } } while (true) { let halfEdge = null; for (const key in halfEdgeList) { halfEdge = halfEdgeList[key]; break; } if (halfEdge === null) break; const queue = [halfEdge]; while (queue.length > 0) { const tri = queue.pop().tri; const vertices = tri.vertices; const vertNormals = tri.normals; const faceNormal = tri.faceNormal; const vertCount = vertices.length; for (let i2 = 0; i2 < vertCount; i2++) { const index = i2; const next = (i2 + 1) % vertCount; const v0 = vertices[index]; const v1 = vertices[next]; const hash = hashEdge(v0, v1); delete halfEdgeList[hash]; const reverseHash = hashEdge(v1, v0); const otherInfo = halfEdgeList[reverseHash]; if (otherInfo) { const otherTri = otherInfo.tri; const otherIndex = otherInfo.index; const otherNormals = otherTri.normals; const otherVertCount = otherNormals.length; const otherFaceNormal = otherTri.faceNormal; if (Math.abs(otherTri.faceNormal.dot(tri.faceNormal)) < .25) continue; if (reverseHash in halfEdgeList) { queue.push(otherInfo); delete halfEdgeList[reverseHash]; } const otherNext = (otherIndex + 1) % otherVertCount; if (vertNormals[index] && otherNormals[otherNext] && vertNormals[index] !== otherNormals[otherNext]) { otherNormals[otherNext].norm.add(vertNormals[index].norm); vertNormals[index].norm = otherNormals[otherNext].norm; } let sharedNormal1 = vertNormals[index] || otherNormals[otherNext]; if (sharedNormal1 === null) { sharedNormal1 = { norm: new Vector3() }; normals.push(sharedNormal1.norm); } if (vertNormals[index] === null) { vertNormals[index] = sharedNormal1; sharedNormal1.norm.add(faceNormal); } if (otherNormals[otherNext] === null) { otherNormals[otherNext] = sharedNormal1; sharedNormal1.norm.add(otherFaceNormal); } if (vertNormals[next] && otherNormals[otherIndex] && vertNormals[next] !== otherNormals[otherIndex]) { otherNormals[otherIndex].norm.add(vertNormals[next].norm); vertNormals[next].norm = otherNormals[otherIndex].norm; } let sharedNormal2 = vertNormals[next] || otherNormals[otherIndex]; if (sharedNormal2 === null) { sharedNormal2 = { norm: new Vector3() }; normals.push(sharedNormal2.norm); } if (vertNormals[next] === null) { vertNormals[next] = sharedNormal2; sharedNormal2.norm.add(faceNormal); } if (otherNormals[otherIndex] === null) { otherNormals[otherIndex] = sharedNormal2; sharedNormal2.norm.add(otherFaceNormal); } } } } } for (let i = 0, l = normals.length; i < l; i++) normals[i].normalize(); } function isPartType(type) { return type === "Part" || type === "Unofficial_Part"; } function isPrimitiveType(type) { return /primitive/i.test(type) || type === "Subpart"; } var LineParser = class { constructor(line, lineNumber) { this.line = line; this.lineLength = line.length; this.currentCharIndex = 0; this.currentChar = " "; this.lineNumber = lineNumber; } seekNonSpace() { while (this.currentCharIndex < this.lineLength) { this.currentChar = this.line.charAt(this.currentCharIndex); if (this.currentChar !== " " && this.currentChar !== " ") return; this.currentCharIndex++; } } getToken() { const pos0 = this.currentCharIndex++; while (this.currentCharIndex < this.lineLength) { this.currentChar = this.line.charAt(this.currentCharIndex); if (this.currentChar === " " || this.currentChar === " ") break; this.currentCharIndex++; } const pos1 = this.currentCharIndex; this.seekNonSpace(); return this.line.substring(pos0, pos1); } getVector() { return new Vector3(parseFloat(this.getToken()), parseFloat(this.getToken()), parseFloat(this.getToken())); } getRemainingString() { return this.line.substring(this.currentCharIndex, this.lineLength); } isAtTheEnd() { return this.currentCharIndex >= this.lineLength; } setToEnd() { this.currentCharIndex = this.lineLength; } getLineNumberString() { return this.lineNumber >= 0 ? " at line " + this.lineNumber : ""; } }; var LDrawParsedCache = class { constructor(loader) { this.loader = loader; this._cache = {}; } cloneResult(original) { const result = {}; result.faces = original.faces.map((face) => { return { colorCode: face.colorCode, material: face.material, vertices: face.vertices.map((v) => v.clone()), normals: face.normals.map(() => null), faceNormal: null }; }); result.conditionalSegments = original.conditionalSegments.map((face) => { return { colorCode: face.colorCode, material: face.material, vertices: face.vertices.map((v) => v.clone()), controlPoints: face.controlPoints.map((v) => v.clone()) }; }); result.lineSegments = original.lineSegments.map((face) => { return { colorCode: face.colorCode, material: face.material, vertices: face.vertices.map((v) => v.clone()) }; }); result.type = original.type; result.category = original.category; result.keywords = original.keywords; result.subobjects = original.subobjects; result.totalFaces = original.totalFaces; result.startingConstructionStep = original.startingConstructionStep; result.materials = original.materials; result.group = null; return result; } async fetchData(fileName) { let triedLowerCase = false; let locationState = FILE_LOCATION_AS_IS; while (locationState !== FILE_LOCATION_NOT_FOUND) { let subobjectURL = fileName; switch (locationState) { case FILE_LOCATION_AS_IS: locationState = locationState + 1; break; case FILE_LOCATION_TRY_PARTS: subobjectURL = "parts/" + subobjectURL; locationState = locationState + 1; break; case FILE_LOCATION_TRY_P: subobjectURL = "p/" + subobjectURL; locationState = locationState + 1; break; case FILE_LOCATION_TRY_MODELS: subobjectURL = "models/" + subobjectURL; locationState = locationState + 1; break; case FILE_LOCATION_TRY_RELATIVE: subobjectURL = fileName.substring(0, fileName.lastIndexOf("/") + 1) + subobjectURL; locationState = locationState + 1; break; case FILE_LOCATION_TRY_ABSOLUTE: if (triedLowerCase) locationState = FILE_LOCATION_NOT_FOUND; else { fileName = fileName.toLowerCase(); subobjectURL = fileName; triedLowerCase = true; locationState = FILE_LOCATION_AS_IS; } break; } const loader = this.loader; const fileLoader = new FileLoader(loader.manager); fileLoader.setPath(loader.partsLibraryPath); fileLoader.setRequestHeader(loader.requestHeader); fileLoader.setWithCredentials(loader.withCredentials); try { return await fileLoader.loadAsync(subobjectURL); } catch (e) { continue; } } throw new Error("LDrawLoader: Subobject \"" + fileName + "\" could not be loaded."); } parse(text, fileName = null) { const loader = this.loader; const faces = []; const lineSegments = []; const conditionalSegments = []; const subobjects = []; const materials = {}; const getLocalMaterial = (colorCode) => { return materials[colorCode] || null; }; let type = "Model"; let category = null; let keywords = null; let totalFaces = 0; if (text.indexOf("\r\n") !== -1) text = text.replace(/\r\n/g, "\n"); const lines = text.split("\n"); const numLines = lines.length; let parsingEmbeddedFiles = false; let currentEmbeddedFileName = null; let currentEmbeddedText = null; let bfcCertified = false; let bfcCCW = true; let bfcInverted = false; let bfcCull = true; let startingConstructionStep = false; for (let lineIndex = 0; lineIndex < numLines; lineIndex++) { const line = lines[lineIndex]; if (line.length === 0) continue; if (parsingEmbeddedFiles) { if (line.startsWith("0 FILE ")) { this.setData(currentEmbeddedFileName, currentEmbeddedText); currentEmbeddedFileName = line.substring(7); currentEmbeddedText = ""; } else currentEmbeddedText += line + "\n"; continue; } const lp = new LineParser(line, lineIndex + 1); lp.seekNonSpace(); if (lp.isAtTheEnd()) continue; const lineType = lp.getToken(); let material; let colorCode; let segment; let ccw; let doubleSided; let v0, v1, v2, v3, c0, c1; switch (lineType) { case "0": const meta = lp.getToken(); if (meta) switch (meta) { case "!LDRAW_ORG": type = lp.getToken(); break; case "!COLOUR": material = loader.parseColorMetaDirective(lp); if (material) materials[material.userData.code] = material; else console.warn("LDrawLoader: Error parsing material" + lp.getLineNumberString()); break; case "!CATEGORY": category = lp.getToken(); break; case "!KEYWORDS": const newKeywords = lp.getRemainingString().split(","); if (newKeywords.length > 0) { if (!keywords) keywords = []; newKeywords.forEach(function(keyword) { keywords.push(keyword.trim()); }); } break; case "FILE": if (lineIndex > 0) { parsingEmbeddedFiles = true; currentEmbeddedFileName = lp.getRemainingString(); currentEmbeddedText = ""; bfcCertified = false; bfcCCW = true; } break; case "BFC": while (!lp.isAtTheEnd()) { const token = lp.getToken(); switch (token) { case "CERTIFY": case "NOCERTIFY": bfcCertified = token === "CERTIFY"; bfcCCW = true; break; case "CW": case "CCW": bfcCCW = token === "CCW"; break; case "INVERTNEXT": bfcInverted = true; break; case "CLIP": case "NOCLIP": bfcCull = token === "CLIP"; break; default: console.warn("THREE.LDrawLoader: BFC directive \"" + token + "\" is unknown."); break; } } break; case "STEP": startingConstructionStep = true; break; } break; case "1": colorCode = lp.getToken(); material = getLocalMaterial(colorCode); const posX = parseFloat(lp.getToken()); const posY = parseFloat(lp.getToken()); const posZ = parseFloat(lp.getToken()); const m0 = parseFloat(lp.getToken()); const m1 = parseFloat(lp.getToken()); const m2 = parseFloat(lp.getToken()); const m3 = parseFloat(lp.getToken()); const m4 = parseFloat(lp.getToken()); const m5 = parseFloat(lp.getToken()); const m6 = parseFloat(lp.getToken()); const m7 = parseFloat(lp.getToken()); const m8 = parseFloat(lp.getToken()); const matrix = new Matrix4().set(m0, m1, m2, posX, m3, m4, m5, posY, m6, m7, m8, posZ, 0, 0, 0, 1); let fileName2 = lp.getRemainingString().trim().replace(/\\/g, "/"); if (loader.fileMap[fileName2]) fileName2 = loader.fileMap[fileName2]; else if (fileName2.startsWith("s/")) fileName2 = "parts/" + fileName2; else if (fileName2.startsWith("48/")) fileName2 = "p/" + fileName2; subobjects.push({ material, colorCode, matrix, fileName: fileName2, inverted: bfcInverted, startingConstructionStep }); bfcInverted = false; break; case "2": colorCode = lp.getToken(); material = getLocalMaterial(colorCode); v0 = lp.getVector(); v1 = lp.getVector(); segment = { material, colorCode, vertices: [v0, v1] }; lineSegments.push(segment); break; case "5": colorCode = lp.getToken(); material = getLocalMaterial(colorCode); v0 = lp.getVector(); v1 = lp.getVector(); c0 = lp.getVector(); c1 = lp.getVector(); segment = { material, colorCode, vertices: [v0, v1], controlPoints: [c0, c1] }; conditionalSegments.push(segment); break; case "3": colorCode = lp.getToken(); material = getLocalMaterial(colorCode); ccw = bfcCCW; doubleSided = !bfcCertified || !bfcCull; if (ccw === true) { v0 = lp.getVector(); v1 = lp.getVector(); v2 = lp.getVector(); } else { v2 = lp.getVector(); v1 = lp.getVector(); v0 = lp.getVector(); } faces.push({ material, colorCode, faceNormal: null, vertices: [ v0, v1, v2 ], normals: [ null, null, null ] }); totalFaces++; if (doubleSided === true) { faces.push({ material, colorCode, faceNormal: null, vertices: [ v2, v1, v0 ], normals: [ null, null, null ] }); totalFaces++; } break; case "4": colorCode = lp.getToken(); material = getLocalMaterial(colorCode); ccw = bfcCCW; doubleSided = !bfcCertified || !bfcCull; if (ccw === true) { v0 = lp.getVector(); v1 = lp.getVector(); v2 = lp.getVector(); v3 = lp.getVector(); } else { v3 = lp.getVector(); v2 = lp.getVector(); v1 = lp.getVector(); v0 = lp.getVector(); } faces.push({ material, colorCode, faceNormal: null, vertices: [ v0, v1, v2, v3 ], normals: [ null, null, null, null ] }); totalFaces += 2; if (doubleSided === true) { faces.push({ material, colorCode, faceNormal: null, vertices: [ v3, v2, v1, v0 ], normals: [ null, null, null, null ] }); totalFaces += 2; } break; default: throw new Error("LDrawLoader: Unknown line type \"" + lineType + "\"" + lp.getLineNumberString() + "."); } } if (parsingEmbeddedFiles) this.setData(currentEmbeddedFileName, currentEmbeddedText); return { faces, conditionalSegments, lineSegments, type, category, keywords, subobjects, totalFaces, startingConstructionStep, materials, fileName, group: null }; } getData(fileName, clone = true) { const key = fileName.toLowerCase(); const result = this._cache[key]; if (result === null || result instanceof Promise) return null; if (clone) return this.cloneResult(result); else return result; } async ensureDataLoaded(fileName) { const key = fileName.toLowerCase(); if (!(key in this._cache)) this._cache[key] = this.fetchData(fileName).then((text) => { const info = this.parse(text, fileName); this._cache[key] = info; return info; }); await this._cache[key]; } setData(fileName, text) { const key = fileName.toLowerCase(); this._cache[key] = this.parse(text, fileName); } }; function getMaterialFromCode(colorCode, parentColorCode, materialHierarchy, forEdge) { if (!forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE) colorCode = parentColorCode; return materialHierarchy[colorCode] || null; } var LDrawPartsGeometryCache = class { constructor(loader) { this.loader = loader; this.parseCache = new LDrawParsedCache(loader); this._cache = {}; } async processIntoMesh(info) { const loader = this.loader; const parseCache = this.parseCache; const faceMaterials = /* @__PURE__ */ new Set(); const processInfoSubobjects = async (info2, subobject = null) => { const subobjects = info2.subobjects; const promises = []; for (let i = 0, l = subobjects.length; i < l; i++) { const subobject2 = subobjects[i]; const promise = parseCache.ensureDataLoaded(subobject2.fileName).then(() => { if (!isPrimitiveType(parseCache.getData(subobject2.fileName, false).type)) return this.loadModel(subobject2.fileName).catch((error) => { console.warn(error); return null; }); return processInfoSubobjects(parseCache.getData(subobject2.fileName), subobject2); }); promises.push(promise); } const group2 = new Group(); group2.userData.category = info2.category; group2.userData.keywords = info2.keywords; info2.group = group2; const subobjectInfos = await Promise.all(promises); for (let i = 0, l = subobjectInfos.length; i < l; i++) { const subobject2 = info2.subobjects[i]; const subobjectInfo = subobjectInfos[i]; if (subobjectInfo === null) continue; if (subobjectInfo.isGroup) { const subobjectGroup = subobjectInfo; subobject2.matrix.decompose(subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale); subobjectGroup.userData.startingConstructionStep = subobject2.startingConstructionStep; subobjectGroup.name = subobject2.fileName; loader.applyMaterialsToMesh(subobjectGroup, subobject2.colorCode, info2.materials); group2.add(subobjectGroup); continue; } if (subobjectInfo.group.children.length) group2.add(subobjectInfo.group); const parentLineSegments = info2.lineSegments; const parentConditionalSegments = info2.conditionalSegments; const parentFaces = info2.faces; const lineSegments = subobjectInfo.lineSegments; const conditionalSegments = subobjectInfo.conditionalSegments; const faces = subobjectInfo.faces; const matrix = subobject2.matrix; const inverted = subobject2.inverted; const matrixScaleInverted = matrix.determinant() < 0; const colorCode = subobject2.colorCode; const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode; for (let i2 = 0, l2 = lineSegments.length; i2 < l2; i2++) { const ls = lineSegments[i2]; const vertices = ls.vertices; vertices[0].applyMatrix4(matrix); vertices[1].applyMatrix4(matrix); ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode; ls.material = ls.material || getMaterialFromCode(ls.colorCode, ls.colorCode, info2.materials, true); parentLineSegments.push(ls); } for (let i2 = 0, l2 = conditionalSegments.length; i2 < l2; i2++) { const os = conditionalSegments[i2]; const vertices = os.vertices; const controlPoints = os.controlPoints; vertices[0].applyMatrix4(matrix); vertices[1].applyMatrix4(matrix); controlPoints[0].applyMatrix4(matrix); controlPoints[1].applyMatrix4(matrix); os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode; os.material = os.material || getMaterialFromCode(os.colorCode, os.colorCode, info2.materials, true); parentConditionalSegments.push(os); } for (let i2 = 0, l2 = faces.length; i2 < l2; i2++) { const tri = faces[i2]; const vertices = tri.vertices; for (let i3 = 0, l3 = vertices.length; i3 < l3; i3++) vertices[i3].applyMatrix4(matrix); tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode; tri.material = tri.material || getMaterialFromCode(tri.colorCode, colorCode, info2.materials, false); faceMaterials.add(tri.colorCode); if (matrixScaleInverted !== inverted) vertices.reverse(); parentFaces.push(tri); } info2.totalFaces += subobjectInfo.totalFaces; } if (subobject) loader.applyMaterialsToMesh(group2, subobject.colorCode, info2.materials); return info2; }; for (let i = 0, l = info.faces; i < l; i++) faceMaterials.add(info.faces[i].colorCode); await processInfoSubobjects(info); if (loader.smoothNormals) { const checkSubSegments = faceMaterials.size > 1; generateFaceNormals(info.faces); smoothNormals(info.faces, info.lineSegments, checkSubSegments); } const group = info.group; if (info.faces.length > 0) group.add(createObject(info.faces, 3, false, info.totalFaces)); if (info.lineSegments.length > 0) group.add(createObject(info.lineSegments, 2)); if (info.conditionalSegments.length > 0) group.add(createObject(info.conditionalSegments, 2, true)); return group; } hasCachedModel(fileName) { return fileName !== null && fileName.toLowerCase() in this._cache; } async getCachedModel(fileName) { if (fileName !== null && this.hasCachedModel(fileName)) { const key = fileName.toLowerCase(); return (await this._cache[key]).clone(); } else return null; } async loadModel(fileName) { const parseCache = this.parseCache; const key = fileName.toLowerCase(); if (this.hasCachedModel(fileName)) return this.getCachedModel(fileName); else { await parseCache.ensureDataLoaded(fileName); const info = parseCache.getData(fileName); const promise = this.processIntoMesh(info); if (this.hasCachedModel(fileName)) return this.getCachedModel(fileName); if (isPartType(info.type)) this._cache[key] = promise; return (await promise).clone(); } } async parseModel(text) { const info = this.parseCache.parse(text); if (isPartType(info.type) && this.hasCachedModel(info.fileName)) return this.getCachedModel(info.fileName); return this.processIntoMesh(info); } }; function sortByMaterial(a, b) { if (a.colorCode === b.colorCode) return 0; if (a.colorCode < b.colorCode) return -1; return 1; } function createObject(elements, elementSize, isConditionalSegments = false, totalElements = null) { elements.sort(sortByMaterial); if (totalElements === null) totalElements = elements.length; const positions = new Float32Array(elementSize * totalElements * 3); const normals = elementSize === 3 ? new Float32Array(elementSize * totalElements * 3) : null; const materials = []; const quadArray = new Array(6); const bufferGeometry = new BufferGeometry(); let prevMaterial = null; let index0 = 0; let numGroupVerts = 0; let offset = 0; for (let iElem = 0, nElem = elements.length; iElem < nElem; iElem++) { const elem = elements[iElem]; let vertices = elem.vertices; if (vertices.length === 4) { quadArray[0] = vertices[0]; quadArray[1] = vertices[1]; quadArray[2] = vertices[2]; quadArray[3] = vertices[0]; quadArray[4] = vertices[2]; quadArray[5] = vertices[3]; vertices = quadArray; } for (let j = 0, l = vertices.length; j < l; j++) { const v = vertices[j]; const index = offset + j * 3; positions[index + 0] = v.x; positions[index + 1] = v.y; positions[index + 2] = v.z; } if (elementSize === 3) { if (!elem.faceNormal) { const v0 = vertices[0]; const v1 = vertices[1]; const v2 = vertices[2]; _tempVec0.subVectors(v1, v0); _tempVec1.subVectors(v2, v1); elem.faceNormal = new Vector3().crossVectors(_tempVec0, _tempVec1).normalize(); } let elemNormals = elem.normals; if (elemNormals.length === 4) { quadArray[0] = elemNormals[0]; quadArray[1] = elemNormals[1]; quadArray[2] = elemNormals[2]; quadArray[3] = elemNormals[0]; quadArray[4] = elemNormals[2]; quadArray[5] = elemNormals[3]; elemNormals = quadArray; } for (let j = 0, l = elemNormals.length; j < l; j++) { let n = elem.faceNormal; if (elemNormals[j]) n = elemNormals[j].norm; const index = offset + j * 3; normals[index + 0] = n.x; normals[index + 1] = n.y; normals[index + 2] = n.z; } } if (prevMaterial !== elem.colorCode) { if (prevMaterial !== null) bufferGeometry.addGroup(index0, numGroupVerts, materials.length - 1); const material = elem.material; if (material !== null) { if (elementSize === 3) materials.push(material); else if (elementSize === 2) if (material !== null) if (isConditionalSegments) materials.push(material.userData.edgeMaterial.userData.conditionalEdgeMaterial); else materials.push(material.userData.edgeMaterial); else materials.push(null); } else materials.push(elem.colorCode); prevMaterial = elem.colorCode; index0 = offset / 3; numGroupVerts = vertices.length; } else numGroupVerts += vertices.length; offset += 3 * vertices.length; } if (numGroupVerts > 0) bufferGeometry.addGroup(index0, Infinity, materials.length - 1); bufferGeometry.setAttribute("position", new BufferAttribute(positions, 3)); if (normals !== null) bufferGeometry.setAttribute("normal", new BufferAttribute(normals, 3)); let object3d = null; if (elementSize === 2) if (isConditionalSegments) object3d = new ConditionalLineSegments(bufferGeometry, materials.length === 1 ? materials[0] : materials); else object3d = new LineSegments(bufferGeometry, materials.length === 1 ? materials[0] : materials); else if (elementSize === 3) object3d = new Mesh(bufferGeometry, materials.length === 1 ? materials[0] : materials); if (isConditionalSegments) { object3d.isConditionalLine = true; const controlArray0 = new Float32Array(elements.length * 3 * 2); const controlArray1 = new Float32Array(elements.length * 3 * 2); const directionArray = new Float32Array(elements.length * 3 * 2); for (let i = 0, l = elements.length; i < l; i++) { const os = elements[i]; const vertices = os.vertices; const controlPoints = os.controlPoints; const c0 = controlPoints[0]; const c1 = controlPoints[1]; const v0 = vertices[0]; const v1 = vertices[1]; const index = i * 3 * 2; controlArray0[index + 0] = c0.x; controlArray0[index + 1] = c0.y; controlArray0[index + 2] = c0.z; controlArray0[index + 3] = c0.x; controlArray0[index + 4] = c0.y; controlArray0[index + 5] = c0.z; controlArray1[index + 0] = c1.x; controlArray1[index + 1] = c1.y; controlArray1[index + 2] = c1.z; controlArray1[index + 3] = c1.x; controlArray1[index + 4] = c1.y; controlArray1[index + 5] = c1.z; directionArray[index + 0] = v1.x - v0.x; directionArray[index + 1] = v1.y - v0.y; directionArray[index + 2] = v1.z - v0.z; directionArray[index + 3] = v1.x - v0.x; directionArray[index + 4] = v1.y - v0.y; directionArray[index + 5] = v1.z - v0.z; } bufferGeometry.setAttribute("control0", new BufferAttribute(controlArray0, 3, false)); bufferGeometry.setAttribute("control1", new BufferAttribute(controlArray1, 3, false)); bufferGeometry.setAttribute("direction", new BufferAttribute(directionArray, 3, false)); } return object3d; } var LDrawLoader = class extends Loader { constructor(manager) { super(manager); this.materials = []; this.materialLibrary = {}; this.partsCache = new LDrawPartsGeometryCache(this); this.fileMap = {}; this.setMaterials([]); this.smoothNormals = true; this.partsLibraryPath = ""; } setPartsLibraryPath(path) { this.partsLibraryPath = path; return this; } async preloadMaterials(url) { const fileLoader = new FileLoader(this.manager); fileLoader.setPath(this.path); fileLoader.setRequestHeader(this.requestHeader); fileLoader.setWithCredentials(this.withCredentials); const text = await fileLoader.loadAsync(url); const colorLineRegex = /^0 !COLOUR/; const lines = text.split(/[\n\r]/g); const materials = []; for (let i = 0, l = lines.length; i < l; i++) { const line = lines[i]; if (colorLineRegex.test(line)) { const directive = line.replace(colorLineRegex, ""); const material = this.parseColorMetaDirective(new LineParser(directive)); materials.push(material); } } this.setMaterials(materials); } load(url, onLoad, onProgress, onError) { const fileLoader = new FileLoader(this.manager); fileLoader.setPath(this.path); fileLoader.setRequestHeader(this.requestHeader); fileLoader.setWithCredentials(this.withCredentials); fileLoader.load(url, (text) => { this.partsCache.parseModel(text, this.materialLibrary).then((group) => { this.applyMaterialsToMesh(group, MAIN_COLOUR_CODE, this.materialLibrary, true); this.computeConstructionSteps(group); onLoad(group); }).catch(onError); }, onProgress, onError); } parse(text, onLoad) { this.partsCache.parseModel(text, this.materialLibrary).then((group) => { this.computeConstructionSteps(group); onLoad(group); }); } setMaterials(materials) { this.materialLibrary = {}; this.materials = []; for (let i = 0, l = materials.length; i < l; i++) this.addMaterial(materials[i]); this.addMaterial(this.parseColorMetaDirective(new LineParser("Main_Colour CODE 16 VALUE #FF8080 EDGE #333333"))); this.addMaterial(this.parseColorMetaDirective(new LineParser("Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333"))); return this; } setFileMap(fileMap) { this.fileMap = fileMap; return this; } addMaterial(material) { const matLib = this.materialLibrary; if (!matLib[material.userData.code]) { this.materials.push(material); matLib[material.userData.code] = material; } return this; } getMaterial(colorCode) { if (colorCode.startsWith("0x2")) { const color = colorCode.substring(3); return this.parseColorMetaDirective(new LineParser("Direct_Color_" + color + " CODE -1 VALUE #" + color + " EDGE #" + color)); } return this.materialLibrary[colorCode] || null; } applyMaterialsToMesh(group, parentColorCode, materialHierarchy, finalMaterialPass = false) { const loader = this; const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE; group.traverse((c) => { if (c.isMesh || c.isLineSegments) { if (Array.isArray(c.material)) { for (let i = 0, l = c.material.length; i < l; i++) if (!c.material[i].isMaterial) c.material[i] = getMaterial(c, c.material[i]); } else if (!c.material.isMaterial) c.material = getMaterial(c, c.material); } }); function getMaterial(c, colorCode) { if (parentIsPassthrough && !(colorCode in materialHierarchy) && !finalMaterialPass) return colorCode; const forEdge = c.isLineSegments || c.isConditionalLine; if (!forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE) colorCode = parentColorCode; let material = null; if (colorCode in materialHierarchy) material = materialHierarchy[colorCode]; else if (finalMaterialPass) { material = loader.getMaterial(colorCode); if (material === null) throw new Error(`LDrawLoader: Material properties for code ${colorCode} not available.`); } else return colorCode; if (c.isLineSegments) { material = material.userData.edgeMaterial; if (c.isConditionalLine) material = material.userData.conditionalEdgeMaterial; } return material; } } getMainMaterial() { return this.getMaterial(MAIN_COLOUR_CODE); } getMainEdgeMaterial() { return this.getMaterial(MAIN_EDGE_COLOUR_CODE); } parseColorMetaDirective(lineParser) { let code = null; let color = 16711935; let edgeColor = 16711935; let alpha = 1; let isTransparent = false; let luminance = 0; let finishType = FINISH_TYPE_DEFAULT; let edgeMaterial = null; const name = lineParser.getToken(); if (!name) throw new Error("LDrawLoader: Material name was expected after \"!COLOUR tag" + lineParser.getLineNumberString() + "."); let token = null; while (true) { token = lineParser.getToken(); if (!token) break; switch (token.toUpperCase()) { case "CODE": code = lineParser.getToken(); break; case "VALUE": color = lineParser.getToken(); if (color.startsWith("0x")) color = "#" + color.substring(2); else if (!color.startsWith("#")) throw new Error("LDrawLoader: Invalid color while parsing material" + lineParser.getLineNumberString() + "."); break; case "EDGE": edgeColor = lineParser.getToken(); if (edgeColor.startsWith("0x")) edgeColor = "#" + edgeColor.substring(2); else if (!edgeColor.startsWith("#")) { edgeMaterial = this.getMaterial(edgeColor); if (!edgeMaterial) throw new Error("LDrawLoader: Invalid edge color while parsing material" + lineParser.getLineNumberString() + "."); edgeMaterial = edgeMaterial.userData.edgeMaterial; } break; case "ALPHA": alpha = parseInt(lineParser.getToken()); if (isNaN(alpha)) throw new Error("LDrawLoader: Invalid alpha value in material definition" + lineParser.getLineNumberString() + "."); alpha = Math.max(0, Math.min(1, alpha / 255)); if (alpha < 1) isTransparent = true; break; case "LUMINANCE": luminance = parseInt(lineParser.getToken()); if (isNaN(luminance)) throw new Error("LDrawLoader: Invalid luminance value in material definition" + LineParser.getLineNumberString() + "."); luminance = Math.max(0, Math.min(1, luminance / 255)); break; case "CHROME": finishType = FINISH_TYPE_CHROME; break; case "PEARLESCENT": finishType = FINISH_TYPE_PEARLESCENT; break; case "RUBBER": finishType = FINISH_TYPE_RUBBER; break; case "MATTE_METALLIC": finishType = FINISH_TYPE_MATTE_METALLIC; break; case "METAL": finishType = FINISH_TYPE_METAL; break; case "MATERIAL": lineParser.setToEnd(); break; default: throw new Error("LDrawLoader: Unknown token \"" + token + "\" while parsing material" + lineParser.getLineNumberString() + "."); } } let material = null; switch (finishType) { case FINISH_TYPE_DEFAULT: material = new MeshStandardMaterial({ color, roughness: .3, metalness: 0 }); break; case FINISH_TYPE_PEARLESCENT: material = new MeshStandardMaterial({ color, roughness: .3, metalness: .25 }); break; case FINISH_TYPE_CHROME: material = new MeshStandardMaterial({ color, roughness: 0, metalness: 1 }); break; case FINISH_TYPE_RUBBER: material = new MeshStandardMaterial({ color, roughness: .9, metalness: 0 }); break; case FINISH_TYPE_MATTE_METALLIC: material = new MeshStandardMaterial({ color, roughness: .8, metalness: .4 }); break; case FINISH_TYPE_METAL: material = new MeshStandardMaterial({ color, roughness: .2, metalness: .85 }); break; } material.transparent = isTransparent; material.premultipliedAlpha = true; material.opacity = alpha; material.depthWrite = !isTransparent; material.polygonOffset = true; material.polygonOffsetFactor = 1; if (luminance !== 0) material.emissive.set(material.color).multiplyScalar(luminance); if (!edgeMaterial) { edgeMaterial = new LineBasicMaterial({ color: edgeColor, transparent: isTransparent, opacity: alpha, depthWrite: !isTransparent }); edgeMaterial.userData.code = code; edgeMaterial.name = name + " - Edge"; edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial({ fog: true, transparent: isTransparent, depthWrite: !isTransparent, color: edgeColor, opacity: alpha }); } material.userData.code = code; material.name = name; material.userData.edgeMaterial = edgeMaterial; this.addMaterial(material); return material; } computeConstructionSteps(model) { let stepNumber = 0; model.traverse((c) => { if (c.isGroup) { if (c.userData.startingConstructionStep) stepNumber++; c.userData.constructionStep = stepNumber; } }); model.userData.numConstructionSteps = stepNumber + 1; } }; //#endregion //#region 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 loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); 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 usedNodeId = (node.getAttributeNS("http://www.w3.org/1999/xlink", "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 i = 0; i < childNodes.length; i++) { const node2 = childNodes[i]; 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 d = node.getAttribute("d"); if (d === "" || d === "none") return null; const commands = d.match(/[a-df-z][^a-df-z]*/gi); for (let i = 0, l = commands.length; i < l; i++) { const command = commands[i]; 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 i = 0; i < node.sheet.cssRules.length; i++) { const stylesheet = node.sheet.cssRules[i]; if (stylesheet.type !== 1) continue; const selectorList = stylesheet.selectorText.split(/,/gm).filter(Boolean).map((i2) => i2.trim()); for (let j = 0; j < selectorList.length; j++) { const definitions = Object.fromEntries(Object.entries(stylesheet.style).filter(([, v]) => v !== "")); 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 s = Math.sqrt(cr); rx = s * rx; ry = s * ry; rxs = rx * rx; rys = ry * ry; } const dq = rxs * y1ps + rys * x1ps; const pq = (rxs * rys - dq) / dq; let 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 dot = ux * vx + uy * vy; const len = Math.sqrt(ux * ux + uy * uy) * Math.sqrt(vx * vx + vy * vy); let ang = Math.acos(Math.max(-1, Math.min(1, dot / len))); if (ux * vy - uy * vx < 0) ang = -ang; return ang; } function parseRectNode(node) { const 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 = .448084975506; 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, a, b) { const x = parseFloatWithUnits(a); const y = parseFloatWithUnits(b); if (index === 0) path.moveTo(x, y); else path.lineTo(x, y); index++; } const regex = /([+-]?\d*\.?\d+(?:e[+-]?\d+)?)(?:,|\s)([+-]?\d*\.?\d+(?:e[+-]?\d+)?)/g; const path = new ShapePath(); let index = 0; node.getAttribute("points").replace(regex, iterator); path.currentPath.autoClose = true; return path; } function parsePolylineNode(node) { function iterator(match, a, b) { const x = parseFloatWithUnits(a); const y = parseFloatWithUnits(b); if (index === 0) path.moveTo(x, y); else path.lineTo(x, y); index++; } const regex = /([+-]?\d*\.?\d+(?:e[+-]?\d+)?)(?:,|\s)([+-]?\d*\.?\d+(?:e[+-]?\d+)?)/g; const path = new ShapePath(); let index = 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 r = parseFloatWithUnits(node.getAttribute("r") || 0); const subpath = new Path(); subpath.absarc(x, y, r, 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((i) => i.trim()); for (let i = 0; i < classSelectors.length; i++) stylesheetStyles = Object.assign(stylesheetStyles, stylesheets["." + classSelectors[i]]); } if (node.hasAttribute("id")) stylesheetStyles = Object.assign(stylesheetStyles, stylesheets["#" + node.getAttribute("id")]); function addStyle(svgName, jsName, adjustFunction) { if (adjustFunction === void 0) adjustFunction = function copy(v) { if (v.startsWith("url")) console.warn("SVGLoader: url access in attributes is not implemented."); return v; }; if (node.hasAttribute(svgName)) style[jsName] = adjustFunction(node.getAttribute(svgName)); if (stylesheetStyles[svgName]) style[jsName] = adjustFunction(stylesheetStyles[svgName]); if (node.style && node.style[svgName] !== "") style[jsName] = adjustFunction(node.style[svgName]); } function clamp(v) { return Math.max(0, Math.min(1, parseFloatWithUnits(v))); } function positive(v) { return Math.max(0, parseFloatWithUnits(v)); } addStyle("fill", "fill"); addStyle("fill-opacity", "fillOpacity", clamp); addStyle("fill-rule", "fillRule"); addStyle("opacity", "opacity", clamp); addStyle("stroke", "stroke"); addStyle("stroke-opacity", "strokeOpacity", clamp); 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(a, b) { return a - (b - a); } function parseFloats(input, flags, stride) { if (typeof input !== "string") throw new TypeError("Invalid input: " + typeof input); const RE = { SEPARATOR: /[ \t\r\n\,.\-+]/, WHITESPACE: /[ \t\r\n]/, DIGIT: /[\d]/, SIGN: /[-+]/, POINT: /\./, COMMA: /,/, EXP: /e/i, FLAGS: /[01]/ }; const SEP = 0; const INT = 1; const FLOAT = 2; const EXP = 3; let state = SEP; let seenComma = true; let number = "", exponent = ""; const result = []; function throwSyntaxError(current2, i, partial) { const error = /* @__PURE__ */ new SyntaxError("Unexpected character \"" + current2 + "\" at index " + i + "."); 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 length = input.length; for (let i = 0; i < length; i++) { current = input[i]; if (Array.isArray(flags) && flags.includes(result.length % stride) && RE.FLAGS.test(current)) { state = INT; number = current; newNumber(); continue; } if (state === SEP) { if (RE.WHITESPACE.test(current)) continue; if (RE.DIGIT.test(current) || RE.SIGN.test(current)) { state = INT; number = current; continue; } if (RE.POINT.test(current)) { state = FLOAT; number = current; continue; } if (RE.COMMA.test(current)) { if (seenComma) throwSyntaxError(current, i, result); seenComma = true; } } if (state === INT) { if (RE.DIGIT.test(current)) { number += current; continue; } if (RE.POINT.test(current)) { number += current; state = FLOAT; continue; } if (RE.EXP.test(current)) { state = EXP; continue; } if (RE.SIGN.test(current) && number.length === 1 && RE.SIGN.test(number[0])) throwSyntaxError(current, i, result); } if (state === FLOAT) { if (RE.DIGIT.test(current)) { number += current; continue; } if (RE.EXP.test(current)) { state = EXP; continue; } if (RE.POINT.test(current) && number[number.length - 1] === ".") throwSyntaxError(current, i, result); } if (state === EXP) { if (RE.DIGIT.test(current)) { exponent += current; continue; } if (RE.SIGN.test(current)) { if (exponent === "") { exponent += current; continue; } if (exponent.length === 1 && RE.SIGN.test(exponent)) throwSyntaxError(current, i, result); } } if (RE.WHITESPACE.test(current)) { newNumber(); state = SEP; seenComma = false; } else if (RE.COMMA.test(current)) { newNumber(); state = SEP; seenComma = true; } else if (RE.SIGN.test(current)) { newNumber(); state = INT; number = current; } else if (RE.POINT.test(current)) { newNumber(); state = FLOAT; number = current; } else throwSyntaxError(current, i, result); } newNumber(); return result; } const units = [ "mm", "cm", "in", "pt", "pc", "px" ]; const unitConversion = { mm: { mm: 1, cm: .1, in: 1 / 25.4, pt: 72 / 25.4, pc: 6 / 25.4, px: -1 }, cm: { mm: 10, cm: 1, in: 1 / 2.54, pt: 72 / 2.54, pc: 6 / 2.54, px: -1 }, in: { mm: 25.4, cm: 2.54, in: 1, pt: 72, pc: 6, px: -1 }, pt: { mm: 25.4 / 72, cm: 2.54 / 72, in: 1 / 72, pt: 1, pc: 6 / 72, px: -1 }, pc: { mm: 25.4 / 6, cm: 2.54 / 6, in: 1 / 6, pt: 72 / 6, pc: 1, px: -1 }, px: { px: 1 } }; function parseFloatWithUnits(string) { let theUnit = "px"; if (typeof string === "string" || string instanceof String) for (let i = 0, n = units.length; i < n; i++) { const u = units[i]; if (string.endsWith(u)) { theUnit = u; string = string.substring(0, string.length - u.length); break; } } let scale = void 0; if (theUnit === "px" && scope.defaultUnit !== "px") scale = unitConversion["in"][scope.defaultUnit] / scope.defaultDPI; else { scale = unitConversion[theUnit][scope.defaultUnit]; if (scale < 0) scale = unitConversion[theUnit]["in"] * scope.defaultDPI; } return scale * 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(v2) { tempV3.set(v2.x, v2.y, 1).applyMatrix3(m); v2.set(tempV3.x, tempV3.y); } function transfEllipseGeneric(curve) { const a = curve.xRadius; const b = curve.yRadius; const cosTheta = Math.cos(curve.aRotation); const sinTheta = Math.sin(curve.aRotation); const v1 = new Vector3(a * cosTheta, a * sinTheta, 0); const v2 = new Vector3(-b * sinTheta, b * cosTheta, 0); const f1 = v1.applyMatrix3(m); const f2 = v2.applyMatrix3(m); const mF = tempTransform0.set(f1.x, f2.x, 0, f1.y, f2.y, 0, 0, 0, 1); const mFInv = tempTransform1.copy(mF).invert(); const mQe = tempTransform2.copy(mFInv).transpose().multiply(mFInv).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); if (!((curve.aEndAngle - curve.aStartAngle) % (2 * Math.PI) < Number.EPSILON)) { const mDsqrt = tempTransform1.set(rt1sqrt, 0, 0, 0, rt2sqrt, 0, 0, 0, 1); const mRT = tempTransform2.set(ed.cs, ed.sn, 0, -ed.sn, ed.cs, 0, 0, 0, 1); const mDRF = mDsqrt.multiply(mRT).multiply(mF); const transformAngle = (phi) => { const { x: cosR, y: sinR } = new Vector3(Math.cos(phi), Math.sin(phi), 0).applyMatrix3(mDRF); return Math.atan2(sinR, cosR); }; curve.aStartAngle = transformAngle(curve.aStartAngle); curve.aEndAngle = transformAngle(curve.aEndAngle); if (isTransformFlipped(m)) curve.aClockwise = !curve.aClockwise; } } function transfEllipseNoSkew(curve) { const sx = getTransformScaleX(m); const sy = getTransformScaleY(m); curve.xRadius *= sx; curve.yRadius *= sy; const theta = sx > Number.EPSILON ? Math.atan2(m.elements[1], m.elements[0]) : Math.atan2(-m.elements[3], m.elements[4]); curve.aRotation += theta; if (isTransformFlipped(m)) { curve.aStartAngle *= -1; curve.aEndAngle *= -1; curve.aClockwise = !curve.aClockwise; } } const subPaths = path.subPaths; for (let i = 0, n = subPaths.length; i < n; i++) { const curves = subPaths[i].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) { tempV2.set(curve.aX, curve.aY); transfVec2(tempV2); curve.aX = tempV2.x; curve.aY = tempV2.y; if (isTransformSkewed(m)) transfEllipseGeneric(curve); else transfEllipseNoSkew(curve); } } } } function isTransformFlipped(m) { const te = m.elements; return te[0] * te[4] - te[1] * te[3] < 0; } function isTransformSkewed(m) { const te = m.elements; const basisDot = te[0] * te[3] + te[1] * te[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 te = m.elements; return Math.sqrt(te[0] * te[0] + te[1] * te[1]); } function getTransformScaleY(m) { const te = m.elements; return Math.sqrt(te[3] * te[3] + te[4] * te[4]); } function eigenDecomposition(A, B, C) { let rt1, rt2, cs, sn, t; const sm = A + C; const df = A - C; const rt = Math.sqrt(df * df + 4 * B * B); if (sm > 0) { rt1 = .5 * (sm + rt); t = 1 / rt1; rt2 = A * t * C - B * t * B; } else if (sm < 0) rt2 = .5 * (sm - rt); else { rt1 = .5 * rt; rt2 = -.5 * rt; } if (df > 0) cs = df + rt; else cs = df - rt; if (Math.abs(cs) > 2 * Math.abs(B)) { t = -2 * B / cs; sn = 1 / Math.sqrt(1 + t * t); cs = t * sn; } else if (Math.abs(B) === 0) { cs = 1; sn = 0; } else { t = -.5 * cs / B; cs = 1 / Math.sqrt(1 + t * t); sn = t * cs; } if (df > 0) { t = cs; cs = -sn; sn = t; } return { rt1, rt2, cs, sn }; } const paths = []; const stylesheets = {}; const transformStack = []; const tempTransform0 = new Matrix3(); const tempTransform1 = new Matrix3(); const tempTransform2 = new Matrix3(); const tempTransform3 = new Matrix3(); const tempV2 = new Vector2(); const tempV3 = new Vector3(); const currentTransform = new Matrix3(); const xml = new DOMParser().parseFromString(text, "image/svg+xml"); parseNode(xml.documentElement, { fill: "#000", fillOpacity: 1, strokeOpacity: 1, strokeWidth: 1, strokeLineJoin: "miter", strokeLineCap: "butt", strokeMiterLimit: 4 }); return { paths, xml: xml.documentElement }; } 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 t2 = nom2 / denom; if (denom === 0 && nom1 !== 0 || t1 <= 0 || t1 >= 1 || t2 < 0 || t2 > 1) return null; else if (nom1 === 0 && denom === 0) { for (let i = 0; i < 2; i++) { classifyPoint(i === 0 ? b0 : b1, a0, a1); if (classifyResult.loc == IntersectionLocationType.ORIGIN) { const point = i === 0 ? b0 : b1; return { x: point.x, y: point.y, t: classifyResult.t }; } else if (classifyResult.loc == IntersectionLocationType.BETWEEN) return { x: +(x1 + classifyResult.t * (x2 - x1)).toPrecision(10), y: +(y1 + classifyResult.t * (y2 - y1)).toPrecision(10), t: classifyResult.t }; } return null; } else { for (let i = 0; i < 2; i++) { classifyPoint(i === 0 ? b0 : b1, a0, a1); if (classifyResult.loc == IntersectionLocationType.ORIGIN) { const point = i === 0 ? b0 : b1; return { x: point.x, y: point.y, t: classifyResult.t }; } } return { x: +(x1 + t1 * (x2 - x1)).toPrecision(10), y: +(y1 + t1 * (y2 - y1)).toPrecision(10), t: t1 }; } } function classifyPoint(p, edgeStart, edgeEnd) { const ax = edgeEnd.x - edgeStart.x; const ay = edgeEnd.y - edgeStart.y; const bx = p.x - edgeStart.x; const by = p.y - edgeStart.y; const sa = ax * by - bx * ay; if (p.x === edgeStart.x && p.y === edgeStart.y) { classifyResult.loc = IntersectionLocationType.ORIGIN; classifyResult.t = 0; return; } if (p.x === edgeEnd.x && p.y === edgeEnd.y) { classifyResult.loc = IntersectionLocationType.DESTINATION; classifyResult.t = 1; return; } if (sa < -Number.EPSILON) { classifyResult.loc = IntersectionLocationType.LEFT; return; } if (sa > Number.EPSILON) { classifyResult.loc = IntersectionLocationType.RIGHT; return; } if (ax * bx < 0 || ay * by < 0) { classifyResult.loc = IntersectionLocationType.BEHIND; return; } if (Math.sqrt(ax * ax + ay * ay) < Math.sqrt(bx * bx + by * by)) { classifyResult.loc = IntersectionLocationType.BEYOND; return; } let t; if (ax !== 0) t = bx / ax; else t = by / ay; classifyResult.loc = IntersectionLocationType.BETWEEN; classifyResult.t = t; } function getIntersections(path1, path2) { const intersectionsRaw = []; const intersections = []; for (let index = 1; index < path1.length; index++) { const path1EdgeStart = path1[index - 1]; const path1EdgeEnd = path1[index]; for (let index2 = 1; index2 < path2.length; index2++) { const path2EdgeStart = path2[index2 - 1]; const path2EdgeEnd = path2[index2]; const intersection = findEdgeIntersection(path1EdgeStart, path1EdgeEnd, path2EdgeStart, path2EdgeEnd); if (intersection !== null && intersectionsRaw.find((i) => i.t <= intersection.t + Number.EPSILON && i.t >= intersection.t - Number.EPSILON) === void 0) { intersectionsRaw.push(intersection); intersections.push(new Vector2(intersection.x, intersection.y)); } } } return intersections; } function getScanlineIntersections(scanline, boundingBox, paths) { const center = new Vector2(); boundingBox.getCenter(center); const allIntersections = []; paths.forEach((path) => { if (path.boundingBox.containsPoint(center)) getIntersections(scanline, path.points).forEach((p) => { allIntersections.push({ identifier: path.identifier, isCW: path.isCW, point: p }); }); }); allIntersections.sort((i1, i2) => { return i1.point.x - i2.point.x; }); return allIntersections; } function isHoleTo(simplePath, allPaths, scanlineMinX2, scanlineMaxX2, _fillRule) { if (_fillRule === null || _fillRule === void 0 || _fillRule === "") _fillRule = "nonzero"; const centerBoundingBox = new Vector2(); simplePath.boundingBox.getCenter(centerBoundingBox); const scanlineIntersections = getScanlineIntersections([new Vector2(scanlineMinX2, centerBoundingBox.y), new Vector2(scanlineMaxX2, centerBoundingBox.y)], simplePath.boundingBox, allPaths); scanlineIntersections.sort((i1, i2) => { return i1.point.x - i2.point.x; }); const baseIntersections = []; const otherIntersections = []; scanlineIntersections.forEach((i2) => { if (i2.identifier === simplePath.identifier) baseIntersections.push(i2); else otherIntersections.push(i2); }); const firstXOfPath = baseIntersections[0].point.x; const stack = []; let i = 0; while (i < otherIntersections.length && otherIntersections[i].point.x < firstXOfPath) { if (stack.length > 0 && stack[stack.length - 1] === otherIntersections[i].identifier) stack.pop(); else stack.push(otherIntersections[i].identifier); i++; } stack.push(simplePath.identifier); if (_fillRule === "evenodd") { const isHole = stack.length % 2 === 0 ? true : false; const isHoleFor = stack[stack.length - 2]; return { identifier: simplePath.identifier, isHole, for: isHoleFor }; } else if (_fillRule === "nonzero") { let isHole = true; let isHoleFor = null; let lastCWValue = null; for (let i2 = 0; i2 < stack.length; i2++) { const identifier = stack[i2]; if (isHole) { lastCWValue = allPaths[identifier].isCW; isHole = false; isHoleFor = identifier; } else if (lastCWValue !== allPaths[identifier].isCW) { lastCWValue = allPaths[identifier].isCW; isHole = true; } } return { identifier: simplePath.identifier, isHole, for: isHoleFor }; } else console.warn("fill-rule: \"" + _fillRule + "\" is currently not implemented."); } let scanlineMinX = BIGNUMBER; let scanlineMaxX = -999999999; let simplePaths = shapePath.subPaths.map((p) => { const points = p.getPoints(); let maxY = -999999999; let minY = BIGNUMBER; let maxX = -999999999; let minX = BIGNUMBER; for (let i = 0; i < points.length; i++) { const p2 = points[i]; if (p2.y > maxY) maxY = p2.y; if (p2.y < minY) minY = p2.y; if (p2.x > maxX) maxX = p2.x; if (p2.x < minX) minX = p2.x; } if (scanlineMaxX <= maxX) scanlineMaxX = maxX + 1; if (scanlineMinX >= minX) scanlineMinX = minX - 1; return { curves: p.curves, points, isCW: ShapeUtils.isClockWise(points), identifier: -1, boundingBox: new Box2(new Vector2(minX, minY), new Vector2(maxX, maxY)) }; }); simplePaths = simplePaths.filter((sp) => sp.points.length > 1); for (let identifier = 0; identifier < simplePaths.length; identifier++) simplePaths[identifier].identifier = identifier; const isAHole = simplePaths.map((p) => isHoleTo(p, simplePaths, scanlineMinX, scanlineMaxX, shapePath.userData ? shapePath.userData.style.fillRule : void 0)); const shapesToReturn = []; simplePaths.forEach((p) => { if (!isAHole[p.identifier].isHole) { const shape = new Shape(); shape.curves = p.curves; isAHole.filter((h) => h.isHole && h.for === p.identifier).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 geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); return geometry; } 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 : .001; vertexOffset = vertexOffset !== void 0 ? vertexOffset : 0; points = removeDuplicatedPoints(points); const numPoints = points.length; if (numPoints < 2) return 0; const isClosed = points[0].equals(points[numPoints - 1]); let currentPoint; let previousPoint = points[0]; let nextPoint; const strokeWidth2 = style.strokeWidth / 2; const deltaU = 1 / (numPoints - 1); let u0 = 0, u1; let innerSideModified; let joinIsOnLeftSide; let isMiter; let initialJoinIsOnLeftSide = false; let numVertices = 0; let currentCoordinate = vertexOffset * 3; let currentCoordinateUV = vertexOffset * 2; getNormal(points[0], points[1], tempV2_1).multiplyScalar(strokeWidth2); lastPointL.copy(points[0]).sub(tempV2_1); lastPointR.copy(points[0]).add(tempV2_1); point0L.copy(lastPointL); point0R.copy(lastPointR); for (let iPoint = 1; iPoint < numPoints; iPoint++) { currentPoint = points[iPoint]; if (iPoint === numPoints - 1) if (isClosed) nextPoint = points[1]; else nextPoint = void 0; else nextPoint = points[iPoint + 1]; const normal1 = tempV2_1; getNormal(previousPoint, currentPoint, normal1); tempV2_3.copy(normal1).multiplyScalar(strokeWidth2); currentPointL.copy(currentPoint).sub(tempV2_3); currentPointR.copy(currentPoint).add(tempV2_3); u1 = u0 + deltaU; innerSideModified = false; if (nextPoint !== void 0) { getNormal(currentPoint, nextPoint, tempV2_2); tempV2_3.copy(tempV2_2).multiplyScalar(strokeWidth2); nextPointL.copy(currentPoint).sub(tempV2_3); nextPointR.copy(currentPoint).add(tempV2_3); joinIsOnLeftSide = true; tempV2_3.subVectors(nextPoint, previousPoint); if (normal1.dot(tempV2_3) < 0) joinIsOnLeftSide = false; if (iPoint === 1) initialJoinIsOnLeftSide = joinIsOnLeftSide; tempV2_3.subVectors(nextPoint, currentPoint); tempV2_3.normalize(); const dot = Math.abs(normal1.dot(tempV2_3)); if (dot > Number.EPSILON) { const miterSide = strokeWidth2 / dot; tempV2_3.multiplyScalar(-miterSide); tempV2_4.subVectors(currentPoint, previousPoint); tempV2_5.copy(tempV2_4).setLength(miterSide).add(tempV2_3); innerPoint.copy(tempV2_5).negate(); const miterLength2 = tempV2_5.length(); const segmentLengthPrev = tempV2_4.length(); tempV2_4.divideScalar(segmentLengthPrev); tempV2_6.subVectors(nextPoint, currentPoint); const segmentLengthNext = tempV2_6.length(); tempV2_6.divideScalar(segmentLengthNext); if (tempV2_4.dot(innerPoint) < segmentLengthPrev && tempV2_6.dot(innerPoint) < segmentLengthNext) innerSideModified = true; outerPoint.copy(tempV2_5).add(currentPoint); innerPoint.add(currentPoint); isMiter = false; if (innerSideModified) if (joinIsOnLeftSide) { nextPointR.copy(innerPoint); currentPointR.copy(innerPoint); } else { nextPointL.copy(innerPoint); currentPointL.copy(innerPoint); } else makeSegmentTriangles(); switch (style.strokeLineJoin) { case "bevel": makeSegmentWithBevelJoin(joinIsOnLeftSide, innerSideModified, u1); break; case "round": createSegmentTrianglesWithMiddleSection(joinIsOnLeftSide, innerSideModified); if (joinIsOnLeftSide) makeCircularSector(currentPoint, currentPointL, nextPointL, u1, 0); else makeCircularSector(currentPoint, nextPointR, currentPointR, u1, 1); break; 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, .5); addVertex(currentPoint, u1, .5); addVertex(tempV2_6, u1, 0); addVertex(tempV2_7, u1, 0); addVertex(currentPoint, u1, .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, .5); addVertex(currentPoint, u1, .5); addVertex(tempV2_6, u1, 1); addVertex(tempV2_7, u1, 1); addVertex(currentPoint, u1, .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, .5); addVertex(currentPoint, u1, .5); addVertex(outerPoint, u1, 0); addVertex(nextPointL, u1, 0); } else { addVertex(currentPointR, u1, 1); addVertex(outerPoint, u1, 1); addVertex(currentPoint, u1, .5); addVertex(currentPoint, u1, .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); lastInner.toArray(vertices, 9); if (isMiter) lastOuter.toArray(vertices, 3); } } else if (isMiter || !initialJoinIsOnLeftSide) { lastInner.toArray(vertices, 3); lastInner.toArray(vertices, 9); if (isMiter) lastOuter.toArray(vertices, 0); } } return numVertices; function getNormal(p1, p2, result) { result.subVectors(p2, p1); return result.set(-result.y, result.x).normalize(); } function addVertex(position, u, v) { if (vertices) { vertices[currentCoordinate] = position.x; vertices[currentCoordinate + 1] = position.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] = v; currentCoordinateUV += 2; } } numVertices += 3; } function makeCircularSector(center, p1, p2, u, v) { tempV2_1.copy(p1).sub(center).normalize(); tempV2_2.copy(p2).sub(center).normalize(); let angle = Math.PI; const dot = tempV2_1.dot(tempV2_2); if (Math.abs(dot) < 1) angle = Math.abs(Math.acos(dot)); angle /= arcDivisions; tempV2_3.copy(p1); for (let i = 0, il = arcDivisions - 1; i < il; i++) { tempV2_4.copy(tempV2_3).rotateAround(center, angle); addVertex(tempV2_3, u, v); addVertex(tempV2_4, u, v); addVertex(center, u, .5); tempV2_3.copy(tempV2_4); } addVertex(tempV2_4, u, v); addVertex(p2, u, v); addVertex(center, u, .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, .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, .5); } else { addVertex(currentPointR, u, 1); addVertex(nextPointR, u, 0); addVertex(currentPoint, u, .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, .5); addVertex(innerPoint, u1, 1); addVertex(currentPoint, u1, .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, .5); addVertex(currentPoint, u1, .5); addVertex(innerPoint, u1, 0); addVertex(nextPointR, u0, 1); } } function addCapGeometry(center, p1, p2, joinIsOnLeftSide2, start, u) { switch (style.strokeLineCap) { case "round": if (start) makeCircularSector(center, p2, p1, u, .5); else makeCircularSector(center, p1, p2, u, .5); break; case "square": if (start) { tempV2_1.subVectors(p1, center); tempV2_2.set(tempV2_1.y, -tempV2_1.x); tempV2_3.addVectors(tempV2_1, tempV2_2).add(center); tempV2_4.subVectors(tempV2_2, tempV2_1).add(center); if (joinIsOnLeftSide2) { tempV2_3.toArray(vertices, 3); tempV2_4.toArray(vertices, 0); tempV2_4.toArray(vertices, 9); } else { tempV2_3.toArray(vertices, 3); uvs[7] === 1 ? tempV2_4.toArray(vertices, 9) : tempV2_3.toArray(vertices, 9); tempV2_4.toArray(vertices, 0); } } else { tempV2_1.subVectors(p2, center); tempV2_2.set(tempV2_1.y, -tempV2_1.x); tempV2_3.addVectors(tempV2_1, tempV2_2).add(center); tempV2_4.subVectors(tempV2_2, tempV2_1).add(center); const vl = vertices.length; if (joinIsOnLeftSide2) { tempV2_3.toArray(vertices, vl - 3); tempV2_4.toArray(vertices, vl - 6); tempV2_4.toArray(vertices, vl - 12); } else { tempV2_4.toArray(vertices, vl - 6); tempV2_3.toArray(vertices, vl - 3); tempV2_4.toArray(vertices, vl - 12); } } break; } } function removeDuplicatedPoints(points2) { let dupPoints = false; for (let i = 1, n = points2.length - 1; i < n; i++) if (points2[i].distanceTo(points2[i + 1]) < minDistance) { dupPoints = true; break; } if (!dupPoints) return points2; const newPoints = []; newPoints.push(points2[0]); for (let i = 1, n = points2.length - 1; i < n; i++) if (points2[i].distanceTo(points2[i + 1]) >= minDistance) newPoints.push(points2[i]); newPoints.push(points2[points2.length - 1]); return newPoints; } } } return SVGLoader2; })(); //#endregion //#region node_modules/three-stdlib/loaders/3DMLoader.js var _taskCache$1 = /* @__PURE__ */ new WeakMap(); var Rhino3dmLoader = class extends Loader { constructor(manager) { super(manager); this.libraryPath = ""; this.libraryPending = null; this.libraryBinary = null; this.libraryConfig = {}; this.url = ""; this.workerLimit = 4; this.workerPool = []; this.workerNextTaskID = 1; this.workerSourceURL = ""; this.workerConfig = {}; this.materials = []; } setLibraryPath(path) { this.libraryPath = path; return this; } setWorkerLimit(workerLimit) { this.workerLimit = workerLimit; return this; } load(url, onLoad, onProgress, onError) { const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); this.url = url; loader.load(url, (buffer) => { if (_taskCache$1.has(buffer)) return _taskCache$1.get(buffer).promise.then(onLoad).catch(onError); this.decodeObjects(buffer, url).then(onLoad).catch(onError); }, onProgress, onError); } debug() { console.log("Task load: ", this.workerPool.map((worker) => worker._taskLoad)); } decodeObjects(buffer, url) { let worker; let taskID; const taskCost = buffer.byteLength; const objectPending = this._getWorker(taskCost).then((_worker) => { worker = _worker; taskID = this.workerNextTaskID++; return new Promise((resolve, reject) => { worker._callbacks[taskID] = { resolve, reject }; worker.postMessage({ type: "decode", id: taskID, buffer }, [buffer]); }); }).then((message) => this._createGeometry(message.data)); objectPending.catch(() => true).then(() => { if (worker && taskID) this._releaseTask(worker, taskID); }); _taskCache$1.set(buffer, { url, promise: objectPending }); return objectPending; } parse(data, onLoad, onError) { this.decodeObjects(data, "").then(onLoad).catch(onError); } _compareMaterials(material) { const mat = {}; mat.name = material.name; mat.color = {}; mat.color.r = material.color.r; mat.color.g = material.color.g; mat.color.b = material.color.b; mat.type = material.type; for (let i = 0; i < this.materials.length; i++) { const m = this.materials[i]; const _mat = {}; _mat.name = m.name; _mat.color = {}; _mat.color.r = m.color.r; _mat.color.g = m.color.g; _mat.color.b = m.color.b; _mat.type = m.type; if (JSON.stringify(mat) === JSON.stringify(_mat)) return m; } this.materials.push(material); return material; } _createMaterial(material) { if (material === void 0) return new MeshStandardMaterial({ color: new Color(1, 1, 1), metalness: .8, name: "default", side: 2 }); const _diffuseColor = material.diffuseColor; const diffusecolor = new Color(_diffuseColor.r / 255, _diffuseColor.g / 255, _diffuseColor.b / 255); if (_diffuseColor.r === 0 && _diffuseColor.g === 0 && _diffuseColor.b === 0) { diffusecolor.r = 1; diffusecolor.g = 1; diffusecolor.b = 1; } const mat = new MeshStandardMaterial({ color: diffusecolor, name: material.name, side: 2, transparent: material.transparency > 0 ? true : false, opacity: 1 - material.transparency }); const textureLoader = new TextureLoader(); for (let i = 0; i < material.textures.length; i++) { const texture = material.textures[i]; if (texture.image !== null) { const map = textureLoader.load(texture.image); switch (texture.type) { case "Diffuse": mat.map = map; break; case "Bump": mat.bumpMap = map; break; case "Transparency": mat.alphaMap = map; mat.transparent = true; break; case "Emap": mat.envMap = map; break; } } } return mat; } _createGeometry(data) { const object = new Object3D(); const instanceDefinitionObjects = []; const instanceDefinitions = []; const instanceReferences = []; object.userData["layers"] = data.layers; object.userData["groups"] = data.groups; object.userData["settings"] = data.settings; object.userData["objectType"] = "File3dm"; object.userData["materials"] = null; object.name = this.url; let objects = data.objects; const materials = data.materials; for (let i = 0; i < objects.length; i++) { const obj = objects[i]; const attributes = obj.attributes; switch (obj.objectType) { case "InstanceDefinition": instanceDefinitions.push(obj); break; case "InstanceReference": instanceReferences.push(obj); break; default: let _object; if (attributes.materialIndex >= 0) { const rMaterial = materials[attributes.materialIndex]; let material = this._createMaterial(rMaterial); material = this._compareMaterials(material); _object = this._createObject(obj, material); } else { const material = this._createMaterial(); _object = this._createObject(obj, material); } if (_object === void 0) continue; const layer = data.layers[attributes.layerIndex]; _object.visible = layer ? data.layers[attributes.layerIndex].visible : true; if (attributes.isInstanceDefinitionObject) instanceDefinitionObjects.push(_object); else object.add(_object); break; } } for (let i = 0; i < instanceDefinitions.length; i++) { const iDef = instanceDefinitions[i]; objects = []; for (let j = 0; j < iDef.attributes.objectIds.length; j++) { const objId = iDef.attributes.objectIds[j]; for (let p = 0; p < instanceDefinitionObjects.length; p++) if (objId === instanceDefinitionObjects[p].userData.attributes.id) objects.push(instanceDefinitionObjects[p]); } for (let j = 0; j < instanceReferences.length; j++) { const iRef = instanceReferences[j]; if (iRef.geometry.parentIdefId === iDef.attributes.id) { const iRefObject = new Object3D(); const xf = iRef.geometry.xform.array; const matrix = new Matrix4(); matrix.set(xf[0], xf[1], xf[2], xf[3], xf[4], xf[5], xf[6], xf[7], xf[8], xf[9], xf[10], xf[11], xf[12], xf[13], xf[14], xf[15]); iRefObject.applyMatrix4(matrix); for (let p = 0; p < objects.length; p++) iRefObject.add(objects[p].clone(true)); object.add(iRefObject); } } } object.userData["materials"] = this.materials; return object; } _createObject(obj, mat) { const loader = new BufferGeometryLoader(); const attributes = obj.attributes; let geometry, material, _color, color; switch (obj.objectType) { case "Point": case "PointSet": geometry = loader.parse(obj.geometry); if (geometry.attributes.hasOwnProperty("color")) material = new PointsMaterial({ vertexColors: true, sizeAttenuation: false, size: 2 }); else { _color = attributes.drawColor; color = new Color(_color.r / 255, _color.g / 255, _color.b / 255); material = new PointsMaterial({ color, sizeAttenuation: false, size: 2 }); } material = this._compareMaterials(material); const points = new Points(geometry, material); points.userData["attributes"] = attributes; points.userData["objectType"] = obj.objectType; if (attributes.name) points.name = attributes.name; return points; case "Mesh": case "Extrusion": case "SubD": case "Brep": if (obj.geometry === null) return; geometry = loader.parse(obj.geometry); if (geometry.attributes.hasOwnProperty("color")) mat.vertexColors = true; if (mat === null) { mat = this._createMaterial(); mat = this._compareMaterials(mat); } const mesh = new Mesh(geometry, mat); mesh.castShadow = attributes.castsShadows; mesh.receiveShadow = attributes.receivesShadows; mesh.userData["attributes"] = attributes; mesh.userData["objectType"] = obj.objectType; if (attributes.name) mesh.name = attributes.name; return mesh; case "Curve": geometry = loader.parse(obj.geometry); _color = attributes.drawColor; color = new Color(_color.r / 255, _color.g / 255, _color.b / 255); material = new LineBasicMaterial({ color }); material = this._compareMaterials(material); const lines = new Line(geometry, material); lines.userData["attributes"] = attributes; lines.userData["objectType"] = obj.objectType; if (attributes.name) lines.name = attributes.name; return lines; case "TextDot": geometry = obj.geometry; const ctx = document.createElement("canvas").getContext("2d"); const font = `${geometry.fontHeight}px ${geometry.fontFace}`; ctx.font = font; const width = ctx.measureText(geometry.text).width + 10; const height = geometry.fontHeight + 10; const r = window.devicePixelRatio; ctx.canvas.width = width * r; ctx.canvas.height = height * r; ctx.canvas.style.width = width + "px"; ctx.canvas.style.height = height + "px"; ctx.setTransform(r, 0, 0, r, 0, 0); ctx.font = font; ctx.textBaseline = "middle"; ctx.textAlign = "center"; color = attributes.drawColor; ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "white"; ctx.fillText(geometry.text, width / 2, height / 2); const texture = new CanvasTexture(ctx.canvas); texture.minFilter = LinearFilter; texture.wrapS = ClampToEdgeWrapping; texture.wrapT = ClampToEdgeWrapping; material = new SpriteMaterial({ map: texture, depthTest: false }); const sprite = new Sprite(material); sprite.position.set(geometry.point[0], geometry.point[1], geometry.point[2]); sprite.scale.set(width / 10, height / 10, 1); sprite.userData["attributes"] = attributes; sprite.userData["objectType"] = obj.objectType; if (attributes.name) sprite.name = attributes.name; return sprite; case "Light": geometry = obj.geometry; let light; if (geometry.isDirectionalLight) { light = new DirectionalLight(); light.castShadow = attributes.castsShadows; light.position.set(geometry.location[0], geometry.location[1], geometry.location[2]); light.target.position.set(geometry.direction[0], geometry.direction[1], geometry.direction[2]); light.shadow.normalBias = .1; } else if (geometry.isPointLight) { light = new PointLight(); light.castShadow = attributes.castsShadows; light.position.set(geometry.location[0], geometry.location[1], geometry.location[2]); light.shadow.normalBias = .1; } else if (geometry.isRectangularLight) { light = new RectAreaLight(); const width2 = Math.abs(geometry.width[2]); const height2 = Math.abs(geometry.length[0]); light.position.set(geometry.location[0] - height2 / 2, geometry.location[1], geometry.location[2] - width2 / 2); light.height = height2; light.width = width2; light.lookAt(new Vector3(geometry.direction[0], geometry.direction[1], geometry.direction[2])); } else if (geometry.isSpotLight) { light = new SpotLight(); light.castShadow = attributes.castsShadows; light.position.set(geometry.location[0], geometry.location[1], geometry.location[2]); light.target.position.set(geometry.direction[0], geometry.direction[1], geometry.direction[2]); light.angle = geometry.spotAngleRadians; light.shadow.normalBias = .1; } else if (geometry.isLinearLight) { console.warn("THREE.3DMLoader: No conversion exists for linear lights."); return; } if (light) { light.intensity = geometry.intensity; _color = geometry.diffuse; color = new Color(_color.r / 255, _color.g / 255, _color.b / 255); light.color = color; light.userData["attributes"] = attributes; light.userData["objectType"] = obj.objectType; } return light; } } _initLibrary() { if (!this.libraryPending) { const jsLoader = new FileLoader(this.manager); jsLoader.setPath(this.libraryPath); const jsContent = new Promise((resolve, reject) => { jsLoader.load("rhino3dm.js", resolve, void 0, reject); }); const binaryLoader = new FileLoader(this.manager); binaryLoader.setPath(this.libraryPath); binaryLoader.setResponseType("arraybuffer"); const binaryContent = new Promise((resolve, reject) => { binaryLoader.load("rhino3dm.wasm", resolve, void 0, reject); }); this.libraryPending = Promise.all([jsContent, binaryContent]).then(([jsContent2, binaryContent2]) => { this.libraryConfig.wasmBinary = binaryContent2; const fn = Rhino3dmWorker.toString(); const body = [ "/* rhino3dm.js */", jsContent2, "/* worker */", fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}")) ].join("\n"); this.workerSourceURL = URL.createObjectURL(new Blob([body])); }); } return this.libraryPending; } _getWorker(taskCost) { return this._initLibrary().then(() => { if (this.workerPool.length < this.workerLimit) { const worker2 = new Worker(this.workerSourceURL); worker2._callbacks = {}; worker2._taskCosts = {}; worker2._taskLoad = 0; worker2.postMessage({ type: "init", libraryConfig: this.libraryConfig }); worker2.onmessage = function(e) { const message = e.data; switch (message.type) { case "decode": worker2._callbacks[message.id].resolve(message); break; case "error": worker2._callbacks[message.id].reject(message); break; default: console.error("THREE.Rhino3dmLoader: Unexpected message, \"" + message.type + "\""); } }; this.workerPool.push(worker2); } else this.workerPool.sort(function(a, b) { return a._taskLoad > b._taskLoad ? -1 : 1; }); const worker = this.workerPool[this.workerPool.length - 1]; worker._taskLoad += taskCost; return worker; }); } _releaseTask(worker, taskID) { worker._taskLoad -= worker._taskCosts[taskID]; delete worker._callbacks[taskID]; delete worker._taskCosts[taskID]; } dispose() { for (let i = 0; i < this.workerPool.length; ++i) this.workerPool[i].terminate(); this.workerPool.length = 0; return this; } }; function Rhino3dmWorker() { let libraryPending; let libraryConfig; let rhino; onmessage = function(e) { const message = e.data; switch (message.type) { case "init": libraryConfig = message.libraryConfig; const wasmBinary = libraryConfig.wasmBinary; let RhinoModule; libraryPending = new Promise(function(resolve) { RhinoModule = { wasmBinary, onRuntimeInitialized: resolve }; rhino3dm(RhinoModule); }).then(() => { rhino = RhinoModule; }); break; case "decode": const buffer = message.buffer; libraryPending.then(() => { const data = decodeObjects(rhino, buffer); self.postMessage({ type: "decode", id: message.id, data }); }); break; } }; function decodeObjects(rhino2, buffer) { const arr = new Uint8Array(buffer); const doc = rhino2.File3dm.fromByteArray(arr); const objects = []; const materials = []; const layers = []; const views = []; const namedViews = []; const groups = []; const objs = doc.objects(); const cnt = objs.count; for (let i = 0; i < cnt; i++) { const _object = objs.get(i); const object = extractObjectData(_object, doc); _object.delete(); if (object) objects.push(object); } for (let i = 0; i < doc.instanceDefinitions().count(); i++) { const idef = doc.instanceDefinitions().get(i); const idefAttributes = extractProperties(idef); idefAttributes.objectIds = idef.getObjectIds(); objects.push({ geometry: null, attributes: idefAttributes, objectType: "InstanceDefinition" }); } const textureTypes = [ rhino2.TextureType.Diffuse, rhino2.TextureType.Bump, rhino2.TextureType.Transparency, rhino2.TextureType.Opacity, rhino2.TextureType.Emap ]; const pbrTextureTypes = [ rhino2.TextureType.PBR_BaseColor, rhino2.TextureType.PBR_Subsurface, rhino2.TextureType.PBR_SubsurfaceScattering, rhino2.TextureType.PBR_SubsurfaceScatteringRadius, rhino2.TextureType.PBR_Metallic, rhino2.TextureType.PBR_Specular, rhino2.TextureType.PBR_SpecularTint, rhino2.TextureType.PBR_Roughness, rhino2.TextureType.PBR_Anisotropic, rhino2.TextureType.PBR_Anisotropic_Rotation, rhino2.TextureType.PBR_Sheen, rhino2.TextureType.PBR_SheenTint, rhino2.TextureType.PBR_Clearcoat, rhino2.TextureType.PBR_ClearcoatBump, rhino2.TextureType.PBR_ClearcoatRoughness, rhino2.TextureType.PBR_OpacityIor, rhino2.TextureType.PBR_OpacityRoughness, rhino2.TextureType.PBR_Emission, rhino2.TextureType.PBR_AmbientOcclusion, rhino2.TextureType.PBR_Displacement ]; for (let i = 0; i < doc.materials().count(); i++) { const _material = doc.materials().get(i); const _pbrMaterial = _material.physicallyBased(); let material = extractProperties(_material); const textures = []; for (let j = 0; j < textureTypes.length; j++) { const _texture = _material.getTexture(textureTypes[j]); if (_texture) { let textureType = textureTypes[j].constructor.name; textureType = textureType.substring(12, textureType.length); const texture = { type: textureType }; const image = doc.getEmbeddedFileAsBase64(_texture.fileName); if (image) texture.image = "data:image/png;base64," + image; else { console.warn(`THREE.3DMLoader: Image for ${textureType} texture not embedded in file.`); texture.image = null; } textures.push(texture); _texture.delete(); } } material.textures = textures; if (_pbrMaterial.supported) { console.log("pbr true"); for (let j = 0; j < pbrTextureTypes.length; j++) { const _texture = _material.getTexture(textureTypes[j]); if (_texture) { const image = doc.getEmbeddedFileAsBase64(_texture.fileName); let textureType = textureTypes[j].constructor.name; textureType = textureType.substring(12, textureType.length); const texture = { type: textureType, image: "data:image/png;base64," + image }; textures.push(texture); _texture.delete(); } } const pbMaterialProperties = extractProperties(_material.physicallyBased()); material = Object.assign(pbMaterialProperties, material); } materials.push(material); _material.delete(); _pbrMaterial.delete(); } for (let i = 0; i < doc.layers().count(); i++) { const _layer = doc.layers().get(i); const layer = extractProperties(_layer); layers.push(layer); _layer.delete(); } for (let i = 0; i < doc.views().count(); i++) { const _view = doc.views().get(i); const view = extractProperties(_view); views.push(view); _view.delete(); } for (let i = 0; i < doc.namedViews().count(); i++) { const _namedView = doc.namedViews().get(i); const namedView = extractProperties(_namedView); namedViews.push(namedView); _namedView.delete(); } for (let i = 0; i < doc.groups().count(); i++) { const _group = doc.groups().get(i); const group = extractProperties(_group); groups.push(group); _group.delete(); } const settings = extractProperties(doc.settings()); doc.delete(); return { objects, materials, layers, views, namedViews, groups, settings }; } function extractObjectData(object, doc) { const _geometry = object.geometry(); const _attributes = object.attributes(); let objectType = _geometry.objectType; let geometry, attributes, position, data, mesh; switch (objectType) { case rhino.ObjectType.Curve: const pts = curveToPoints(_geometry, 100); position = {}; attributes = {}; data = {}; position.itemSize = 3; position.type = "Float32Array"; position.array = []; for (let j = 0; j < pts.length; j++) { position.array.push(pts[j][0]); position.array.push(pts[j][1]); position.array.push(pts[j][2]); } attributes.position = position; data.attributes = attributes; geometry = { data }; break; case rhino.ObjectType.Point: const pt = _geometry.location; position = {}; const color = {}; attributes = {}; data = {}; position.itemSize = 3; position.type = "Float32Array"; position.array = [ pt[0], pt[1], pt[2] ]; const _color = _attributes.drawColor(doc); color.itemSize = 3; color.type = "Float32Array"; color.array = [ _color.r / 255, _color.g / 255, _color.b / 255 ]; attributes.position = position; attributes.color = color; data.attributes = attributes; geometry = { data }; break; case rhino.ObjectType.PointSet: case rhino.ObjectType.Mesh: geometry = _geometry.toThreejsJSON(); break; case rhino.ObjectType.Brep: const faces = _geometry.faces(); mesh = new rhino.Mesh(); for (let faceIndex = 0; faceIndex < faces.count; faceIndex++) { const face = faces.get(faceIndex); const _mesh = face.getMesh(rhino.MeshType.Any); if (_mesh) { mesh.append(_mesh); _mesh.delete(); } face.delete(); } if (mesh.faces().count > 0) { mesh.compact(); geometry = mesh.toThreejsJSON(); faces.delete(); } mesh.delete(); break; case rhino.ObjectType.Extrusion: mesh = _geometry.getMesh(rhino.MeshType.Any); if (mesh) { geometry = mesh.toThreejsJSON(); mesh.delete(); } break; case rhino.ObjectType.TextDot: geometry = extractProperties(_geometry); break; case rhino.ObjectType.Light: geometry = extractProperties(_geometry); break; case rhino.ObjectType.InstanceReference: geometry = extractProperties(_geometry); geometry.xform = extractProperties(_geometry.xform); geometry.xform.array = _geometry.xform.toFloatArray(true); break; case rhino.ObjectType.SubD: _geometry.subdivide(3); mesh = rhino.Mesh.createFromSubDControlNet(_geometry); if (mesh) { geometry = mesh.toThreejsJSON(); mesh.delete(); } break; default: console.warn(`THREE.3DMLoader: TODO: Implement ${objectType.constructor.name}`); break; } if (geometry) { attributes = extractProperties(_attributes); attributes.geometry = extractProperties(_geometry); if (_attributes.groupCount > 0) attributes.groupIds = _attributes.getGroupList(); if (_attributes.userStringCount > 0) attributes.userStrings = _attributes.getUserStrings(); if (_geometry.userStringCount > 0) attributes.geometry.userStrings = _geometry.getUserStrings(); attributes.drawColor = _attributes.drawColor(doc); objectType = objectType.constructor.name; objectType = objectType.substring(11, objectType.length); return { geometry, attributes, objectType }; } else console.warn(`THREE.3DMLoader: ${objectType.constructor.name} has no associated mesh geometry.`); } function extractProperties(object) { const result = {}; for (const property in object) { const value = object[property]; if (typeof value !== "function") if (typeof value === "object" && value !== null && value.hasOwnProperty("constructor")) result[property] = { name: value.constructor.name, value: value.value }; else result[property] = value; } return result; } function curveToPoints(curve, pointLimit) { let pointCount = pointLimit; let rc = []; const ts = []; if (curve instanceof rhino.LineCurve) return [curve.pointAtStart, curve.pointAtEnd]; if (curve instanceof rhino.PolylineCurve) { pointCount = curve.pointCount; for (let i = 0; i < pointCount; i++) rc.push(curve.point(i)); return rc; } if (curve instanceof rhino.PolyCurve) { const segmentCount = curve.segmentCount; for (let i = 0; i < segmentCount; i++) { const segment = curve.segmentCurve(i); const segmentArray = curveToPoints(segment, pointCount); rc = rc.concat(segmentArray); segment.delete(); } return rc; } if (curve instanceof rhino.ArcCurve) { pointCount = Math.floor(curve.angleDegrees / 5); pointCount = pointCount < 2 ? 2 : pointCount; } if (curve instanceof rhino.NurbsCurve && curve.degree === 1) { const pLine = curve.tryGetPolyline(); for (let i = 0; i < pLine.count; i++) rc.push(pLine.get(i)); pLine.delete(); return rc; } const domain = curve.domain; const divisions = pointCount - 1; for (let j = 0; j < pointCount; j++) { const t = domain[0] + j / divisions * (domain[1] - domain[0]); if (t === domain[0] || t === domain[1]) { ts.push(t); continue; } const tan = curve.tangentAt(t); const prevTan = curve.tangentAt(ts.slice(-1)[0]); const tS = tan[0] * tan[0] + tan[1] * tan[1] + tan[2] * tan[2]; const ptS = prevTan[0] * prevTan[0] + prevTan[1] * prevTan[1] + prevTan[2] * prevTan[2]; const denominator = Math.sqrt(tS * ptS); let angle; if (denominator === 0) angle = Math.PI / 2; else { const theta = (tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z) / denominator; angle = Math.acos(Math.max(-1, Math.min(1, theta))); } if (angle < .1) continue; ts.push(t); } rc = ts.map((t) => curve.pointAt(t)); return rc; } } //#endregion //#region node_modules/three-stdlib/loaders/OBJLoader.js var _object_pattern = /^[og]\s*(.+)?/; var _material_library_pattern = /^mtllib /; var _material_use_pattern = /^usemtl /; var _map_use_pattern = /^usemap /; var _vA = /* @__PURE__ */ new Vector3(); var _vB = /* @__PURE__ */ new Vector3(); var _vC = /* @__PURE__ */ new Vector3(); var _ab = /* @__PURE__ */ new Vector3(); var _cb = /* @__PURE__ */ new Vector3(); function ParserState() { const state = { objects: [], object: {}, vertices: [], normals: [], colors: [], uvs: [], materials: {}, materialLibraries: [], startObject: function(name, fromDeclaration) { if (this.object && this.object.fromDeclaration === false) { this.object.name = name; this.object.fromDeclaration = fromDeclaration !== false; return; } const previousMaterial = this.object && typeof this.object.currentMaterial === "function" ? this.object.currentMaterial() : void 0; if (this.object && typeof this.object._finalize === "function") this.object._finalize(true); this.object = { name: name || "", fromDeclaration: fromDeclaration !== false, geometry: { vertices: [], normals: [], colors: [], uvs: [], hasUVIndices: false }, materials: [], smooth: true, startMaterial: function(name2, libraries) { const previous = this._finalize(false); if (previous && (previous.inherited || previous.groupCount <= 0)) this.materials.splice(previous.index, 1); const material = { index: this.materials.length, name: name2 || "", mtllib: Array.isArray(libraries) && libraries.length > 0 ? libraries[libraries.length - 1] : "", smooth: previous !== void 0 ? previous.smooth : this.smooth, groupStart: previous !== void 0 ? previous.groupEnd : 0, groupEnd: -1, groupCount: -1, inherited: false, clone: function(index) { const cloned = { index: typeof index === "number" ? index : this.index, name: this.name, mtllib: this.mtllib, smooth: this.smooth, groupStart: 0, groupEnd: -1, groupCount: -1, inherited: false }; cloned.clone = this.clone.bind(cloned); return cloned; } }; this.materials.push(material); return material; }, currentMaterial: function() { if (this.materials.length > 0) return this.materials[this.materials.length - 1]; }, _finalize: function(end) { const lastMultiMaterial = this.currentMaterial(); if (lastMultiMaterial && lastMultiMaterial.groupEnd === -1) { lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3; lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart; lastMultiMaterial.inherited = false; } if (end && this.materials.length > 1) { for (let mi = this.materials.length - 1; mi >= 0; mi--) if (this.materials[mi].groupCount <= 0) this.materials.splice(mi, 1); } if (end && this.materials.length === 0) this.materials.push({ name: "", smooth: this.smooth }); return lastMultiMaterial; } }; if (previousMaterial && previousMaterial.name && typeof previousMaterial.clone === "function") { const declared = previousMaterial.clone(0); declared.inherited = true; this.object.materials.push(declared); } this.objects.push(this.object); }, finalize: function() { if (this.object && typeof this.object._finalize === "function") this.object._finalize(true); }, parseVertexIndex: function(value, len) { const index = parseInt(value, 10); return (index >= 0 ? index - 1 : index + len / 3) * 3; }, parseNormalIndex: function(value, len) { const index = parseInt(value, 10); return (index >= 0 ? index - 1 : index + len / 3) * 3; }, parseUVIndex: function(value, len) { const index = parseInt(value, 10); return (index >= 0 ? index - 1 : index + len / 2) * 2; }, addVertex: function(a, b, c) { const src = this.vertices; const dst = this.object.geometry.vertices; dst.push(src[a + 0], src[a + 1], src[a + 2]); dst.push(src[b + 0], src[b + 1], src[b + 2]); dst.push(src[c + 0], src[c + 1], src[c + 2]); }, addVertexPoint: function(a) { const src = this.vertices; this.object.geometry.vertices.push(src[a + 0], src[a + 1], src[a + 2]); }, addVertexLine: function(a) { const src = this.vertices; this.object.geometry.vertices.push(src[a + 0], src[a + 1], src[a + 2]); }, addNormal: function(a, b, c) { const src = this.normals; const dst = this.object.geometry.normals; dst.push(src[a + 0], src[a + 1], src[a + 2]); dst.push(src[b + 0], src[b + 1], src[b + 2]); dst.push(src[c + 0], src[c + 1], src[c + 2]); }, addFaceNormal: function(a, b, c) { const src = this.vertices; const dst = this.object.geometry.normals; _vA.fromArray(src, a); _vB.fromArray(src, b); _vC.fromArray(src, c); _cb.subVectors(_vC, _vB); _ab.subVectors(_vA, _vB); _cb.cross(_ab); _cb.normalize(); dst.push(_cb.x, _cb.y, _cb.z); dst.push(_cb.x, _cb.y, _cb.z); dst.push(_cb.x, _cb.y, _cb.z); }, addColor: function(a, b, c) { const src = this.colors; const dst = this.object.geometry.colors; if (src[a] !== void 0) dst.push(src[a + 0], src[a + 1], src[a + 2]); if (src[b] !== void 0) dst.push(src[b + 0], src[b + 1], src[b + 2]); if (src[c] !== void 0) dst.push(src[c + 0], src[c + 1], src[c + 2]); }, addUV: function(a, b, c) { const src = this.uvs; const dst = this.object.geometry.uvs; dst.push(src[a + 0], src[a + 1]); dst.push(src[b + 0], src[b + 1]); dst.push(src[c + 0], src[c + 1]); }, addDefaultUV: function() { const dst = this.object.geometry.uvs; dst.push(0, 0); dst.push(0, 0); dst.push(0, 0); }, addUVLine: function(a) { const src = this.uvs; this.object.geometry.uvs.push(src[a + 0], src[a + 1]); }, addFace: function(a, b, c, ua, ub, uc, na, nb, nc) { const vLen = this.vertices.length; let ia = this.parseVertexIndex(a, vLen); let ib = this.parseVertexIndex(b, vLen); let ic = this.parseVertexIndex(c, vLen); this.addVertex(ia, ib, ic); this.addColor(ia, ib, ic); if (na !== void 0 && na !== "") { const nLen = this.normals.length; ia = this.parseNormalIndex(na, nLen); ib = this.parseNormalIndex(nb, nLen); ic = this.parseNormalIndex(nc, nLen); this.addNormal(ia, ib, ic); } else this.addFaceNormal(ia, ib, ic); if (ua !== void 0 && ua !== "") { const uvLen = this.uvs.length; ia = this.parseUVIndex(ua, uvLen); ib = this.parseUVIndex(ub, uvLen); ic = this.parseUVIndex(uc, uvLen); this.addUV(ia, ib, ic); this.object.geometry.hasUVIndices = true; } else this.addDefaultUV(); }, addPointGeometry: function(vertices) { this.object.geometry.type = "Points"; const vLen = this.vertices.length; for (let vi = 0, l = vertices.length; vi < l; vi++) { const index = this.parseVertexIndex(vertices[vi], vLen); this.addVertexPoint(index); this.addColor(index); } }, addLineGeometry: function(vertices, uvs) { this.object.geometry.type = "Line"; const vLen = this.vertices.length; const uvLen = this.uvs.length; for (let vi = 0, l = vertices.length; vi < l; vi++) this.addVertexLine(this.parseVertexIndex(vertices[vi], vLen)); for (let uvi = 0, l = uvs.length; uvi < l; uvi++) this.addUVLine(this.parseUVIndex(uvs[uvi], uvLen)); } }; state.startObject("", false); return state; } var OBJLoader = class extends Loader { constructor(manager) { super(manager); this.materials = null; } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } setMaterials(materials) { this.materials = materials; return this; } parse(text) { const state = new ParserState(); if (text.indexOf("\r\n") !== -1) text = text.replace(/\r\n/g, "\n"); if (text.indexOf("\\\n") !== -1) text = text.replace(/\\\n/g, ""); const lines = text.split("\n"); let line = "", lineFirstChar = ""; let lineLength = 0; let result = []; const trimLeft = typeof "".trimLeft === "function"; for (let i = 0, l = lines.length; i < l; i++) { line = lines[i]; line = trimLeft ? line.trimLeft() : line.trim(); lineLength = line.length; if (lineLength === 0) continue; lineFirstChar = line.charAt(0); if (lineFirstChar === "#") continue; if (lineFirstChar === "v") { const data = line.split(/\s+/); switch (data[0]) { case "v": state.vertices.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3])); if (data.length >= 7) state.colors.push(parseFloat(data[4]), parseFloat(data[5]), parseFloat(data[6])); else state.colors.push(void 0, void 0, void 0); break; case "vn": state.normals.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3])); break; case "vt": state.uvs.push(parseFloat(data[1]), parseFloat(data[2])); break; } } else if (lineFirstChar === "f") { const vertexData = line.substr(1).trim().split(/\s+/); const faceVertices = []; for (let j = 0, jl = vertexData.length; j < jl; j++) { const vertex = vertexData[j]; if (vertex.length > 0) { const vertexParts = vertex.split("/"); faceVertices.push(vertexParts); } } const v1 = faceVertices[0]; for (let j = 1, jl = faceVertices.length - 1; j < jl; j++) { const v2 = faceVertices[j]; const v3 = faceVertices[j + 1]; state.addFace(v1[0], v2[0], v3[0], v1[1], v2[1], v3[1], v1[2], v2[2], v3[2]); } } else if (lineFirstChar === "l") { const lineParts = line.substring(1).trim().split(" "); let lineVertices = []; const lineUVs = []; if (line.indexOf("/") === -1) lineVertices = lineParts; else for (let li = 0, llen = lineParts.length; li < llen; li++) { const parts = lineParts[li].split("/"); if (parts[0] !== "") lineVertices.push(parts[0]); if (parts[1] !== "") lineUVs.push(parts[1]); } state.addLineGeometry(lineVertices, lineUVs); } else if (lineFirstChar === "p") { const pointData = line.substr(1).trim().split(" "); state.addPointGeometry(pointData); } else if ((result = _object_pattern.exec(line)) !== null) { const name = (" " + result[0].substr(1).trim()).substr(1); state.startObject(name); } else if (_material_use_pattern.test(line)) state.object.startMaterial(line.substring(7).trim(), state.materialLibraries); else if (_material_library_pattern.test(line)) state.materialLibraries.push(line.substring(7).trim()); else if (_map_use_pattern.test(line)) console.warn("THREE.OBJLoader: Rendering identifier \"usemap\" not supported. Textures must be defined in MTL files."); else if (lineFirstChar === "s") { result = line.split(" "); if (result.length > 1) { const value = result[1].trim().toLowerCase(); state.object.smooth = value !== "0" && value !== "off"; } else state.object.smooth = true; const material = state.object.currentMaterial(); if (material) material.smooth = state.object.smooth; } else { if (line === "\0") continue; console.warn("THREE.OBJLoader: Unexpected line: \"" + line + "\""); } } state.finalize(); const container = new Group(); container.materialLibraries = [].concat(state.materialLibraries); if (!(state.objects.length === 1 && state.objects[0].geometry.vertices.length === 0) === true) for (let i = 0, l = state.objects.length; i < l; i++) { const object = state.objects[i]; const geometry = object.geometry; const materials = object.materials; const isLine = geometry.type === "Line"; const isPoints = geometry.type === "Points"; let hasVertexColors = false; if (geometry.vertices.length === 0) continue; const buffergeometry = new BufferGeometry(); buffergeometry.setAttribute("position", new Float32BufferAttribute(geometry.vertices, 3)); if (geometry.normals.length > 0) buffergeometry.setAttribute("normal", new Float32BufferAttribute(geometry.normals, 3)); if (geometry.colors.length > 0) { hasVertexColors = true; buffergeometry.setAttribute("color", new Float32BufferAttribute(geometry.colors, 3)); } if (geometry.hasUVIndices === true) buffergeometry.setAttribute("uv", new Float32BufferAttribute(geometry.uvs, 2)); const createdMaterials = []; for (let mi = 0, miLen = materials.length; mi < miLen; mi++) { const sourceMaterial = materials[mi]; const materialHash = sourceMaterial.name + "_" + sourceMaterial.smooth + "_" + hasVertexColors; let material = state.materials[materialHash]; if (this.materials !== null) { material = this.materials.create(sourceMaterial.name); if (isLine && material && !(material instanceof LineBasicMaterial)) { const materialLine = new LineBasicMaterial(); Material.prototype.copy.call(materialLine, material); materialLine.color.copy(material.color); material = materialLine; } else if (isPoints && material && !(material instanceof PointsMaterial)) { const materialPoints = new PointsMaterial({ size: 10, sizeAttenuation: false }); Material.prototype.copy.call(materialPoints, material); materialPoints.color.copy(material.color); materialPoints.map = material.map; material = materialPoints; } } if (material === void 0) { if (isLine) material = new LineBasicMaterial(); else if (isPoints) material = new PointsMaterial({ size: 1, sizeAttenuation: false }); else material = new MeshPhongMaterial(); material.name = sourceMaterial.name; material.flatShading = sourceMaterial.smooth ? false : true; material.vertexColors = hasVertexColors; state.materials[materialHash] = material; } createdMaterials.push(material); } let mesh; if (createdMaterials.length > 1) { for (let mi = 0, miLen = materials.length; mi < miLen; mi++) { const sourceMaterial = materials[mi]; buffergeometry.addGroup(sourceMaterial.groupStart, sourceMaterial.groupCount, mi); } if (isLine) mesh = new LineSegments(buffergeometry, createdMaterials); else if (isPoints) mesh = new Points(buffergeometry, createdMaterials); else mesh = new Mesh(buffergeometry, createdMaterials); } else if (isLine) mesh = new LineSegments(buffergeometry, createdMaterials[0]); else if (isPoints) mesh = new Points(buffergeometry, createdMaterials[0]); else mesh = new Mesh(buffergeometry, createdMaterials[0]); mesh.name = object.name; container.add(mesh); } else if (state.vertices.length > 0) { const material = new PointsMaterial({ size: 1, sizeAttenuation: false }); const buffergeometry = new BufferGeometry(); buffergeometry.setAttribute("position", new Float32BufferAttribute(state.vertices, 3)); if (state.colors.length > 0 && state.colors[0] !== void 0) { buffergeometry.setAttribute("color", new Float32BufferAttribute(state.colors, 3)); material.vertexColors = true; } const points = new Points(buffergeometry, material); container.add(points); } return container; } }; //#endregion //#region node_modules/three-stdlib/loaders/AMFLoader.js var AMFLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(data) { function loadDocument(data2) { let view = new DataView(data2); if (String.fromCharCode(view.getUint8(0), view.getUint8(1)) === "PK") { let zip = null; let file = null; console.log("THREE.AMFLoader: Loading Zip"); try { zip = unzipSync(new Uint8Array(data2)); } catch (e) { if (e instanceof ReferenceError) { console.log("THREE.AMFLoader: fflate missing and file is compressed."); return null; } } for (file in zip) if (file.toLowerCase().substr(-4) === ".amf") break; console.log("THREE.AMFLoader: Trying to load file asset: " + file); view = new DataView(zip[file].buffer); } const fileText = decodeText$1(view); const xmlData2 = new DOMParser().parseFromString(fileText, "application/xml"); if (xmlData2.documentElement.nodeName.toLowerCase() !== "amf") { console.log("THREE.AMFLoader: Error loading AMF - no AMF document found."); return null; } return xmlData2; } function loadDocumentScale(node) { let scale = 1; let unit = "millimeter"; if (node.documentElement.attributes.unit !== void 0) unit = node.documentElement.attributes.unit.value.toLowerCase(); const scaleUnits = { millimeter: 1, inch: 25.4, feet: 304.8, meter: 1e3, micron: .001 }; if (scaleUnits[unit] !== void 0) scale = scaleUnits[unit]; console.log("THREE.AMFLoader: Unit scale: " + scale); return scale; } function loadMaterials(node) { let matName = "AMF Material"; const matId = node.attributes.id.textContent; let color = { r: 1, g: 1, b: 1, a: 1 }; let loadedMaterial = null; for (let i2 = 0; i2 < node.childNodes.length; i2++) { const matChildEl = node.childNodes[i2]; if (matChildEl.nodeName === "metadata" && matChildEl.attributes.type !== void 0) { if (matChildEl.attributes.type.value === "name") matName = matChildEl.textContent; } else if (matChildEl.nodeName === "color") color = loadColor(matChildEl); } loadedMaterial = new MeshPhongMaterial({ flatShading: true, color: new Color(color.r, color.g, color.b), name: matName }); if (color.a !== 1) { loadedMaterial.transparent = true; loadedMaterial.opacity = color.a; } return { id: matId, material: loadedMaterial }; } function loadColor(node) { const color = { r: 1, g: 1, b: 1, a: 1 }; for (let i2 = 0; i2 < node.childNodes.length; i2++) { const matColor = node.childNodes[i2]; if (matColor.nodeName === "r") color.r = matColor.textContent; else if (matColor.nodeName === "g") color.g = matColor.textContent; else if (matColor.nodeName === "b") color.b = matColor.textContent; else if (matColor.nodeName === "a") color.a = matColor.textContent; } return color; } function loadMeshVolume(node) { const volume = { name: "", triangles: [], materialid: null }; let currVolumeNode = node.firstElementChild; if (node.attributes.materialid !== void 0) volume.materialId = node.attributes.materialid.nodeValue; while (currVolumeNode) { if (currVolumeNode.nodeName === "metadata") { if (currVolumeNode.attributes.type !== void 0) { if (currVolumeNode.attributes.type.value === "name") volume.name = currVolumeNode.textContent; } } else if (currVolumeNode.nodeName === "triangle") { const v1 = currVolumeNode.getElementsByTagName("v1")[0].textContent; const v2 = currVolumeNode.getElementsByTagName("v2")[0].textContent; const v3 = currVolumeNode.getElementsByTagName("v3")[0].textContent; volume.triangles.push(v1, v2, v3); } currVolumeNode = currVolumeNode.nextElementSibling; } return volume; } function loadMeshVertices(node) { const vertArray = []; const normalArray = []; let currVerticesNode = node.firstElementChild; while (currVerticesNode) { if (currVerticesNode.nodeName === "vertex") { let vNode = currVerticesNode.firstElementChild; while (vNode) { if (vNode.nodeName === "coordinates") { const x = vNode.getElementsByTagName("x")[0].textContent; const y = vNode.getElementsByTagName("y")[0].textContent; const z = vNode.getElementsByTagName("z")[0].textContent; vertArray.push(x, y, z); } else if (vNode.nodeName === "normal") { const nx = vNode.getElementsByTagName("nx")[0].textContent; const ny = vNode.getElementsByTagName("ny")[0].textContent; const nz = vNode.getElementsByTagName("nz")[0].textContent; normalArray.push(nx, ny, nz); } vNode = vNode.nextElementSibling; } } currVerticesNode = currVerticesNode.nextElementSibling; } return { vertices: vertArray, normals: normalArray }; } function loadObject(node) { const objId = node.attributes.id.textContent; const loadedObject = { name: "amfobject", meshes: [] }; let currColor = null; let currObjNode = node.firstElementChild; while (currObjNode) { if (currObjNode.nodeName === "metadata") { if (currObjNode.attributes.type !== void 0) { if (currObjNode.attributes.type.value === "name") loadedObject.name = currObjNode.textContent; } } else if (currObjNode.nodeName === "color") currColor = loadColor(currObjNode); else if (currObjNode.nodeName === "mesh") { let currMeshNode = currObjNode.firstElementChild; const mesh = { vertices: [], normals: [], volumes: [], color: currColor }; while (currMeshNode) { if (currMeshNode.nodeName === "vertices") { const loadedVertices = loadMeshVertices(currMeshNode); mesh.normals = mesh.normals.concat(loadedVertices.normals); mesh.vertices = mesh.vertices.concat(loadedVertices.vertices); } else if (currMeshNode.nodeName === "volume") mesh.volumes.push(loadMeshVolume(currMeshNode)); currMeshNode = currMeshNode.nextElementSibling; } loadedObject.meshes.push(mesh); } currObjNode = currObjNode.nextElementSibling; } return { id: objId, obj: loadedObject }; } const xmlData = loadDocument(data); let amfName = ""; let amfAuthor = ""; const amfScale = loadDocumentScale(xmlData); const amfMaterials = {}; const amfObjects = {}; const childNodes = xmlData.documentElement.childNodes; let i, j; for (i = 0; i < childNodes.length; i++) { const child = childNodes[i]; if (child.nodeName === "metadata") { if (child.attributes.type !== void 0) { if (child.attributes.type.value === "name") amfName = child.textContent; else if (child.attributes.type.value === "author") amfAuthor = child.textContent; } } else if (child.nodeName === "material") { const loadedMaterial = loadMaterials(child); amfMaterials[loadedMaterial.id] = loadedMaterial.material; } else if (child.nodeName === "object") { const loadedObject = loadObject(child); amfObjects[loadedObject.id] = loadedObject.obj; } } const sceneObject = new Group(); const defaultMaterial = new MeshPhongMaterial({ color: 11184895, flatShading: true }); sceneObject.name = amfName; sceneObject.userData.author = amfAuthor; sceneObject.userData.loader = "AMF"; for (const id in amfObjects) { const part = amfObjects[id]; const meshes = part.meshes; const newObject = new Group(); newObject.name = part.name || ""; for (i = 0; i < meshes.length; i++) { let objDefaultMaterial = defaultMaterial; const mesh = meshes[i]; const vertices = new Float32BufferAttribute(mesh.vertices, 3); let normals = null; if (mesh.normals.length) normals = new Float32BufferAttribute(mesh.normals, 3); if (mesh.color) { const color = mesh.color; objDefaultMaterial = defaultMaterial.clone(); objDefaultMaterial.color = new Color(color.r, color.g, color.b); if (color.a !== 1) { objDefaultMaterial.transparent = true; objDefaultMaterial.opacity = color.a; } } const volumes = mesh.volumes; for (j = 0; j < volumes.length; j++) { const volume = volumes[j]; const newGeometry = new BufferGeometry(); let material = objDefaultMaterial; newGeometry.setIndex(volume.triangles); newGeometry.setAttribute("position", vertices.clone()); if (normals) newGeometry.setAttribute("normal", normals.clone()); if (amfMaterials[volume.materialId] !== void 0) material = amfMaterials[volume.materialId]; newGeometry.scale(amfScale, amfScale, amfScale); newObject.add(new Mesh(newGeometry, material.clone())); } } sceneObject.add(newObject); } return sceneObject; } }; //#endregion //#region node_modules/three-stdlib/loaders/MMDLoader.js var MMDLoader = class extends Loader { constructor(manager) { super(manager); this.loader = new FileLoader(this.manager); this.parser = null; this.meshBuilder = new MeshBuilder(this.manager); this.animationBuilder = new AnimationBuilder(); } /** * @param {string} animationPath * @return {MMDLoader} */ setAnimationPath(animationPath) { this.animationPath = animationPath; return this; } /** * Loads Model file (.pmd or .pmx) as a SkinnedMesh. * * @param {string} url - url to Model(.pmd or .pmx) file * @param {function} onLoad * @param {function} onProgress * @param {function} onError */ load(url, onLoad, onProgress, onError) { const builder = this.meshBuilder.setCrossOrigin(this.crossOrigin); let resourcePath; if (this.resourcePath !== "") resourcePath = this.resourcePath; else if (this.path !== "") resourcePath = this.path; else resourcePath = LoaderUtils.extractUrlBase(url); const modelExtension = this._extractExtension(url).toLowerCase(); if (modelExtension !== "pmd" && modelExtension !== "pmx") { if (onError) onError(/* @__PURE__ */ new Error("THREE.MMDLoader: Unknown model file extension ." + modelExtension + ".")); return; } this[modelExtension === "pmd" ? "loadPMD" : "loadPMX"](url, function(data) { onLoad(builder.build(data, resourcePath, onProgress, onError)); }, onProgress, onError); } /** * Loads Motion file(s) (.vmd) as a AnimationClip. * If two or more files are specified, they'll be merged. * * @param {string|Array} url - url(s) to animation(.vmd) file(s) * @param {SkinnedMesh|THREE.Camera} object - tracks will be fitting to this object * @param {function} onLoad * @param {function} onProgress * @param {function} onError */ loadAnimation(url, object, onLoad, onProgress, onError) { const builder = this.animationBuilder; this.loadVMD(url, function(vmd) { onLoad(object.isCamera ? builder.buildCameraAnimation(vmd) : builder.build(vmd, object)); }, onProgress, onError); } /** * Loads mode file and motion file(s) as an object containing * a SkinnedMesh and a AnimationClip. * Tracks of AnimationClip are fitting to the model. * * @param {string} modelUrl - url to Model(.pmd or .pmx) file * @param {string|Array{string}} vmdUrl - url(s) to animation(.vmd) file * @param {function} onLoad * @param {function} onProgress * @param {function} onError */ loadWithAnimation(modelUrl, vmdUrl, onLoad, onProgress, onError) { const scope = this; this.load(modelUrl, function(mesh) { scope.loadAnimation(vmdUrl, mesh, function(animation) { onLoad({ mesh, animation }); }, onProgress, onError); }, onProgress, onError); } /** * Loads .pmd file as an Object. * * @param {string} url - url to .pmd file * @param {function} onLoad * @param {function} onProgress * @param {function} onError */ loadPMD(url, onLoad, onProgress, onError) { const parser = this._getParser(); this.loader.setMimeType(void 0).setPath(this.path).setResponseType("arraybuffer").setRequestHeader(this.requestHeader).setWithCredentials(this.withCredentials).load(url, function(buffer) { onLoad(parser.parsePmd(buffer, true)); }, onProgress, onError); } /** * Loads .pmx file as an Object. * * @param {string} url - url to .pmx file * @param {function} onLoad * @param {function} onProgress * @param {function} onError */ loadPMX(url, onLoad, onProgress, onError) { const parser = this._getParser(); this.loader.setMimeType(void 0).setPath(this.path).setResponseType("arraybuffer").setRequestHeader(this.requestHeader).setWithCredentials(this.withCredentials).load(url, function(buffer) { onLoad(parser.parsePmx(buffer, true)); }, onProgress, onError); } /** * Loads .vmd file as an Object. If two or more files are specified * they'll be merged. * * @param {string|Array} url - url(s) to .vmd file(s) * @param {function} onLoad * @param {function} onProgress * @param {function} onError */ loadVMD(url, onLoad, onProgress, onError) { const urls = Array.isArray(url) ? url : [url]; const vmds = []; const vmdNum = urls.length; const parser = this._getParser(); this.loader.setMimeType(void 0).setPath(this.animationPath).setResponseType("arraybuffer").setRequestHeader(this.requestHeader).setWithCredentials(this.withCredentials); for (let i = 0, il = urls.length; i < il; i++) this.loader.load(urls[i], function(buffer) { vmds.push(parser.parseVmd(buffer, true)); if (vmds.length === vmdNum) onLoad(parser.mergeVmds(vmds)); }, onProgress, onError); } /** * Loads .vpd file as an Object. * * @param {string} url - url to .vpd file * @param {boolean} isUnicode * @param {function} onLoad * @param {function} onProgress * @param {function} onError */ loadVPD(url, isUnicode, onLoad, onProgress, onError) { const parser = this._getParser(); this.loader.setMimeType(isUnicode ? void 0 : "text/plain; charset=shift_jis").setPath(this.animationPath).setResponseType("text").setRequestHeader(this.requestHeader).setWithCredentials(this.withCredentials).load(url, function(text) { onLoad(parser.parseVpd(text, true)); }, onProgress, onError); } _extractExtension(url) { const index = url.lastIndexOf("."); return index < 0 ? "" : url.slice(index + 1); } _getParser() { if (this.parser === null) this.parser = new Parser(); return this.parser; } }; var DEFAULT_TOON_TEXTURES = [ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/bWiiMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh8aBHZBl14e8wAAAABJRU5ErkJggg==", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOUlEQVRYR+3WMREAMAwDsYY/yoDI7MLwIiP40+RJklfcCCBAgAABAgTqArfb/QMCCBAgQIAAgbbAB3z/e0F3js2cAAAAAElFTkSuQmCC", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/B5ilMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh81dWyx0gFwKAAAAABJRU5ErkJggg==", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOklEQVRYR+3WoREAMAwDsWb/UQtCy9wxTOQJ/oQ8SXKKGwEECBAgQIBAXeDt7f4BAQQIECBAgEBb4AOz8Hzx7WLY4wAAAABJRU5ErkJggg==", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABPUlEQVRYR+1XwW7CMAy1+f9fZOMysSEOEweEOPRNdm3HbdOyIhAcklPrOs/PLy9RygBALxzcCDQFmgJNgaZAU6Ap0BR4PwX8gsRMVLssMRH5HcpzJEaWL7EVg9F1IHRlyqQohgVr4FGUlUcMJSjcUlDw0zvjeun70cLWmneoyf7NgBTQSniBTQQSuJAZsOnnaczjIMb5hCiuHKxokCrJfVnrctyZL0PkJAJe1HMil4nxeyi3Ypfn1kX51jpPvo/JeCNC4PhVdHdJw2XjBR8brF8PEIhNVn12AgP7uHsTBguBn53MUZCqv7Lp07Pn5k1Ro+uWmUNn7D+M57rtk7aG0Vo73xyF/fbFf0bPJjDXngnGocDTdFhygZjwUQrMNrDcmZlQT50VJ/g/UwNyHpu778+yW+/ksOz/BFo54P4AsUXMfRq7XWsAAAAASUVORK5CYII=", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACMElEQVRYR+2Xv4pTQRTGf2dubhLdICiii2KnYKHVolhauKWPoGAnNr6BD6CvIVaihYuI2i1ia0BY0MZGRHQXjZj/mSPnnskfNWiWZUlzJ5k7M2cm833nO5Mziej2DWWJRUoCpQKlAntSQCqgw39/iUWAGmh37jrRnVsKlgpiqmkoGVABA7E57fvY+pJDdgKqF6HzFCSADkDq+F6AHABtQ+UMVE5D7zXod7fFNhTEckTbj5XQgHzNN+5tQvc5NG7C6BNkp6D3EmpXHDR+dQAjFLchW3VS9rlw3JBh+B7ys5Cf9z0GW1C/7P32AyBAOAz1q4jGliIH3YPuBnSfQX4OGreTIgEYQb/pBDtPnEQ4CivXYPAWBk13oHrB54yA9QuSn2H4AcKRpEILDt0BUzj+RLR1V5EqjD66NPRBVpLcQwjHoHYJOhsQv6U4mnzmrIXJCFr4LDwm/xBUoboG9XX4cc9VKdYoSA2yk5NQLJaKDUjTBoveG3Z2TElTxwjNK4M3LEZgUdDdruvcXzKBpStgp2NPiWi3ks9ZXxIoFVi+AvHLdc9TqtjL3/aYjpPlrzOcEnK62Szhimdd7xX232zFDTgtxezOu3WNMRLjiKgjtOhHVMd1loynVHvOgjuIIJMaELEqhJAV/RCSLbWTcfPFakFgFlALTRRvx+ok6Hlp/Q+v3fmx90bMyUzaEAhmM3KvHlXTL5DxnbGf/1M8RNNACLL5MNtPxP/mypJAqcDSFfgFhpYqWUzhTEAAAAAASUVORK5CYII=", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=" ]; var MeshBuilder = class { constructor(manager) { this.crossOrigin = "anonymous"; this.geometryBuilder = new GeometryBuilder(); this.materialBuilder = new MaterialBuilder(manager); } /** * @param {string} crossOrigin * @return {MeshBuilder} */ setCrossOrigin(crossOrigin) { this.crossOrigin = crossOrigin; return this; } /** * @param {Object} data - parsed PMD/PMX data * @param {string} resourcePath * @param {function} onProgress * @param {function} onError * @return {SkinnedMesh} */ build(data, resourcePath, onProgress, onError) { const geometry = this.geometryBuilder.build(data); const mesh = new SkinnedMesh(geometry, this.materialBuilder.setCrossOrigin(this.crossOrigin).setResourcePath(resourcePath).build(data, geometry, onProgress, onError)); const skeleton = new Skeleton(initBones(mesh)); mesh.bind(skeleton); return mesh; } }; function initBones(mesh) { const geometry = mesh.geometry; const bones = []; if (geometry && geometry.bones !== void 0) { for (let i = 0, il = geometry.bones.length; i < il; i++) { const gbone = geometry.bones[i]; const 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 (let i = 0, il = geometry.bones.length; i < il; i++) { const gbone = geometry.bones[i]; if (gbone.parent !== -1 && gbone.parent !== null && bones[gbone.parent] !== void 0) bones[gbone.parent].add(bones[i]); else mesh.add(bones[i]); } } mesh.updateMatrixWorld(true); return bones; } var GeometryBuilder = class { /** * @param {Object} data - parsed PMD/PMX data * @return {BufferGeometry} */ build(data) { const positions = []; const uvs = []; const normals = []; const indices = []; const groups = []; const bones = []; const skinIndices = []; const skinWeights = []; const morphTargets = []; const morphPositions = []; const iks = []; const grants = []; const rigidBodies = []; const constraints = []; let offset = 0; const boneTypeTable = {}; for (let i = 0; i < data.metadata.vertexCount; i++) { const v = data.vertices[i]; for (let j = 0, jl = v.position.length; j < jl; j++) positions.push(v.position[j]); for (let j = 0, jl = v.normal.length; j < jl; j++) normals.push(v.normal[j]); for (let j = 0, jl = v.uv.length; j < jl; j++) uvs.push(v.uv[j]); for (let j = 0; j < 4; j++) skinIndices.push(v.skinIndices.length - 1 >= j ? v.skinIndices[j] : 0); for (let j = 0; j < 4; j++) skinWeights.push(v.skinWeights.length - 1 >= j ? v.skinWeights[j] : 0); } for (let i = 0; i < data.metadata.faceCount; i++) { const face = data.faces[i]; for (let j = 0, jl = face.indices.length; j < jl; j++) indices.push(face.indices[j]); } for (let i = 0; i < data.metadata.materialCount; i++) { const material = data.materials[i]; groups.push({ offset: offset * 3, count: material.faceCount * 3 }); offset += material.faceCount; } for (let i = 0; i < data.metadata.rigidBodyCount; i++) { const body = data.rigidBodies[i]; let value = boneTypeTable[body.boneIndex]; value = value === void 0 ? body.type : Math.max(body.type, value); boneTypeTable[body.boneIndex] = value; } for (let i = 0; i < data.metadata.boneCount; i++) { const boneData = data.bones[i]; const bone = { index: i, transformationClass: boneData.transformationClass, parent: boneData.parentIndex, name: boneData.name, pos: boneData.position.slice(0, 3), rotq: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ], rigidBodyType: boneTypeTable[i] !== void 0 ? boneTypeTable[i] : -1 }; if (bone.parent !== -1) { bone.pos[0] -= data.bones[bone.parent].position[0]; bone.pos[1] -= data.bones[bone.parent].position[1]; bone.pos[2] -= data.bones[bone.parent].position[2]; } bones.push(bone); } if (data.metadata.format === "pmd") for (let i = 0; i < data.metadata.ikCount; i++) { const ik = data.iks[i]; const param = { target: ik.target, effector: ik.effector, iteration: ik.iteration, maxAngle: ik.maxAngle * 4, links: [] }; for (let j = 0, jl = ik.links.length; j < jl; j++) { const link = {}; link.index = ik.links[j].index; link.enabled = true; if (data.bones[link.index].name.indexOf("ひざ") >= 0) link.limitation = new Vector3(1, 0, 0); param.links.push(link); } iks.push(param); } else for (let i = 0; i < data.metadata.boneCount; i++) { const ik = data.bones[i].ik; if (ik === void 0) continue; const param = { target: i, effector: ik.effector, iteration: ik.iteration, maxAngle: ik.maxAngle, links: [] }; for (let j = 0, jl = ik.links.length; j < jl; j++) { const link = {}; link.index = ik.links[j].index; link.enabled = true; if (ik.links[j].angleLimitation === 1) { const rotationMin = ik.links[j].lowerLimitationAngle; const rotationMax = ik.links[j].upperLimitationAngle; const tmp1 = -rotationMax[0]; const tmp2 = -rotationMax[1]; rotationMax[0] = -rotationMin[0]; rotationMax[1] = -rotationMin[1]; rotationMin[0] = tmp1; rotationMin[1] = tmp2; link.rotationMin = new Vector3().fromArray(rotationMin); link.rotationMax = new Vector3().fromArray(rotationMax); } param.links.push(link); } iks.push(param); bones[i].ik = param; } if (data.metadata.format === "pmx") { let traverse = function(entry) { if (entry.param) { grants.push(entry.param); bones[entry.param.index].grant = entry.param; } entry.visited = true; for (let i = 0, il = entry.children.length; i < il; i++) { const child = entry.children[i]; if (!child.visited) traverse(child); } }; const grantEntryMap = {}; for (let i = 0; i < data.metadata.boneCount; i++) { const boneData = data.bones[i]; const grant = boneData.grant; if (grant === void 0) continue; grantEntryMap[i] = { parent: null, children: [], param: { index: i, parentIndex: grant.parentIndex, ratio: grant.ratio, isLocal: grant.isLocal, affectRotation: grant.affectRotation, affectPosition: grant.affectPosition, transformationClass: boneData.transformationClass }, visited: false }; } const rootEntry = { parent: null, children: [], param: null, visited: false }; for (const boneIndex in grantEntryMap) { const grantEntry = grantEntryMap[boneIndex]; const parentGrantEntry = grantEntryMap[grantEntry.parentIndex] || rootEntry; grantEntry.parent = parentGrantEntry; parentGrantEntry.children.push(grantEntry); } traverse(rootEntry); } function updateAttributes(attribute, morph, ratio) { for (let i = 0; i < morph.elementCount; i++) { const element = morph.elements[i]; let index; if (data.metadata.format === "pmd") index = data.morphs[0].elements[element.index].index; else index = element.index; attribute.array[index * 3 + 0] += element.position[0] * ratio; attribute.array[index * 3 + 1] += element.position[1] * ratio; attribute.array[index * 3 + 2] += element.position[2] * ratio; } } for (let i = 0; i < data.metadata.morphCount; i++) { const morph = data.morphs[i]; const params = { name: morph.name }; const attribute = new Float32BufferAttribute(data.metadata.vertexCount * 3, 3); attribute.name = morph.name; for (let j = 0; j < data.metadata.vertexCount * 3; j++) attribute.array[j] = positions[j]; if (data.metadata.format === "pmd") { if (i !== 0) updateAttributes(attribute, morph, 1); } else if (morph.type === 0) for (let j = 0; j < morph.elementCount; j++) { const morph2 = data.morphs[morph.elements[j].index]; const ratio = morph.elements[j].ratio; if (morph2.type === 1) updateAttributes(attribute, morph2, ratio); } else if (morph.type === 1) updateAttributes(attribute, morph, 1); else if (morph.type === 2); else if (morph.type === 3); else if (morph.type === 4); else if (morph.type === 5); else if (morph.type === 6); else if (morph.type === 7); else if (morph.type === 8); morphTargets.push(params); morphPositions.push(attribute); } for (let i = 0; i < data.metadata.rigidBodyCount; i++) { const rigidBody = data.rigidBodies[i]; const params = {}; for (const key in rigidBody) params[key] = rigidBody[key]; if (data.metadata.format === "pmx") { if (params.boneIndex !== -1) { const bone = data.bones[params.boneIndex]; params.position[0] -= bone.position[0]; params.position[1] -= bone.position[1]; params.position[2] -= bone.position[2]; } } rigidBodies.push(params); } for (let i = 0; i < data.metadata.constraintCount; i++) { const constraint = data.constraints[i]; const params = {}; for (const key in constraint) params[key] = constraint[key]; const bodyA = rigidBodies[params.rigidBodyIndex1]; const bodyB = rigidBodies[params.rigidBodyIndex2]; if (bodyA.type !== 0 && bodyB.type === 2) { if (bodyA.boneIndex !== -1 && bodyB.boneIndex !== -1 && data.bones[bodyB.boneIndex].parentIndex === bodyA.boneIndex) bodyB.type = 1; } constraints.push(params); } const geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); geometry.setAttribute("skinIndex", new Uint16BufferAttribute(skinIndices, 4)); geometry.setAttribute("skinWeight", new Float32BufferAttribute(skinWeights, 4)); geometry.setIndex(indices); for (let i = 0, il = groups.length; i < il; i++) geometry.addGroup(groups[i].offset, groups[i].count, i); geometry.bones = bones; geometry.morphTargets = morphTargets; geometry.morphAttributes.position = morphPositions; geometry.morphTargetsRelative = false; geometry.userData.MMD = { bones, iks, grants, rigidBodies, constraints, format: data.metadata.format }; geometry.computeBoundingSphere(); return geometry; } }; var MaterialBuilder = class { constructor(manager) { this.manager = manager; this.textureLoader = new TextureLoader(this.manager); this.tgaLoader = null; this.crossOrigin = "anonymous"; this.resourcePath = void 0; } /** * @param {string} crossOrigin * @return {MaterialBuilder} */ setCrossOrigin(crossOrigin) { this.crossOrigin = crossOrigin; return this; } /** * @param {string} resourcePath * @return {MaterialBuilder} */ setResourcePath(resourcePath) { this.resourcePath = resourcePath; return this; } /** * @param {Object} data - parsed PMD/PMX data * @param {BufferGeometry} geometry - some properties are dependend on geometry * @param {function} onProgress * @param {function} onError * @return {Array} */ build(data, geometry) { const materials = []; const textures = {}; this.textureLoader.setCrossOrigin(this.crossOrigin); for (let i = 0; i < data.metadata.materialCount; i++) { const material = data.materials[i]; const params = { userData: {} }; if (material.name !== void 0) params.name = material.name; params.color = new Color().fromArray(material.diffuse); params.opacity = material.diffuse[3]; params.emissive = new Color().fromArray(material.ambient); params.transparent = params.opacity !== 1; params.skinning = geometry.bones.length > 0 ? true : false; params.morphTargets = geometry.morphTargets.length > 0 ? true : false; params.fog = true; params.blending = 5; params.blendSrc = 204; params.blendDst = 205; params.blendSrcAlpha = 204; params.blendDstAlpha = 206; if (data.metadata.format === "pmx" && (material.flag & 1) === 1) params.side = 2; else params.side = params.opacity === 1 ? 0 : 2; if (data.metadata.format === "pmd") { if (material.fileName) { const fileNames = material.fileName.split("*"); params.map = this._loadTexture(fileNames[0], textures); if (fileNames.length > 1) { const extension = fileNames[1].slice(-4).toLowerCase(); params.envMap = this._loadTexture(fileNames[1], textures); params.combine = extension === ".sph" ? 0 : 2; } } const toonFileName = material.toonIndex === -1 ? "toon00.bmp" : data.toonTextures[material.toonIndex].fileName; params.gradientMap = this._loadTexture(toonFileName, textures, { isToonTexture: true, isDefaultToonTexture: this._isDefaultToonTexture(toonFileName) }); params.userData.outlineParameters = { thickness: material.edgeFlag === 1 ? .003 : 0, color: [ 0, 0, 0 ], alpha: 1, visible: material.edgeFlag === 1 }; } else { if (material.textureIndex !== -1) params.map = this._loadTexture(data.textures[material.textureIndex], textures); if (material.envTextureIndex !== -1 && (material.envFlag === 1 || material.envFlag == 2)) { params.envMap = this._loadTexture(data.textures[material.envTextureIndex], textures); params.combine = material.envFlag === 1 ? 0 : 2; } let toonFileName, isDefaultToon; if (material.toonIndex === -1 || material.toonFlag !== 0) { toonFileName = "toon" + ("0" + (material.toonIndex + 1)).slice(-2) + ".bmp"; isDefaultToon = true; } else { toonFileName = data.textures[material.toonIndex]; isDefaultToon = false; } params.gradientMap = this._loadTexture(toonFileName, textures, { isToonTexture: true, isDefaultToonTexture: isDefaultToon }); params.userData.outlineParameters = { thickness: material.edgeSize / 300, color: material.edgeColor.slice(0, 3), alpha: material.edgeColor[3], visible: (material.flag & 16) !== 0 && material.edgeSize > 0 }; } if (params.map !== void 0) { if (!params.transparent) this._checkImageTransparency(params.map, geometry, i); params.emissive.multiplyScalar(.2); } materials.push(new MeshToonMaterial(params)); } if (data.metadata.format === "pmx") { let checkAlphaMorph = function(elements, materials2) { for (let i = 0, il = elements.length; i < il; i++) { const element = elements[i]; if (element.index === -1) continue; const material = materials2[element.index]; if (material.opacity !== element.diffuse[3]) material.transparent = true; } }; for (let i = 0, il = data.morphs.length; i < il; i++) { const morph = data.morphs[i]; const elements = morph.elements; if (morph.type === 0) for (let j = 0, jl = elements.length; j < jl; j++) { const morph2 = data.morphs[elements[j].index]; if (morph2.type !== 8) continue; checkAlphaMorph(morph2.elements, materials); } else if (morph.type === 8) checkAlphaMorph(elements, materials); } } return materials; } _getTGALoader() { if (this.tgaLoader === null) { if (TGALoader === void 0) throw new Error("THREE.MMDLoader: Import TGALoader"); this.tgaLoader = new TGALoader(this.manager); } return this.tgaLoader; } _isDefaultToonTexture(name) { if (name.length !== 10) return false; return /toon(10|0[0-9])\.bmp/.test(name); } _loadTexture(filePath, textures, params, onProgress, onError) { params = params || {}; const scope = this; let fullPath; if (params.isDefaultToonTexture === true) { let index; try { index = parseInt(filePath.match(/toon([0-9]{2})\.bmp$/)[1]); } catch (e) { console.warn("THREE.MMDLoader: " + filePath + " seems like a not right default texture path. Using toon00.bmp instead."); index = 0; } fullPath = DEFAULT_TOON_TEXTURES[index]; } else fullPath = this.resourcePath + filePath; if (textures[fullPath] !== void 0) return textures[fullPath]; let loader = this.manager.getHandler(fullPath); if (loader === null) loader = filePath.slice(-4).toLowerCase() === ".tga" ? this._getTGALoader() : this.textureLoader; const texture = loader.load(fullPath, function(t) { if (params.isToonTexture === true) { t.image = scope._getRotatedImage(t.image); t.magFilter = NearestFilter; t.minFilter = NearestFilter; } t.flipY = false; t.wrapS = RepeatWrapping; t.wrapT = RepeatWrapping; for (let i = 0; i < texture.readyCallbacks.length; i++) texture.readyCallbacks[i](texture); delete texture.readyCallbacks; }, onProgress, onError); texture.readyCallbacks = []; textures[fullPath] = texture; return texture; } _getRotatedImage(image) { const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); const width = image.width; const height = image.height; canvas.width = width; canvas.height = height; context.clearRect(0, 0, width, height); context.translate(width / 2, height / 2); context.rotate(.5 * Math.PI); context.translate(-width / 2, -height / 2); context.drawImage(image, 0, 0); return context.getImageData(0, 0, width, height); } _checkImageTransparency(map, geometry, groupIndex) { map.readyCallbacks.push(function(texture) { function createImageData(image) { const canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; const context = canvas.getContext("2d"); context.drawImage(image, 0, 0); return context.getImageData(0, 0, canvas.width, canvas.height); } function detectImageTransparency(image, uvs, indices) { const width = image.width; const height = image.height; const data = image.data; const threshold = 253; if (data.length / (width * height) !== 4) return false; for (let i = 0; i < indices.length; i += 3) { const centerUV = { x: 0, y: 0 }; for (let j = 0; j < 3; j++) { const index = indices[i * 3 + j]; const uv = { x: uvs[index * 2 + 0], y: uvs[index * 2 + 1] }; if (getAlphaByUv(image, uv) < threshold) return true; centerUV.x += uv.x; centerUV.y += uv.y; } centerUV.x /= 3; centerUV.y /= 3; if (getAlphaByUv(image, centerUV) < threshold) return true; } return false; } function getAlphaByUv(image, uv) { const width = image.width; const height = image.height; let x = Math.round(uv.x * width) % width; let y = Math.round(uv.y * height) % height; if (x < 0) x += width; if (y < 0) y += height; const index = y * width + x; return image.data[index * 4 + 3]; } const imageData = texture.image.data !== void 0 ? texture.image : createImageData(texture.image); const group = geometry.groups[groupIndex]; if (detectImageTransparency(imageData, geometry.attributes.uv.array, geometry.index.array.slice(group.start, group.start + group.count))) map.transparent = true; }); } }; var AnimationBuilder = class { /** * @param {Object} vmd - parsed VMD data * @param {SkinnedMesh} mesh - tracks will be fitting to mesh * @return {AnimationClip} */ build(vmd, mesh) { const tracks = this.buildSkeletalAnimation(vmd, mesh).tracks; const tracks2 = this.buildMorphAnimation(vmd, mesh).tracks; for (let i = 0, il = tracks2.length; i < il; i++) tracks.push(tracks2[i]); return new AnimationClip("", -1, tracks); } /** * @param {Object} vmd - parsed VMD data * @param {SkinnedMesh} mesh - tracks will be fitting to mesh * @return {AnimationClip} */ buildSkeletalAnimation(vmd, mesh) { function pushInterpolation(array, interpolation, index) { array.push(interpolation[index + 0] / 127); array.push(interpolation[index + 8] / 127); array.push(interpolation[index + 4] / 127); array.push(interpolation[index + 12] / 127); } const tracks = []; const motions = {}; const bones = mesh.skeleton.bones; const boneNameDictionary = {}; for (let i = 0, il = bones.length; i < il; i++) boneNameDictionary[bones[i].name] = true; for (let i = 0; i < vmd.metadata.motionCount; i++) { const motion = vmd.motions[i]; const boneName = motion.boneName; if (boneNameDictionary[boneName] === void 0) continue; motions[boneName] = motions[boneName] || []; motions[boneName].push(motion); } for (const key in motions) { const array = motions[key]; array.sort(function(a, b) { return a.frameNum - b.frameNum; }); const times = []; const positions = []; const rotations = []; const pInterpolations = []; const rInterpolations = []; const basePosition = mesh.skeleton.getBoneByName(key).position.toArray(); for (let i = 0, il = array.length; i < il; i++) { const time = array[i].frameNum / 30; const position = array[i].position; const rotation = array[i].rotation; const interpolation = array[i].interpolation; times.push(time); for (let j = 0; j < 3; j++) positions.push(basePosition[j] + position[j]); for (let j = 0; j < 4; j++) rotations.push(rotation[j]); for (let j = 0; j < 3; j++) pushInterpolation(pInterpolations, interpolation, j); pushInterpolation(rInterpolations, interpolation, 3); } const targetName = ".bones[" + key + "]"; tracks.push(this._createTrack(targetName + ".position", VectorKeyframeTrack, times, positions, pInterpolations)); tracks.push(this._createTrack(targetName + ".quaternion", QuaternionKeyframeTrack, times, rotations, rInterpolations)); } return new AnimationClip("", -1, tracks); } /** * @param {Object} vmd - parsed VMD data * @param {SkinnedMesh} mesh - tracks will be fitting to mesh * @return {AnimationClip} */ buildMorphAnimation(vmd, mesh) { const tracks = []; const morphs = {}; const morphTargetDictionary = mesh.morphTargetDictionary; for (let i = 0; i < vmd.metadata.morphCount; i++) { const morph = vmd.morphs[i]; const morphName = morph.morphName; if (morphTargetDictionary[morphName] === void 0) continue; morphs[morphName] = morphs[morphName] || []; morphs[morphName].push(morph); } for (const key in morphs) { const array = morphs[key]; array.sort(function(a, b) { return a.frameNum - b.frameNum; }); const times = []; const values = []; for (let i = 0, il = array.length; i < il; i++) { times.push(array[i].frameNum / 30); values.push(array[i].weight); } tracks.push(new NumberKeyframeTrack(".morphTargetInfluences[" + morphTargetDictionary[key] + "]", times, values)); } return new AnimationClip("", -1, tracks); } /** * @param {Object} vmd - parsed VMD data * @return {AnimationClip} */ buildCameraAnimation(vmd) { function pushVector3(array, vec) { array.push(vec.x); array.push(vec.y); array.push(vec.z); } function pushQuaternion(array, q) { array.push(q.x); array.push(q.y); array.push(q.z); array.push(q.w); } function pushInterpolation(array, interpolation, index) { array.push(interpolation[index * 4 + 0] / 127); array.push(interpolation[index * 4 + 1] / 127); array.push(interpolation[index * 4 + 2] / 127); array.push(interpolation[index * 4 + 3] / 127); } const cameras = vmd.cameras === void 0 ? [] : vmd.cameras.slice(); cameras.sort(function(a, b) { return a.frameNum - b.frameNum; }); const times = []; const centers = []; const quaternions = []; const positions = []; const fovs = []; const cInterpolations = []; const qInterpolations = []; const pInterpolations = []; const fInterpolations = []; const quaternion = new Quaternion(); const euler = new Euler(); const position = new Vector3(); const center = new Vector3(); for (let i = 0, il = cameras.length; i < il; i++) { const motion = cameras[i]; const time = motion.frameNum / 30; const pos = motion.position; const rot = motion.rotation; const distance = motion.distance; const fov = motion.fov; const interpolation = motion.interpolation; times.push(time); position.set(0, 0, -distance); center.set(pos[0], pos[1], pos[2]); euler.set(-rot[0], -rot[1], -rot[2]); quaternion.setFromEuler(euler); position.add(center); position.applyQuaternion(quaternion); pushVector3(centers, center); pushQuaternion(quaternions, quaternion); pushVector3(positions, position); fovs.push(fov); for (let j = 0; j < 3; j++) pushInterpolation(cInterpolations, interpolation, j); pushInterpolation(qInterpolations, interpolation, 3); for (let j = 0; j < 3; j++) pushInterpolation(pInterpolations, interpolation, 4); pushInterpolation(fInterpolations, interpolation, 5); } const tracks = []; tracks.push(this._createTrack("target.position", VectorKeyframeTrack, times, centers, cInterpolations)); tracks.push(this._createTrack(".quaternion", QuaternionKeyframeTrack, times, quaternions, qInterpolations)); tracks.push(this._createTrack(".position", VectorKeyframeTrack, times, positions, pInterpolations)); tracks.push(this._createTrack(".fov", NumberKeyframeTrack, times, fovs, fInterpolations)); return new AnimationClip("", -1, tracks); } _createTrack(node, typedKeyframeTrack, times, values, interpolations) { if (times.length > 2) { times = times.slice(); values = values.slice(); interpolations = interpolations.slice(); const stride = values.length / times.length; const interpolateStride = interpolations.length / times.length; let index = 1; for (let aheadIndex = 2, endIndex = times.length; aheadIndex < endIndex; aheadIndex++) { for (let i = 0; i < stride; i++) if (values[index * stride + i] !== values[(index - 1) * stride + i] || values[index * stride + i] !== values[aheadIndex * stride + i]) { index++; break; } if (aheadIndex > index) { times[index] = times[aheadIndex]; for (let i = 0; i < stride; i++) values[index * stride + i] = values[aheadIndex * stride + i]; for (let i = 0; i < interpolateStride; i++) interpolations[index * interpolateStride + i] = interpolations[aheadIndex * interpolateStride + i]; } } times.length = index + 1; values.length = (index + 1) * stride; interpolations.length = (index + 1) * interpolateStride; } const track = new typedKeyframeTrack(node, times, values); track.createInterpolant = function InterpolantFactoryMethodCubicBezier(result) { return new CubicBezierInterpolation(this.times, this.values, this.getValueSize(), result, new Float32Array(interpolations)); }; return track; } }; var CubicBezierInterpolation = class extends Interpolant { constructor(parameterPositions, sampleValues, sampleSize, resultBuffer, params) { super(parameterPositions, sampleValues, sampleSize, resultBuffer); this.interpolationParams = params; } interpolate_(i1, t0, t, t1) { const result = this.resultBuffer; const values = this.sampleValues; const stride = this.valueSize; const params = this.interpolationParams; const offset1 = i1 * stride; const offset0 = offset1 - stride; const weight1 = t1 - t0 < 1 / 30 * 1.5 ? 0 : (t - t0) / (t1 - t0); if (stride === 4) { const x1 = params[i1 * 4 + 0]; const x2 = params[i1 * 4 + 1]; const y1 = params[i1 * 4 + 2]; const y2 = params[i1 * 4 + 3]; const ratio = this._calculate(x1, x2, y1, y2, weight1); Quaternion.slerpFlat(result, 0, values, offset0, values, offset1, ratio); } else if (stride === 3) for (let i = 0; i !== stride; ++i) { const x1 = params[i1 * 12 + i * 4 + 0]; const x2 = params[i1 * 12 + i * 4 + 1]; const y1 = params[i1 * 12 + i * 4 + 2]; const y2 = params[i1 * 12 + i * 4 + 3]; const ratio = this._calculate(x1, x2, y1, y2, weight1); result[i] = values[offset0 + i] * (1 - ratio) + values[offset1 + i] * ratio; } else { const x1 = params[i1 * 4 + 0]; const x2 = params[i1 * 4 + 1]; const y1 = params[i1 * 4 + 2]; const y2 = params[i1 * 4 + 3]; const ratio = this._calculate(x1, x2, y1, y2, weight1); result[0] = values[offset0] * (1 - ratio) + values[offset1] * ratio; } return result; } _calculate(x1, x2, y1, y2, x) { let c = .5; let t = c; let s = 1 - t; const loop = 15; const eps = 1e-5; const math = Math; let sst3, stt3, ttt; for (let i = 0; i < loop; i++) { sst3 = 3 * s * s * t; stt3 = 3 * s * t * t; ttt = t * t * t; const ft = sst3 * x1 + stt3 * x2 + ttt - x; if (math.abs(ft) < eps) break; c /= 2; t += ft < 0 ? c : -c; s = 1 - t; } return sst3 * y1 + stt3 * y2 + ttt; } }; //#endregion //#region node_modules/three-stdlib/loaders/KTXLoader.js var KTXLoader = class extends CompressedTextureLoader { constructor(manager) { super(manager); } parse(buffer, loadMipmaps) { const ktx = new KhronosTextureContainer(buffer, 1); return { mipmaps: ktx.mipmaps(loadMipmaps), width: ktx.pixelWidth, height: ktx.pixelHeight, format: ktx.glInternalFormat, isCubemap: ktx.numberOfFaces === 6, mipmapCount: ktx.numberOfMipmapLevels }; } }; var HEADER_LEN = 64; var COMPRESSED_2D = 0; var KhronosTextureContainer = class { /** * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented */ constructor(arrayBuffer, facesExpected) { this.arrayBuffer = arrayBuffer; const identifier = new Uint8Array(this.arrayBuffer, 0, 12); if (identifier[0] !== 171 || identifier[1] !== 75 || identifier[2] !== 84 || identifier[3] !== 88 || identifier[4] !== 32 || identifier[5] !== 49 || identifier[6] !== 49 || identifier[7] !== 187 || identifier[8] !== 13 || identifier[9] !== 10 || identifier[10] !== 26 || identifier[11] !== 10) { console.error("texture missing KTX identifier"); return; } const dataSize = Uint32Array.BYTES_PER_ELEMENT; const headerDataView = new DataView(this.arrayBuffer, 12, 13 * dataSize); const littleEndian = headerDataView.getUint32(0, true) === 67305985; this.glType = headerDataView.getUint32(1 * dataSize, littleEndian); this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian); this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian); this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian); this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian); this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian); this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian); this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian); this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian); this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian); this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian); this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian); if (this.glType !== 0) { console.warn("only compressed formats currently supported"); return; } else this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels); if (this.pixelHeight === 0 || this.pixelDepth !== 0) { console.warn("only 2D textures currently supported"); return; } if (this.numberOfArrayElements !== 0) { console.warn("texture arrays not currently supported"); return; } if (this.numberOfFaces !== facesExpected) { console.warn("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces); return; } this.loadType = COMPRESSED_2D; } mipmaps(loadMipmaps) { const mipmaps = []; let dataOffset = HEADER_LEN + this.bytesOfKeyValueData; let width = this.pixelWidth; let height = this.pixelHeight; const mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1; for (let level = 0; level < mipmapCount; level++) { const imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; dataOffset += 4; for (let face = 0; face < this.numberOfFaces; face++) { const byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize); mipmaps.push({ data: byteArray, width, height }); dataOffset += imageSize; dataOffset += 3 - (imageSize + 3) % 4; } width = Math.max(1, width * .5); height = Math.max(1, height * .5); } return mipmaps; } }; //#endregion //#region node_modules/three-stdlib/loaders/TiltLoader.js var TiltLoader = class extends Loader { load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setWithCredentials(this.withCredentials); loader.load(url, function(buffer) { try { onLoad(scope.parse(buffer)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(buffer) { const group = new Group(); const zip = unzipSync(new Uint8Array(buffer.slice(16))); const metadata = JSON.parse(strFromU8(zip["metadata.json"])); const data = new DataView(zip["data.sketch"].buffer); const num_strokes = data.getInt32(16, true); const brushes = {}; let offset = 20; for (let i = 0; i < num_strokes; i++) { const brush_index = data.getInt32(offset, true); const brush_color = [ data.getFloat32(offset + 4, true), data.getFloat32(offset + 8, true), data.getFloat32(offset + 12, true), data.getFloat32(offset + 16, true) ]; const brush_size = data.getFloat32(offset + 20, true); const stroke_mask = data.getUint32(offset + 24, true); const controlpoint_mask = data.getUint32(offset + 28, true); let offset_stroke_mask = 0; let offset_controlpoint_mask = 0; for (let j = 0; j < 4; j++) { const byte = 1 << j; if ((stroke_mask & byte) > 0) offset_stroke_mask += 4; if ((controlpoint_mask & byte) > 0) offset_controlpoint_mask += 4; } offset = offset + 28 + offset_stroke_mask + 4; const num_control_points = data.getInt32(offset, true); const positions = new Float32Array(num_control_points * 3); const quaternions = new Float32Array(num_control_points * 4); offset = offset + 4; for (let j = 0, k = 0; j < positions.length; j += 3, k += 4) { positions[j + 0] = data.getFloat32(offset + 0, true); positions[j + 1] = data.getFloat32(offset + 4, true); positions[j + 2] = data.getFloat32(offset + 8, true); quaternions[k + 0] = data.getFloat32(offset + 12, true); quaternions[k + 1] = data.getFloat32(offset + 16, true); quaternions[k + 2] = data.getFloat32(offset + 20, true); quaternions[k + 3] = data.getFloat32(offset + 24, true); offset = offset + 28 + offset_controlpoint_mask; } if (brush_index in brushes === false) brushes[brush_index] = []; brushes[brush_index].push([ positions, quaternions, brush_size, brush_color ]); } for (const brush_index in brushes) { const geometry = new StrokeGeometry(brushes[brush_index]); const material = getMaterial(metadata.BrushIndex[brush_index]); group.add(new Mesh(geometry, material)); } return group; } }; var StrokeGeometry = class extends BufferGeometry { constructor(strokes) { super(); const vertices = []; const colors = []; const uvs = []; const position = new Vector3(); const prevPosition = new Vector3(); const quaternion = new Quaternion(); const prevQuaternion = new Quaternion(); const vector1 = new Vector3(); const vector2 = new Vector3(); const vector3 = new Vector3(); const vector4 = new Vector3(); for (const k in strokes) { const stroke = strokes[k]; const positions = stroke[0]; const quaternions = stroke[1]; const size = stroke[2]; const color = stroke[3]; prevPosition.fromArray(positions, 0); prevQuaternion.fromArray(quaternions, 0); for (let i = 3, j = 4, l = positions.length; i < l; i += 3, j += 4) { position.fromArray(positions, i); quaternion.fromArray(quaternions, j); vector1.set(-size, 0, 0); vector1.applyQuaternion(quaternion); vector1.add(position); vector2.set(size, 0, 0); vector2.applyQuaternion(quaternion); vector2.add(position); vector3.set(size, 0, 0); vector3.applyQuaternion(prevQuaternion); vector3.add(prevPosition); vector4.set(-size, 0, 0); vector4.applyQuaternion(prevQuaternion); vector4.add(prevPosition); vertices.push(vector1.x, vector1.y, -vector1.z); vertices.push(vector2.x, vector2.y, -vector2.z); vertices.push(vector4.x, vector4.y, -vector4.z); vertices.push(vector2.x, vector2.y, -vector2.z); vertices.push(vector3.x, vector3.y, -vector3.z); vertices.push(vector4.x, vector4.y, -vector4.z); prevPosition.copy(position); prevQuaternion.copy(quaternion); colors.push(...color); colors.push(...color); colors.push(...color); colors.push(...color); colors.push(...color); colors.push(...color); const p1 = i / l; const p2 = (i - 3) / l; uvs.push(p1, 0); uvs.push(p1, 1); uvs.push(p2, 0); uvs.push(p1, 1); uvs.push(p2, 1); uvs.push(p2, 0); } } this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3)); this.setAttribute("color", new BufferAttribute(new Float32Array(colors), 4)); this.setAttribute("uv", new BufferAttribute(new Float32Array(uvs), 2)); } }; var BRUSH_LIST_ARRAY = { "89d104cd-d012-426b-b5b3-bbaee63ac43c": "Bubbles", "700f3aa8-9a7c-2384-8b8a-ea028905dd8c": "CelVinyl", "0f0ff7b2-a677-45eb-a7d6-0cd7206f4816": "ChromaticWave", "1161af82-50cf-47db-9706-0c3576d43c43": "CoarseBristles", "79168f10-6961-464a-8be1-57ed364c5600": "CoarseBristlesSingleSided", "1caa6d7d-f015-3f54-3a4b-8b5354d39f81": "Comet", "c8313697-2563-47fc-832e-290f4c04b901": "DiamondHull", "4391aaaa-df73-4396-9e33-31e4e4930b27": "Disco", "d1d991f2-e7a0-4cf1-b328-f57e915e6260": "DotMarker", "6a1cf9f9-032c-45ec-9b1d-a6680bee30f7": "Dots", "0d3889f3-3ede-470c-8af4-f44813306126": "DoubleTaperedFlat", "0d3889f3-3ede-470c-8af4-de4813306126": "DoubleTaperedMarker", "d0262945-853c-4481-9cbd-88586bed93cb": "DuctTape", "3ca16e2f-bdcd-4da2-8631-dcef342f40f1": "DuctTapeSingleSided", "f6e85de3-6dcc-4e7f-87fd-cee8c3d25d51": "Electricity", "02ffb866-7fb2-4d15-b761-1012cefb1360": "Embers", "cb92b597-94ca-4255-b017-0e3f42f12f9e": "Fire", "2d35bcf0-e4d8-452c-97b1-3311be063130": "Flat", "55303bc4-c749-4a72-98d9-d23e68e76e18": "FlatDeprecated", "280c0a7a-aad8-416c-a7d2-df63d129ca70": "FlatSingleSided", "cf019139-d41c-4eb0-a1d0-5cf54b0a42f3": "Highlighter", "6a1cf9f9-032c-45ec-9b6e-a6680bee32e9": "HyperGrid", "dce872c2-7b49-4684-b59b-c45387949c5c": "Hypercolor", "e8ef32b1-baa8-460a-9c2c-9cf8506794f5": "HypercolorSingleSided", "2f212815-f4d3-c1a4-681a-feeaf9c6dc37": "Icing", "f5c336cf-5108-4b40-ade9-c687504385ab": "Ink", "c0012095-3ffd-4040-8ee1-fc180d346eaa": "InkSingleSided", "4a76a27a-44d8-4bfe-9a8c-713749a499b0": "Leaves", "ea19de07-d0c0-4484-9198-18489a3c1487": "LeavesSingleSided", "2241cd32-8ba2-48a5-9ee7-2caef7e9ed62": "Light", "4391aaaa-df81-4396-9e33-31e4e4930b27": "LightWire", "d381e0f5-3def-4a0d-8853-31e9200bcbda": "Lofted", "429ed64a-4e97-4466-84d3-145a861ef684": "Marker", "79348357-432d-4746-8e29-0e25c112e3aa": "MatteHull", "b2ffef01-eaaa-4ab5-aa64-95a2c4f5dbc6": "NeonPulse", "f72ec0e7-a844-4e38-82e3-140c44772699": "OilPaint", "c515dad7-4393-4681-81ad-162ef052241b": "OilPaintSingleSided", "f1114e2e-eb8d-4fde-915a-6e653b54e9f5": "Paper", "759f1ebd-20cd-4720-8d41-234e0da63716": "PaperSingleSided", "e0abbc80-0f80-e854-4970-8924a0863dcc": "Petal", "c33714d1-b2f9-412e-bd50-1884c9d46336": "Plasma", "ad1ad437-76e2-450d-a23a-e17f8310b960": "Rainbow", "faaa4d44-fcfb-4177-96be-753ac0421ba3": "ShinyHull", "70d79cca-b159-4f35-990c-f02193947fe8": "Smoke", "d902ed8b-d0d1-476c-a8de-878a79e3a34c": "Snow", "accb32f5-4509-454f-93f8-1df3fd31df1b": "SoftHighlighter", "cf7f0059-7aeb-53a4-2b67-c83d863a9ffa": "Spikes", "8dc4a70c-d558-4efd-a5ed-d4e860f40dc3": "Splatter", "7a1c8107-50c5-4b70-9a39-421576d6617e": "SplatterSingleSided", "0eb4db27-3f82-408d-b5a1-19ebd7d5b711": "Stars", "44bb800a-fbc3-4592-8426-94ecb05ddec3": "Streamers", "0077f88c-d93a-42f3-b59b-b31c50cdb414": "Taffy", "b468c1fb-f254-41ed-8ec9-57030bc5660c": "TaperedFlat", "c8ccb53d-ae13-45ef-8afb-b730d81394eb": "TaperedFlatSingleSided", "d90c6ad8-af0f-4b54-b422-e0f92abe1b3c": "TaperedMarker", "1a26b8c0-8a07-4f8a-9fac-d2ef36e0cad0": "TaperedMarker_Flat", "75b32cf0-fdd6-4d89-a64b-e2a00b247b0f": "ThickPaint", "fdf0326a-c0d1-4fed-b101-9db0ff6d071f": "ThickPaintSingleSided", "4391385a-df73-4396-9e33-31e4e4930b27": "Toon", "a8fea537-da7c-4d4b-817f-24f074725d6d": "UnlitHull", "d229d335-c334-495a-a801-660ac8a87360": "VelvetInk", "10201aa3-ebc2-42d8-84b7-2e63f6eeb8ab": "Waveform", "b67c0e81-ce6d-40a8-aeb0-ef036b081aa3": "WetPaint", "dea67637-cd1a-27e4-c9b1-52f4bbcb84e5": "WetPaintSingleSided", "5347acf0-a8e2-47b6-8346-30c70719d763": "WigglyGraphite", "e814fef1-97fd-7194-4a2f-50c2bb918be2": "WigglyGraphiteSingleSided", "4391385a-cf83-4396-9e33-31e4e4930b27": "Wire" }; var common = { colors: { BloomColor: ` vec3 BloomColor(vec3 color, float gain) { // Guarantee that there's at least a little bit of all 3 channels. // This makes fully-saturated strokes (which only have 2 non-zero // color channels) eventually clip to white rather than to a secondary. float cmin = length(color.rgb) * .05; color.rgb = max(color.rgb, vec3(cmin, cmin, cmin)); // If we try to remove this pow() from .a, it brightens up // pressure-sensitive strokes; looks better as-is. color = pow(color, vec3(2.2)); color.rgb *= 2. * exp(gain * 10.); return color; } `, LinearToSrgb: ` vec3 LinearToSrgb(vec3 color) { // Approximation http://chilliant.blogspot.com/2012/08/srgb-approximations-for-hlsl.html vec3 linearColor = color.rgb; vec3 S1 = sqrt(linearColor); vec3 S2 = sqrt(S1); vec3 S3 = sqrt(S2); color.rgb = 0.662002687 * S1 + 0.684122060 * S2 - 0.323583601 * S3 - 0.0225411470 * linearColor; return color; } `, hsv: ` // uniform sampler2D lookupTex; vec4 lookup(vec4 textureColor) { return textureColor; } vec3 lookup(vec3 textureColor) { return textureColor; } vec3 hsv2rgb( vec3 hsv ) { vec3 rgb = clamp( abs(mod(hsv.x*6.0+vec3(0.0,4.0,2.0),6.0)-3.0)-1.0, 0.0, 1.0 ); return hsv.z * mix( vec3(1.0), rgb, hsv.y); } vec3 rgb2hsv( vec3 rgb ) { vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); vec4 p = mix(vec4(rgb.bg, K.wz), vec4(rgb.gb, K.xy), step(rgb.b, rgb.g)); vec4 q = mix(vec4(p.xyw, rgb.r), vec4(rgb.r, p.yzx), step(p.x, rgb.r)); float d = q.x - min(q.w, q.y); float e = 1.0e-10; return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); } `, SrgbToLinear: ` vec3 SrgbToLinear(vec3 color) { // Approximation http://chilliant.blogspot.com/2012/08/srgb-approximations-for-hlsl.html vec3 sRGB = color.rgb; color.rgb = sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878); return color; } ` } }; var shaders = () => ({ Light: { uniforms: { mainTex: { value: new TextureLoader().setPath("./textures/tiltbrush/").loader.load("Light.webp") }, alphaTest: { value: .067 }, emission_gain: { value: .45 }, alpha: { value: 1 } }, vertexShader: ` precision highp float; precision highp int; attribute vec2 uv; attribute vec4 color; attribute vec3 position; uniform mat4 modelMatrix; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat3 normalMatrix; uniform vec3 cameraPosition; varying vec2 vUv; varying vec3 vColor; ${common.colors.LinearToSrgb} ${common.colors.hsv} void main() { vUv = uv; vColor = lookup(color.rgb); vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); gl_Position = projectionMatrix * mvPosition; } `, fragmentShader: ` precision highp float; precision highp int; uniform float emission_gain; uniform sampler2D mainTex; uniform float alphaTest; varying vec2 vUv; varying vec3 vColor; ${common.colors.BloomColor} ${common.colors.SrgbToLinear} void main(){ vec4 col = texture2D(mainTex, vUv); vec3 color = vColor; color = BloomColor(color, emission_gain); color = color * col.rgb; color = color * col.a; color = SrgbToLinear(color); gl_FragColor = vec4(color, 1.0); } `, side: 2, transparent: true, depthFunc: 2, depthWrite: true, depthTest: false, blending: 5, blendDst: 201, blendDstAlpha: 201, blendEquation: 100, blendEquationAlpha: 100, blendSrc: 201, blendSrcAlpha: 201 } }); function getMaterial(GUID) { switch (BRUSH_LIST_ARRAY[GUID]) { case "Light": return new RawShaderMaterial(shaders().Light); default: return new MeshBasicMaterial({ vertexColors: true, side: 2 }); } } //#endregion //#region node_modules/three-stdlib/loaders/DRACOLoader.js var _taskCache = /* @__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 loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, (buffer) => { const taskConfig = { attributeIDs: this.defaultAttributeIDs, attributeTypes: this.defaultAttributeTypes, useUniqueIDs: false }; this.decodeGeometry(buffer, taskConfig).then(onLoad).catch(onError); }, onProgress, onError); } /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */ decodeDracoFile(buffer, callback, attributeIDs, attributeTypes) { const taskConfig = { attributeIDs: attributeIDs || this.defaultAttributeIDs, attributeTypes: attributeTypes || this.defaultAttributeTypes, useUniqueIDs: !!attributeIDs }; this.decodeGeometry(buffer, taskConfig).then(callback); } decodeGeometry(buffer, 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 (_taskCache.has(buffer)) { const cachedTask = _taskCache.get(buffer); if (cachedTask.key === taskKey) return cachedTask.promise; else if (buffer.byteLength === 0) throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred."); } let worker; const taskID = this.workerNextTaskID++; const taskCost = buffer.byteLength; const geometryPending = this._getWorker(taskID, taskCost).then((_worker) => { worker = _worker; return new Promise((resolve, reject) => { worker._callbacks[taskID] = { resolve, reject }; worker.postMessage({ type: "decode", id: taskID, taskConfig, buffer }, [buffer]); }); }).then((message) => this._createGeometry(message.geometry)); geometryPending.catch(() => true).then(() => { if (worker && taskID) this._releaseTask(worker, taskID); }); _taskCache.set(buffer, { key: taskKey, promise: geometryPending }); return geometryPending; } _createGeometry(geometryData) { const geometry = new BufferGeometry(); if (geometryData.index) geometry.setIndex(new BufferAttribute(geometryData.index.array, 1)); for (let i = 0; i < geometryData.attributes.length; i++) { const attribute = geometryData.attributes[i]; const name = attribute.name; const array = attribute.array; const itemSize = attribute.itemSize; geometry.setAttribute(name, new BufferAttribute(array, itemSize)); } return geometry; } _loadLibrary(url, responseType) { const loader = new FileLoader(this.manager); loader.setPath(this.decoderPath); loader.setResponseType(responseType); loader.setWithCredentials(this.withCredentials); return new Promise((resolve, reject) => { loader.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(e) { const message = e.data; switch (message.type) { case "decode": worker2._callbacks[message.id].resolve(message); break; case "error": worker2._callbacks[message.id].reject(message); break; default: console.error("THREE.DRACOLoader: Unexpected message, \"" + message.type + "\""); } }; this.workerPool.push(worker2); } else this.workerPool.sort(function(a, b) { return a._taskLoad > b._taskLoad ? -1 : 1; }); const worker = this.workerPool[this.workerPool.length - 1]; worker._taskCosts[taskID] = taskCost; worker._taskLoad += taskCost; return worker; }); } _releaseTask(worker, taskID) { worker._taskLoad -= worker._taskCosts[taskID]; delete worker._callbacks[taskID]; delete worker._taskCosts[taskID]; } debug() { console.log("Task load: ", this.workerPool.map((worker) => worker._taskLoad)); } dispose() { for (let i = 0; i < this.workerPool.length; ++i) this.workerPool[i].terminate(); this.workerPool.length = 0; return this; } }; function DRACOWorker() { let decoderConfig; let decoderPending; onmessage = function(e) { const message = e.data; switch (message.type) { case "init": decoderConfig = message.decoderConfig; decoderPending = new Promise(function(resolve) { decoderConfig.onModuleLoaded = function(draco) { resolve({ draco }); }; DracoDecoderModule(decoderConfig); }); break; case "decode": const buffer = message.buffer; const taskConfig = message.taskConfig; decoderPending.then((module) => { const draco = module.draco; const decoder = new draco.Decoder(); const decoderBuffer = new draco.DecoderBuffer(); decoderBuffer.Init(new Int8Array(buffer), buffer.byteLength); try { const geometry = decodeGeometry(draco, decoder, decoderBuffer, taskConfig); const buffers = geometry.attributes.map((attr) => attr.array.buffer); if (geometry.index) buffers.push(geometry.index.array.buffer); self.postMessage({ type: "decode", id: message.id, geometry }, buffers); } catch (error) { console.error(error); self.postMessage({ type: "error", id: message.id, error: error.message }); } finally { draco.destroy(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 geometry = { index: null, attributes: [] }; for (const attributeName in attributeIDs) { const attributeType = self[attributeTypes[attributeName]]; let attribute; let attributeID; if (taskConfig.useUniqueIDs) { attributeID = attributeIDs[attributeName]; attribute = decoder.GetAttributeByUniqueId(dracoGeometry, attributeID); } else { attributeID = decoder.GetAttributeId(dracoGeometry, draco[attributeIDs[attributeName]]); if (attributeID === -1) continue; attribute = decoder.GetAttribute(dracoGeometry, attributeID); } geometry.attributes.push(decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute)); } if (geometryType === draco.TRIANGULAR_MESH) geometry.index = decodeIndex(draco, decoder, dracoGeometry); draco.destroy(dracoGeometry); return geometry; } function decodeIndex(draco, decoder, dracoGeometry) { const numIndices = dracoGeometry.num_faces() * 3; const byteLength = numIndices * 4; const ptr = draco._malloc(byteLength); decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr); const index = new Uint32Array(draco.HEAPF32.buffer, ptr, numIndices).slice(); draco._free(ptr); return { array: index, itemSize: 1 }; } function decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute) { const numComponents = attribute.num_components(); const numValues = dracoGeometry.num_points() * 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; } } } //#endregion //#region node_modules/three-stdlib/loaders/HDRCubeTextureLoader.js var HDRCubeTextureLoader = class extends Loader { constructor(manager) { super(manager); this.hdrLoader = new RGBELoader(); this.type = HalfFloatType; } load(urls, onLoad, onProgress, onError) { if (typeof urls === "string") urls = [urls]; else if (!Array.isArray(urls)) { console.warn("THREE.HDRCubeTextureLoader signature has changed. Use .setDataType() instead."); this.setDataType(urls); urls = onLoad; onLoad = onProgress; onProgress = onError; onError = arguments[4]; } const texture = new CubeTexture(); texture.type = this.type; 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; break; } const scope = this; let loaded = 0; function loadHDRData(i, onLoad2, onProgress2, onError2) { new FileLoader(scope.manager).setPath(scope.path).setResponseType("arraybuffer").setWithCredentials(scope.withCredentials).load(urls[i], function(buffer) { loaded++; const texData = scope.hdrLoader.parse(buffer); if (!texData) return; if (texData.data !== void 0) { const dataTexture = new DataTexture(texData.data, texData.width, texData.height); dataTexture.type = texture.type; if ("colorSpace" in dataTexture) dataTexture.colorSpace = texture.SRGBColorSpace; else dataTexture.encoding = texture.encoding; dataTexture.format = texture.format; dataTexture.minFilter = texture.minFilter; dataTexture.magFilter = texture.magFilter; dataTexture.generateMipmaps = texture.generateMipmaps; texture.images[i] = dataTexture; } if (loaded === 6) { texture.needsUpdate = true; if (onLoad2) onLoad2(texture); } }, onProgress2, onError2); } for (let i = 0; i < urls.length; i++) loadHDRData(i, onLoad, onProgress, onError); return texture; } setDataType(value) { this.type = value; this.hdrLoader.setDataType(value); return this; } }; //#endregion //#region node_modules/three-stdlib/loaders/PDBLoader.js var PDBLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(text) { function trim(text2) { return text2.replace(/^\s\s*/, "").replace(/\s\s*$/, ""); } function capitalize(text2) { return text2.charAt(0).toUpperCase() + text2.substr(1).toLowerCase(); } function hash(s, e) { return "s" + Math.min(s, e) + "e" + Math.max(s, e); } function parseBond(start, length, satom, i) { const eatom = parseInt(lines[i].substr(start, length)); if (eatom) { const h = hash(satom, eatom); if (_bhash[h] === void 0) { _bonds.push([ satom - 1, eatom - 1, 1 ]); _bhash[h] = _bonds.length - 1; } } } function buildGeometry() { const build = { geometryAtoms: new BufferGeometry(), geometryBonds: new BufferGeometry(), json: { atoms } }; const geometryAtoms = build.geometryAtoms; const geometryBonds = build.geometryBonds; const verticesAtoms = []; const colorsAtoms = []; const verticesBonds = []; for (let i = 0, l = atoms.length; i < l; i++) { const atom = atoms[i]; const x = atom[0]; const y = atom[1]; const z = atom[2]; verticesAtoms.push(x, y, z); const r = atom[3][0] / 255; const g = atom[3][1] / 255; const b = atom[3][2] / 255; colorsAtoms.push(r, g, b); } for (let i = 0, l = _bonds.length; i < l; i++) { const bond = _bonds[i]; const start = bond[0]; const end = bond[1]; const startAtom = _atomMap[start]; const endAtom = _atomMap[end]; let x = startAtom[0]; let y = startAtom[1]; let z = startAtom[2]; verticesBonds.push(x, y, z); x = endAtom[0]; y = endAtom[1]; z = endAtom[2]; verticesBonds.push(x, y, z); } geometryAtoms.setAttribute("position", new Float32BufferAttribute(verticesAtoms, 3)); geometryAtoms.setAttribute("color", new Float32BufferAttribute(colorsAtoms, 3)); geometryBonds.setAttribute("position", new Float32BufferAttribute(verticesBonds, 3)); return build; } const CPK = { h: [ 255, 255, 255 ], he: [ 217, 255, 255 ], li: [ 204, 128, 255 ], be: [ 194, 255, 0 ], b: [ 255, 181, 181 ], c: [ 144, 144, 144 ], n: [ 48, 80, 248 ], o: [ 255, 13, 13 ], f: [ 144, 224, 80 ], ne: [ 179, 227, 245 ], na: [ 171, 92, 242 ], mg: [ 138, 255, 0 ], al: [ 191, 166, 166 ], si: [ 240, 200, 160 ], p: [ 255, 128, 0 ], s: [ 255, 255, 48 ], cl: [ 31, 240, 31 ], ar: [ 128, 209, 227 ], k: [ 143, 64, 212 ], ca: [ 61, 255, 0 ], sc: [ 230, 230, 230 ], ti: [ 191, 194, 199 ], v: [ 166, 166, 171 ], cr: [ 138, 153, 199 ], mn: [ 156, 122, 199 ], fe: [ 224, 102, 51 ], co: [ 240, 144, 160 ], ni: [ 80, 208, 80 ], cu: [ 200, 128, 51 ], zn: [ 125, 128, 176 ], ga: [ 194, 143, 143 ], ge: [ 102, 143, 143 ], as: [ 189, 128, 227 ], se: [ 255, 161, 0 ], br: [ 166, 41, 41 ], kr: [ 92, 184, 209 ], rb: [ 112, 46, 176 ], sr: [ 0, 255, 0 ], y: [ 148, 255, 255 ], zr: [ 148, 224, 224 ], nb: [ 115, 194, 201 ], mo: [ 84, 181, 181 ], tc: [ 59, 158, 158 ], ru: [ 36, 143, 143 ], rh: [ 10, 125, 140 ], pd: [ 0, 105, 133 ], ag: [ 192, 192, 192 ], cd: [ 255, 217, 143 ], in: [ 166, 117, 115 ], sn: [ 102, 128, 128 ], sb: [ 158, 99, 181 ], te: [ 212, 122, 0 ], i: [ 148, 0, 148 ], xe: [ 66, 158, 176 ], cs: [ 87, 23, 143 ], ba: [ 0, 201, 0 ], la: [ 112, 212, 255 ], ce: [ 255, 255, 199 ], pr: [ 217, 255, 199 ], nd: [ 199, 255, 199 ], pm: [ 163, 255, 199 ], sm: [ 143, 255, 199 ], eu: [ 97, 255, 199 ], gd: [ 69, 255, 199 ], tb: [ 48, 255, 199 ], dy: [ 31, 255, 199 ], ho: [ 0, 255, 156 ], er: [ 0, 230, 117 ], tm: [ 0, 212, 82 ], yb: [ 0, 191, 56 ], lu: [ 0, 171, 36 ], hf: [ 77, 194, 255 ], ta: [ 77, 166, 255 ], w: [ 33, 148, 214 ], re: [ 38, 125, 171 ], os: [ 38, 102, 150 ], ir: [ 23, 84, 135 ], pt: [ 208, 208, 224 ], au: [ 255, 209, 35 ], hg: [ 184, 184, 208 ], tl: [ 166, 84, 77 ], pb: [ 87, 89, 97 ], bi: [ 158, 79, 181 ], po: [ 171, 92, 0 ], at: [ 117, 79, 69 ], rn: [ 66, 130, 150 ], fr: [ 66, 0, 102 ], ra: [ 0, 125, 0 ], ac: [ 112, 171, 250 ], th: [ 0, 186, 255 ], pa: [ 0, 161, 255 ], u: [ 0, 143, 255 ], np: [ 0, 128, 255 ], pu: [ 0, 107, 255 ], am: [ 84, 92, 242 ], cm: [ 120, 92, 227 ], bk: [ 138, 79, 227 ], cf: [ 161, 54, 212 ], es: [ 179, 31, 212 ], fm: [ 179, 31, 186 ], md: [ 179, 13, 166 ], no: [ 189, 13, 135 ], lr: [ 199, 0, 102 ], rf: [ 204, 0, 89 ], db: [ 209, 0, 79 ], sg: [ 217, 0, 69 ], bh: [ 224, 0, 56 ], hs: [ 230, 0, 46 ], mt: [ 235, 0, 38 ], ds: [ 235, 0, 38 ], rg: [ 235, 0, 38 ], cn: [ 235, 0, 38 ], uut: [ 235, 0, 38 ], uuq: [ 235, 0, 38 ], uup: [ 235, 0, 38 ], uuh: [ 235, 0, 38 ], uus: [ 235, 0, 38 ], uuo: [ 235, 0, 38 ] }; const atoms = []; const _bonds = []; const _bhash = {}; const _atomMap = {}; const lines = text.split("\n"); for (let i = 0, l = lines.length; i < l; i++) if (lines[i].substr(0, 4) === "ATOM" || lines[i].substr(0, 6) === "HETATM") { const x = parseFloat(lines[i].substr(30, 7)); const y = parseFloat(lines[i].substr(38, 7)); const z = parseFloat(lines[i].substr(46, 7)); const index = parseInt(lines[i].substr(6, 5)) - 1; let e = trim(lines[i].substr(76, 2)).toLowerCase(); if (e === "") e = trim(lines[i].substr(12, 2)).toLowerCase(); const atomData = [ x, y, z, CPK[e], capitalize(e) ]; atoms.push(atomData); _atomMap[index] = atomData; } else if (lines[i].substr(0, 6) === "CONECT") { const satom = parseInt(lines[i].substr(6, 5)); parseBond(11, 5, satom, i); parseBond(16, 5, satom, i); parseBond(21, 5, satom, i); parseBond(26, 5, satom, i); } return buildGeometry(); } }; //#endregion //#region node_modules/three-stdlib/loaders/PRWMLoader.js var bigEndianPlatform = null; function isBigEndianPlatform() { if (bigEndianPlatform === null) { const buffer = /* @__PURE__ */ new ArrayBuffer(2), uint8Array = new Uint8Array(buffer), uint16Array = new Uint16Array(buffer); uint8Array[0] = 170; uint8Array[1] = 187; bigEndianPlatform = uint16Array[0] === 43707; } return bigEndianPlatform; } var InvertedEncodingTypes = [ null, Float32Array, null, Int8Array, Int16Array, null, Int32Array, Uint8Array, Uint16Array, null, Uint32Array ]; var getMethods = { Uint16Array: "getUint16", Uint32Array: "getUint32", Int16Array: "getInt16", Int32Array: "getInt32", Float32Array: "getFloat32", Float64Array: "getFloat64" }; function copyFromBuffer(sourceArrayBuffer, viewType, position, length, fromBigEndian) { const bytesPerElement = viewType.BYTES_PER_ELEMENT; let result; if (fromBigEndian === isBigEndianPlatform() || bytesPerElement === 1) result = new viewType(sourceArrayBuffer, position, length); else { const readView = new DataView(sourceArrayBuffer, position, length * bytesPerElement), getMethod = getMethods[viewType.name], littleEndian = !fromBigEndian; result = new viewType(length); for (let i = 0; i < length; i++) result[i] = readView[getMethod](i * bytesPerElement, littleEndian); } return result; } function decodePrwm(buffer) { const array = new Uint8Array(buffer), version = array[0]; let flags = array[1]; const indexedGeometry = !!(flags >> 7 & 1), indicesType = flags >> 6 & 1, bigEndian = (flags >> 5 & 1) === 1, attributesNumber = flags & 31; let valuesNumber = 0, indicesNumber = 0; if (bigEndian) { valuesNumber = (array[2] << 16) + (array[3] << 8) + array[4]; indicesNumber = (array[5] << 16) + (array[6] << 8) + array[7]; } else { valuesNumber = array[2] + (array[3] << 8) + (array[4] << 16); indicesNumber = array[5] + (array[6] << 8) + (array[7] << 16); } if (version === 0) throw new Error("PRWM decoder: Invalid format version: 0"); else if (version !== 1) throw new Error("PRWM decoder: Unsupported format version: " + version); if (!indexedGeometry) { if (indicesType !== 0) throw new Error("PRWM decoder: Indices type must be set to 0 for non-indexed geometries"); else if (indicesNumber !== 0) throw new Error("PRWM decoder: Number of indices must be set to 0 for non-indexed geometries"); } let pos = 8; const attributes = {}; for (let i = 0; i < attributesNumber; i++) { let attributeName = ""; while (pos < array.length) { const char = array[pos]; pos++; if (char === 0) break; else attributeName += String.fromCharCode(char); } flags = array[pos]; const attributeType = flags >> 7 & 1; const cardinality = (flags >> 4 & 3) + 1; const arrayType = InvertedEncodingTypes[flags & 15]; pos++; pos = Math.ceil(pos / 4) * 4; const values = copyFromBuffer(buffer, arrayType, pos, cardinality * valuesNumber, bigEndian); pos += arrayType.BYTES_PER_ELEMENT * cardinality * valuesNumber; attributes[attributeName] = { type: attributeType, cardinality, values }; } pos = Math.ceil(pos / 4) * 4; let indices = null; if (indexedGeometry) indices = copyFromBuffer(buffer, indicesType === 1 ? Uint32Array : Uint16Array, pos, indicesNumber, bigEndian); return { version, attributes, indices }; } var PRWMLoader = /* @__PURE__ */ (() => { class PRWMLoader2 extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); url = url.replace(/\*/g, isBigEndianPlatform() ? "be" : "le"); loader.load(url, function(arrayBuffer) { try { onLoad(scope.parse(arrayBuffer)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(arrayBuffer) { const data = decodePrwm(arrayBuffer), attributesKey = Object.keys(data.attributes), bufferGeometry = new BufferGeometry(); for (let i = 0; i < attributesKey.length; i++) { const attribute = data.attributes[attributesKey[i]]; bufferGeometry.setAttribute(attributesKey[i], new BufferAttribute(attribute.values, attribute.cardinality, attribute.normalized)); } if (data.indices !== null) bufferGeometry.setIndex(new BufferAttribute(data.indices, 1)); return bufferGeometry; } static isBigEndianPlatform() { return isBigEndianPlatform(); } } return PRWMLoader2; })(); //#endregion //#region node_modules/three-stdlib/loaders/RGBMLoader.js var UPNG; function init() { if (UPNG) return UPNG; UPNG = {}; UPNG.toRGBA8 = function(out) { var w = out.width, h = out.height; if (out.tabs.acTL == null) return [UPNG.toRGBA8.decodeImage(out.data, w, h, out).buffer]; var frms = []; if (out.frames[0].data == null) out.frames[0].data = out.data; var len = w * h * 4, img = new Uint8Array(len), empty = new Uint8Array(len), prev = new Uint8Array(len); for (var i = 0; i < out.frames.length; i++) { var frm = out.frames[i]; var fx = frm.rect.x, fy = frm.rect.y, fw = frm.rect.width, fh = frm.rect.height; var fdata = UPNG.toRGBA8.decodeImage(frm.data, fw, fh, out); if (i != 0) for (var j = 0; j < len; j++) prev[j] = img[j]; if (frm.blend == 0) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 0); else if (frm.blend == 1) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 1); frms.push(img.buffer.slice(0)); if (frm.dispose == 1) UPNG._copyTile(empty, fw, fh, img, w, h, fx, fy, 0); else if (frm.dispose == 2) for (var j = 0; j < len; j++) img[j] = prev[j]; } return frms; }; UPNG.toRGBA8.decodeImage = function(data, w, h, out) { var area = w * h, bpp = UPNG.decode._getBPP(out); var bpl = Math.ceil(w * bpp / 8); var bf = new Uint8Array(area * 4), bf32 = new Uint32Array(bf.buffer); var ctype = out.ctype, depth = out.depth; var rs = UPNG._bin.readUshort; if (ctype == 6) { var qarea = area << 2; if (depth == 8) for (var i = 0; i < qarea; i += 4) { bf[i] = data[i]; bf[i + 1] = data[i + 1]; bf[i + 2] = data[i + 2]; bf[i + 3] = data[i + 3]; } if (depth == 16) for (var i = 0; i < qarea; i++) bf[i] = data[i << 1]; } else if (ctype == 2) { var ts = out.tabs["tRNS"]; if (ts == null) { if (depth == 8) for (var i = 0; i < area; i++) { var ti = i * 3; bf32[i] = 255 << 24 | data[ti + 2] << 16 | data[ti + 1] << 8 | data[ti]; } if (depth == 16) for (var i = 0; i < area; i++) { var ti = i * 6; bf32[i] = 255 << 24 | data[ti + 4] << 16 | data[ti + 2] << 8 | data[ti]; } } else { var tr = ts[0], tg = ts[1], tb = ts[2]; if (depth == 8) for (var i = 0; i < area; i++) { var qi = i << 2, ti = i * 3; bf32[i] = 255 << 24 | data[ti + 2] << 16 | data[ti + 1] << 8 | data[ti]; if (data[ti] == tr && data[ti + 1] == tg && data[ti + 2] == tb) bf[qi + 3] = 0; } if (depth == 16) for (var i = 0; i < area; i++) { var qi = i << 2, ti = i * 6; bf32[i] = 255 << 24 | data[ti + 4] << 16 | data[ti + 2] << 8 | data[ti]; if (rs(data, ti) == tr && rs(data, ti + 2) == tg && rs(data, ti + 4) == tb) bf[qi + 3] = 0; } } } else if (ctype == 3) { var p = out.tabs["PLTE"], ap = out.tabs["tRNS"], tl = ap ? ap.length : 0; if (depth == 1) for (var y = 0; y < h; y++) { var s0 = y * bpl, t0 = y * w; for (var i = 0; i < w; i++) { var qi = t0 + i << 2, j = data[s0 + (i >> 3)] >> 7 - ((i & 7) << 0) & 1, cj = 3 * j; bf[qi] = p[cj]; bf[qi + 1] = p[cj + 1]; bf[qi + 2] = p[cj + 2]; bf[qi + 3] = j < tl ? ap[j] : 255; } } if (depth == 2) for (var y = 0; y < h; y++) { var s0 = y * bpl, t0 = y * w; for (var i = 0; i < w; i++) { var qi = t0 + i << 2, j = data[s0 + (i >> 2)] >> 6 - ((i & 3) << 1) & 3, cj = 3 * j; bf[qi] = p[cj]; bf[qi + 1] = p[cj + 1]; bf[qi + 2] = p[cj + 2]; bf[qi + 3] = j < tl ? ap[j] : 255; } } if (depth == 4) for (var y = 0; y < h; y++) { var s0 = y * bpl, t0 = y * w; for (var i = 0; i < w; i++) { var qi = t0 + i << 2, j = data[s0 + (i >> 1)] >> 4 - ((i & 1) << 2) & 15, cj = 3 * j; bf[qi] = p[cj]; bf[qi + 1] = p[cj + 1]; bf[qi + 2] = p[cj + 2]; bf[qi + 3] = j < tl ? ap[j] : 255; } } if (depth == 8) for (var i = 0; i < area; i++) { var qi = i << 2, j = data[i], cj = 3 * j; bf[qi] = p[cj]; bf[qi + 1] = p[cj + 1]; bf[qi + 2] = p[cj + 2]; bf[qi + 3] = j < tl ? ap[j] : 255; } } else if (ctype == 4) { if (depth == 8) for (var i = 0; i < area; i++) { var qi = i << 2, di = i << 1, gr = data[di]; bf[qi] = gr; bf[qi + 1] = gr; bf[qi + 2] = gr; bf[qi + 3] = data[di + 1]; } if (depth == 16) for (var i = 0; i < area; i++) { var qi = i << 2, di = i << 2, gr = data[di]; bf[qi] = gr; bf[qi + 1] = gr; bf[qi + 2] = gr; bf[qi + 3] = data[di + 2]; } } else if (ctype == 0) { var tr = out.tabs["tRNS"] ? out.tabs["tRNS"] : -1; for (var y = 0; y < h; y++) { var off = y * bpl, to = y * w; if (depth == 1) for (var x = 0; x < w; x++) { var gr = 255 * (data[off + (x >>> 3)] >>> 7 - (x & 7) & 1), al = gr == tr * 255 ? 0 : 255; bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; } else if (depth == 2) for (var x = 0; x < w; x++) { var gr = 85 * (data[off + (x >>> 2)] >>> 6 - ((x & 3) << 1) & 3), al = gr == tr * 85 ? 0 : 255; bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; } else if (depth == 4) for (var x = 0; x < w; x++) { var gr = 17 * (data[off + (x >>> 1)] >>> 4 - ((x & 1) << 2) & 15), al = gr == tr * 17 ? 0 : 255; bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; } else if (depth == 8) for (var x = 0; x < w; x++) { var gr = data[off + x], al = gr == tr ? 0 : 255; bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; } else if (depth == 16) for (var x = 0; x < w; x++) { var gr = data[off + (x << 1)], al = rs(data, off + (x << 1)) == tr ? 0 : 255; bf32[to + x] = al << 24 | gr << 16 | gr << 8 | gr; } } } return bf; }; UPNG.decode = function(buff) { var data = new Uint8Array(buff), offset = 8, bin = UPNG._bin, rUs = bin.readUshort, rUi = bin.readUint; var out = { tabs: {}, frames: [] }; var dd = new Uint8Array(data.length), doff = 0; var fd, foff = 0; var text, keyw, bfr; var mgck = [ 137, 80, 78, 71, 13, 10, 26, 10 ]; for (var i = 0; i < 8; i++) if (data[i] != mgck[i]) throw new Error("The input is not a PNG file!"); while (offset < data.length) { var len = bin.readUint(data, offset); offset += 4; var type = bin.readASCII(data, offset, 4); offset += 4; if (type == "IHDR") UPNG.decode._IHDR(data, offset, out); else if (type == "CgBI") out.tabs[type] = data.slice(offset, offset + 4); else if (type == "IDAT") { for (var i = 0; i < len; i++) dd[doff + i] = data[offset + i]; doff += len; } else if (type == "acTL") { out.tabs[type] = { num_frames: rUi(data, offset), num_plays: rUi(data, offset + 4) }; fd = new Uint8Array(data.length); } else if (type == "fcTL") { if (foff != 0) { var fr = out.frames[out.frames.length - 1]; fr.data = UPNG.decode._decompress(out, fd.slice(0, foff), fr.rect.width, fr.rect.height); foff = 0; } var rct = { x: rUi(data, offset + 12), y: rUi(data, offset + 16), width: rUi(data, offset + 4), height: rUi(data, offset + 8) }; var del = rUs(data, offset + 22); del = rUs(data, offset + 20) / (del == 0 ? 100 : del); var frm = { rect: rct, delay: Math.round(del * 1e3), dispose: data[offset + 24], blend: data[offset + 25] }; out.frames.push(frm); } else if (type == "fdAT") { for (var i = 0; i < len - 4; i++) fd[foff + i] = data[offset + i + 4]; foff += len - 4; } else if (type == "pHYs") out.tabs[type] = [ bin.readUint(data, offset), bin.readUint(data, offset + 4), data[offset + 8] ]; else if (type == "cHRM") { out.tabs[type] = []; for (var i = 0; i < 8; i++) out.tabs[type].push(bin.readUint(data, offset + i * 4)); } else if (type == "tEXt" || type == "zTXt") { if (out.tabs[type] == null) out.tabs[type] = {}; var nz = bin.nextZero(data, offset); keyw = bin.readASCII(data, offset, nz - offset); var tl = offset + len - nz - 1; if (type == "tEXt") text = bin.readASCII(data, nz + 1, tl); else { bfr = UPNG.decode._inflate(data.slice(nz + 2, nz + 2 + tl)); text = bin.readUTF8(bfr, 0, bfr.length); } out.tabs[type][keyw] = text; } else if (type == "iTXt") { if (out.tabs[type] == null) out.tabs[type] = {}; var nz = 0, off = offset; nz = bin.nextZero(data, off); keyw = bin.readASCII(data, off, nz - off); off = nz + 1; var cflag = data[off]; off += 2; nz = bin.nextZero(data, off); bin.readASCII(data, off, nz - off); off = nz + 1; nz = bin.nextZero(data, off); bin.readUTF8(data, off, nz - off); off = nz + 1; var tl = len - (off - offset); if (cflag == 0) text = bin.readUTF8(data, off, tl); else { bfr = UPNG.decode._inflate(data.slice(off, off + tl)); text = bin.readUTF8(bfr, 0, bfr.length); } out.tabs[type][keyw] = text; } else if (type == "PLTE") out.tabs[type] = bin.readBytes(data, offset, len); else if (type == "hIST") { var pl = out.tabs["PLTE"].length / 3; out.tabs[type] = []; for (var i = 0; i < pl; i++) out.tabs[type].push(rUs(data, offset + i * 2)); } else if (type == "tRNS") { if (out.ctype == 3) out.tabs[type] = bin.readBytes(data, offset, len); else if (out.ctype == 0) out.tabs[type] = rUs(data, offset); else if (out.ctype == 2) out.tabs[type] = [ rUs(data, offset), rUs(data, offset + 2), rUs(data, offset + 4) ]; } else if (type == "gAMA") out.tabs[type] = bin.readUint(data, offset) / 1e5; else if (type == "sRGB") out.tabs[type] = data[offset]; else if (type == "bKGD") { if (out.ctype == 0 || out.ctype == 4) out.tabs[type] = [rUs(data, offset)]; else if (out.ctype == 2 || out.ctype == 6) out.tabs[type] = [ rUs(data, offset), rUs(data, offset + 2), rUs(data, offset + 4) ]; else if (out.ctype == 3) out.tabs[type] = data[offset]; } else if (type == "IEND") break; offset += len; bin.readUint(data, offset); offset += 4; } if (foff != 0) { var fr = out.frames[out.frames.length - 1]; fr.data = UPNG.decode._decompress(out, fd.slice(0, foff), fr.rect.width, fr.rect.height); } out.data = UPNG.decode._decompress(out, dd, out.width, out.height); delete out.compress; delete out.interlace; delete out.filter; return out; }; UPNG.decode._decompress = function(out, dd, w, h) { var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), buff = new Uint8Array((bpl + 1 + out.interlace) * h); if (out.tabs["CgBI"]) dd = UPNG.inflateRaw(dd, buff); else dd = UPNG.decode._inflate(dd, buff); if (out.interlace == 0) dd = UPNG.decode._filterZero(dd, out, 0, w, h); else if (out.interlace == 1) dd = UPNG.decode._readInterlace(dd, out); return dd; }; UPNG.decode._inflate = function(data, buff) { return UPNG["inflateRaw"](new Uint8Array(data.buffer, 2, data.length - 6), buff); }; UPNG.inflateRaw = function() { var H = {}; H.H = {}; H.H.N = function(N, W) { var R = Uint8Array, i = 0, m = 0, J = 0, h = 0, Q = 0, X = 0, u = 0, w = 0, d = 0, v, C; if (N[0] == 3 && N[1] == 0) return W ? W : new R(0); var V = H.H, n = V.b, A = V.e, l = V.R, M = V.n, I = V.A, e = V.Z, b = V.m, Z = W == null; if (Z) W = new R(N.length >>> 2 << 5); while (i == 0) { i = n(N, d, 1); m = n(N, d + 1, 2); d += 3; if (m == 0) { if ((d & 7) != 0) d += 8 - (d & 7); var D = (d >>> 3) + 4, q = N[D - 4] | N[D - 3] << 8; if (Z) W = H.H.W(W, w + q); W.set(new R(N.buffer, N.byteOffset + D, q), w); d = D + q << 3; w += q; continue; } if (Z) W = H.H.W(W, w + (1 << 17)); if (m == 1) { v = b.J; C = b.h; X = 511; u = 31; } if (m == 2) { J = A(N, d, 5) + 257; h = A(N, d + 5, 5) + 1; Q = A(N, d + 10, 4) + 4; d += 14; var j = 1; for (var c = 0; c < 38; c += 2) { b.Q[c] = 0; b.Q[c + 1] = 0; } for (var c = 0; c < Q; c++) { var K = A(N, d + c * 3, 3); b.Q[(b.X[c] << 1) + 1] = K; if (K > j) j = K; } d += 3 * Q; M(b.Q, j); I(b.Q, j, b.u); v = b.w; C = b.d; d = l(b.u, (1 << j) - 1, J + h, N, d, b.v); var r = V.V(b.v, 0, J, b.C); X = (1 << r) - 1; var S = V.V(b.v, J, h, b.D); u = (1 << S) - 1; M(b.C, r); I(b.C, r, v); M(b.D, S); I(b.D, S, C); } while (true) { var T = v[e(N, d) & X]; d += T & 15; var p = T >>> 4; if (p >>> 8 == 0) W[w++] = p; else if (p == 256) break; else { var z = w + p - 254; if (p > 264) { var _ = b.q[p - 257]; z = w + (_ >>> 3) + A(N, d, _ & 7); d += _ & 7; } var $ = C[e(N, d) & u]; d += $ & 15; var s = $ >>> 4, Y = b.c[s], a = (Y >>> 4) + n(N, d, Y & 15); d += Y & 15; while (w < z) { W[w] = W[w++ - a]; W[w] = W[w++ - a]; W[w] = W[w++ - a]; W[w] = W[w++ - a]; } w = z; } } } return W.length == w ? W : W.slice(0, w); }; H.H.W = function(N, W) { var R = N.length; if (W <= R) return N; var V = new Uint8Array(R << 1); V.set(N, 0); return V; }; H.H.R = function(N, W, R, V, n, A) { var l = H.H.e, M = H.H.Z, I = 0; while (I < R) { var e = N[M(V, n) & W]; n += e & 15; var b = e >>> 4; if (b <= 15) { A[I] = b; I++; } else { var Z = 0, m = 0; if (b == 16) { m = 3 + l(V, n, 2); n += 2; Z = A[I - 1]; } else if (b == 17) { m = 3 + l(V, n, 3); n += 3; } else if (b == 18) { m = 11 + l(V, n, 7); n += 7; } var J = I + m; while (I < J) { A[I] = Z; I++; } } } return n; }; H.H.V = function(N, W, R, V) { var n = 0, A = 0, l = V.length >>> 1; while (A < R) { var M = N[A + W]; V[A << 1] = 0; V[(A << 1) + 1] = M; if (M > n) n = M; A++; } while (A < l) { V[A << 1] = 0; V[(A << 1) + 1] = 0; A++; } return n; }; H.H.n = function(N, W) { var R = H.H.m, V = N.length, n, A, l, M, I, e = R.j; for (var M = 0; M <= W; M++) e[M] = 0; for (M = 1; M < V; M += 2) e[N[M]]++; var b = R.K; n = 0; e[0] = 0; for (A = 1; A <= W; A++) { n = n + e[A - 1] << 1; b[A] = n; } for (l = 0; l < V; l += 2) { I = N[l + 1]; if (I != 0) { N[l] = b[I]; b[I]++; } } }; H.H.A = function(N, W, R) { var V = N.length, A = H.H.m.r; for (var l = 0; l < V; l += 2) if (N[l + 1] != 0) { var M = l >> 1, I = N[l + 1], e = M << 4 | I, b = W - I, Z = N[l] << b, m = Z + (1 << b); while (Z != m) { var J = A[Z] >>> 15 - W; R[J] = e; Z++; } } }; H.H.l = function(N, W) { var R = H.H.m.r, V = 15 - W; for (var n = 0; n < N.length; n += 2) N[n] = R[N[n] << W - N[n + 1]] >>> V; }; H.H.M = function(N, W, R) { R = R << (W & 7); var V = W >>> 3; N[V] |= R; N[V + 1] |= R >>> 8; }; H.H.I = function(N, W, R) { R = R << (W & 7); var V = W >>> 3; N[V] |= R; N[V + 1] |= R >>> 8; N[V + 2] |= R >>> 16; }; H.H.e = function(N, W, R) { return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R) - 1; }; H.H.b = function(N, W, R) { return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R) - 1; }; H.H.Z = function(N, W) { return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7); }; H.H.i = function(N, W) { return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7); }; H.H.m = function() { var N = Uint16Array, W = Uint32Array; return { K: new N(16), j: new N(16), X: [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ], S: [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 999, 999, 999 ], T: [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0 ], q: new N(32), p: [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 65535, 65535 ], z: [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0 ], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(32768), s: new W(286), Y: new W(30), a: new W(19), t: new W(15e3), k: new N(65536), g: new N(32768) }; }(); (function() { var N = H.H.m, W = 32768; for (var R = 0; R < W; R++) { var V = R; V = (V & 2863311530) >>> 1 | (V & 1431655765) << 1; V = (V & 3435973836) >>> 2 | (V & 858993459) << 2; V = (V & 4042322160) >>> 4 | (V & 252645135) << 4; V = (V & 4278255360) >>> 8 | (V & 16711935) << 8; N.r[R] = (V >>> 16 | V << 16) >>> 17; } function n(A, l, M) { while (l-- != 0) A.push(0, M); } for (var R = 0; R < 32; R++) { N.q[R] = N.S[R] << 3 | N.T[R]; N.c[R] = N.p[R] << 4 | N.z[R]; } n(N._, 144, 8); n(N._, 112, 9); n(N._, 24, 7); n(N._, 8, 8); H.H.n(N._, 9); H.H.A(N._, 9, N.J); H.H.l(N._, 9); n(N.$, 32, 5); H.H.n(N.$, 5); H.H.A(N.$, 5, N.h); H.H.l(N.$, 5); n(N.Q, 19, 0); n(N.C, 286, 0); n(N.D, 30, 0); n(N.v, 320, 0); })(); return H.H.N; }(); UPNG.decode._readInterlace = function(data, out) { var w = out.width, h = out.height; var bpp = UPNG.decode._getBPP(out), cbpp = bpp >> 3, bpl = Math.ceil(w * bpp / 8); var img = new Uint8Array(h * bpl); var di = 0; var starting_row = [ 0, 0, 4, 0, 2, 0, 1 ]; var starting_col = [ 0, 4, 0, 2, 0, 1, 0 ]; var row_increment = [ 8, 8, 8, 4, 4, 2, 2 ]; var col_increment = [ 8, 8, 4, 4, 2, 2, 1 ]; var pass = 0; while (pass < 7) { var ri = row_increment[pass], ci = col_increment[pass]; var sw = 0, sh = 0; var cr = starting_row[pass]; while (cr < h) { cr += ri; sh++; } var cc = starting_col[pass]; while (cc < w) { cc += ci; sw++; } var bpll = Math.ceil(sw * bpp / 8); UPNG.decode._filterZero(data, out, di, sw, sh); var y = 0, row = starting_row[pass]; var val; while (row < h) { var col = starting_col[pass]; var cdi = di + y * bpll << 3; while (col < w) { if (bpp == 1) { val = data[cdi >> 3]; val = val >> 7 - (cdi & 7) & 1; img[row * bpl + (col >> 3)] |= val << 7 - ((col & 7) << 0); } if (bpp == 2) { val = data[cdi >> 3]; val = val >> 6 - (cdi & 7) & 3; img[row * bpl + (col >> 2)] |= val << 6 - ((col & 3) << 1); } if (bpp == 4) { val = data[cdi >> 3]; val = val >> 4 - (cdi & 7) & 15; img[row * bpl + (col >> 1)] |= val << 4 - ((col & 1) << 2); } if (bpp >= 8) { var ii = row * bpl + col * cbpp; for (var j = 0; j < cbpp; j++) img[ii + j] = data[(cdi >> 3) + j]; } cdi += bpp; col += ci; } y++; row += ri; } if (sw * sh != 0) di += sh * (1 + bpll); pass = pass + 1; } return img; }; UPNG.decode._getBPP = function(out) { return [ 1, null, 3, 1, 2, null, 4 ][out.ctype] * out.depth; }; UPNG.decode._filterZero = function(data, out, off, w, h) { var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), paeth = UPNG.decode._paeth; bpp = Math.ceil(bpp / 8); var i, di, type = data[off], x = 0; if (type > 1) data[off] = [ 0, 0, 1 ][type - 2]; if (type == 3) for (x = bpp; x < bpl; x++) data[x + 1] = data[x + 1] + (data[x + 1 - bpp] >>> 1) & 255; for (var y = 0; y < h; y++) { i = off + y * bpl; di = i + y + 1; type = data[di - 1]; x = 0; if (type == 0) for (; x < bpl; x++) data[i + x] = data[di + x]; else if (type == 1) { for (; x < bpp; x++) data[i + x] = data[di + x]; for (; x < bpl; x++) data[i + x] = data[di + x] + data[i + x - bpp]; } else if (type == 2) for (; x < bpl; x++) data[i + x] = data[di + x] + data[i + x - bpl]; else if (type == 3) { for (; x < bpp; x++) data[i + x] = data[di + x] + (data[i + x - bpl] >>> 1); for (; x < bpl; x++) data[i + x] = data[di + x] + (data[i + x - bpl] + data[i + x - bpp] >>> 1); } else { for (; x < bpp; x++) data[i + x] = data[di + x] + paeth(0, data[i + x - bpl], 0); for (; x < bpl; x++) data[i + x] = data[di + x] + paeth(data[i + x - bpp], data[i + x - bpl], data[i + x - bpp - bpl]); } } return data; }; UPNG.decode._paeth = function(a, b, c) { var p = a + b - c, pa = p - a, pb = p - b, pc = p - c; if (pa * pa <= pb * pb && pa * pa <= pc * pc) return a; else if (pb * pb <= pc * pc) return b; return c; }; UPNG.decode._IHDR = function(data, offset, out) { var bin = UPNG._bin; out.width = bin.readUint(data, offset); offset += 4; out.height = bin.readUint(data, offset); offset += 4; out.depth = data[offset]; offset++; out.ctype = data[offset]; offset++; out.compress = data[offset]; offset++; out.filter = data[offset]; offset++; out.interlace = data[offset]; offset++; }; UPNG._bin = { nextZero: function(data, p) { while (data[p] != 0) p++; return p; }, readUshort: function(buff, p) { return buff[p] << 8 | buff[p + 1]; }, writeUshort: function(buff, p, n) { buff[p] = n >> 8 & 255; buff[p + 1] = n & 255; }, readUint: function(buff, p) { return buff[p] * (256 * 256 * 256) + (buff[p + 1] << 16 | buff[p + 2] << 8 | buff[p + 3]); }, writeUint: function(buff, p, n) { buff[p] = n >> 24 & 255; buff[p + 1] = n >> 16 & 255; buff[p + 2] = n >> 8 & 255; buff[p + 3] = n & 255; }, readASCII: function(buff, p, l) { var s = ""; for (var i = 0; i < l; i++) s += String.fromCharCode(buff[p + i]); return s; }, writeASCII: function(data, p, s) { for (var i = 0; i < s.length; i++) data[p + i] = s.charCodeAt(i); }, readBytes: function(buff, p, l) { var arr = []; for (var i = 0; i < l; i++) arr.push(buff[p + i]); return arr; }, pad: function(n) { return n.length < 2 ? "0" + n : n; }, readUTF8: function(buff, p, l) { var s = "", ns; for (var i = 0; i < l; i++) s += "%" + UPNG._bin.pad(buff[p + i].toString(16)); try { ns = decodeURIComponent(s); } catch (e) { return UPNG._bin.readASCII(buff, p, l); } return ns; } }; UPNG._copyTile = function(sb, sw, sh, tb, tw, th, xoff, yoff, mode) { var w = Math.min(sw, tw), h = Math.min(sh, th); var si = 0, ti = 0; for (var y = 0; y < h; y++) for (var x = 0; x < w; x++) { if (xoff >= 0 && yoff >= 0) { si = y * sw + x << 2; ti = (yoff + y) * tw + xoff + x << 2; } else { si = (-yoff + y) * sw - xoff + x << 2; ti = y * tw + x << 2; } if (mode == 0) { tb[ti] = sb[si]; tb[ti + 1] = sb[si + 1]; tb[ti + 2] = sb[si + 2]; tb[ti + 3] = sb[si + 3]; } else if (mode == 1) { var fa = sb[si + 3] * (1 / 255), fr = sb[si] * fa, fg = sb[si + 1] * fa, fb = sb[si + 2] * fa; var ba = tb[ti + 3] * (1 / 255), br = tb[ti] * ba, bg = tb[ti + 1] * ba, bb = tb[ti + 2] * ba; var ifa = 1 - fa, oa = fa + ba * ifa, ioa = oa == 0 ? 0 : 1 / oa; tb[ti + 3] = 255 * oa; tb[ti + 0] = (fr + br * ifa) * ioa; tb[ti + 1] = (fg + bg * ifa) * ioa; tb[ti + 2] = (fb + bb * ifa) * ioa; } else if (mode == 2) { var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2]; var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2]; if (fa == ba && fr == br && fg == bg && fb == bb) { tb[ti] = 0; tb[ti + 1] = 0; tb[ti + 2] = 0; tb[ti + 3] = 0; } else { tb[ti] = fr; tb[ti + 1] = fg; tb[ti + 2] = fb; tb[ti + 3] = fa; } } else if (mode == 3) { var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2]; var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2]; if (fa == ba && fr == br && fg == bg && fb == bb) continue; if (fa < 220 && ba > 20) return false; } } return true; }; } var RGBMLoader = class extends DataTextureLoader { constructor(manager) { super(manager); this.type = HalfFloatType; this.maxRange = 7; } setDataType(value) { this.type = value; return this; } setMaxRange(value) { this.maxRange = value; return this; } loadCubemap(urls, onLoad, onProgress, onError) { const texture = new CubeTexture(); let loaded = 0; const scope = this; function loadTexture(i) { scope.load(urls[i], function(image) { texture.images[i] = image; loaded++; if (loaded === 6) { texture.needsUpdate = true; if (onLoad) onLoad(texture); } }, void 0, onError); } for (let i = 0; i < urls.length; ++i) loadTexture(i); texture.type = this.type; texture.format = RGBAFormat; texture.minFilter = LinearFilter; texture.generateMipmaps = false; return texture; } parse(buffer) { init(); const img = UPNG.decode(buffer); const rgba = UPNG.toRGBA8(img)[0]; const data = new Uint8Array(rgba); const size = img.width * img.height * 4; const output = this.type === 1016 ? new Uint16Array(size) : new Float32Array(size); for (let i = 0; i < data.length; i += 4) { const r = data[i + 0] / 255; const g = data[i + 1] / 255; const b = data[i + 2] / 255; const a = data[i + 3] / 255; if (this.type === 1016) { output[i + 0] = DataUtils.toHalfFloat(Math.min(r * a * this.maxRange, 65504)); output[i + 1] = DataUtils.toHalfFloat(Math.min(g * a * this.maxRange, 65504)); output[i + 2] = DataUtils.toHalfFloat(Math.min(b * a * this.maxRange, 65504)); output[i + 3] = DataUtils.toHalfFloat(1); } else { output[i + 0] = r * a * this.maxRange; output[i + 1] = g * a * this.maxRange; output[i + 2] = b * a * this.maxRange; output[i + 3] = 1; } } return { width: img.width, height: img.height, data: output, format: RGBAFormat, type: this.type, flipY: true }; } }; //#endregion //#region node_modules/three-stdlib/loaders/VOXLoader.js var VOXLoader = class extends Loader { load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.load(url, function(buffer) { try { onLoad(scope.parse(buffer)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(buffer) { const data = new DataView(buffer); const id = data.getUint32(0, true); const version = data.getUint32(4, true); if (id !== 542658390 || version !== 150) { console.error("Not a valid VOX file"); return; } const DEFAULT_PALETTE = [ 0, 4294967295, 4291624959, 4288282623, 4284940287, 4281597951, 4278255615, 4294954239, 4291611903, 4288269567, 4284927231, 4281584895, 4278242559, 4294941183, 4291598847, 4288256511, 4284914175, 4281571839, 4278229503, 4294928127, 4291585791, 4288243455, 4284901119, 4281558783, 4278216447, 4294915071, 4291572735, 4288230399, 4284888063, 4281545727, 4278203391, 4294902015, 4291559679, 4288217343, 4284875007, 4281532671, 4278190335, 4294967244, 4291624908, 4288282572, 4284940236, 4281597900, 4278255564, 4294954188, 4291611852, 4288269516, 4284927180, 4281584844, 4278242508, 4294941132, 4291598796, 4288256460, 4284914124, 4281571788, 4278229452, 4294928076, 4291585740, 4288243404, 4284901068, 4281558732, 4278216396, 4294915020, 4291572684, 4288230348, 4284888012, 4281545676, 4278203340, 4294901964, 4291559628, 4288217292, 4284874956, 4281532620, 4278190284, 4294967193, 4291624857, 4288282521, 4284940185, 4281597849, 4278255513, 4294954137, 4291611801, 4288269465, 4284927129, 4281584793, 4278242457, 4294941081, 4291598745, 4288256409, 4284914073, 4281571737, 4278229401, 4294928025, 4291585689, 4288243353, 4284901017, 4281558681, 4278216345, 4294914969, 4291572633, 4288230297, 4284887961, 4281545625, 4278203289, 4294901913, 4291559577, 4288217241, 4284874905, 4281532569, 4278190233, 4294967142, 4291624806, 4288282470, 4284940134, 4281597798, 4278255462, 4294954086, 4291611750, 4288269414, 4284927078, 4281584742, 4278242406, 4294941030, 4291598694, 4288256358, 4284914022, 4281571686, 4278229350, 4294927974, 4291585638, 4288243302, 4284900966, 4281558630, 4278216294, 4294914918, 4291572582, 4288230246, 4284887910, 4281545574, 4278203238, 4294901862, 4291559526, 4288217190, 4284874854, 4281532518, 4278190182, 4294967091, 4291624755, 4288282419, 4284940083, 4281597747, 4278255411, 4294954035, 4291611699, 4288269363, 4284927027, 4281584691, 4278242355, 4294940979, 4291598643, 4288256307, 4284913971, 4281571635, 4278229299, 4294927923, 4291585587, 4288243251, 4284900915, 4281558579, 4278216243, 4294914867, 4291572531, 4288230195, 4284887859, 4281545523, 4278203187, 4294901811, 4291559475, 4288217139, 4284874803, 4281532467, 4278190131, 4294967040, 4291624704, 4288282368, 4284940032, 4281597696, 4278255360, 4294953984, 4291611648, 4288269312, 4284926976, 4281584640, 4278242304, 4294940928, 4291598592, 4288256256, 4284913920, 4281571584, 4278229248, 4294927872, 4291585536, 4288243200, 4284900864, 4281558528, 4278216192, 4294914816, 4291572480, 4288230144, 4284887808, 4281545472, 4278203136, 4294901760, 4291559424, 4288217088, 4284874752, 4281532416, 4278190318, 4278190301, 4278190267, 4278190250, 4278190216, 4278190199, 4278190165, 4278190148, 4278190114, 4278190097, 4278251008, 4278246656, 4278237952, 4278233600, 4278224896, 4278220544, 4278211840, 4278207488, 4278198784, 4278194432, 4293787648, 4292673536, 4290445312, 4289331200, 4287102976, 4285988864, 4283760640, 4282646528, 4280418304, 4279304192, 4293848814, 4292730333, 4290493371, 4289374890, 4287137928, 4286019447, 4283782485, 4282664004, 4280427042, 4279308561 ]; let i = 8; let chunk; const chunks = []; while (i < data.byteLength) { let id2 = ""; for (let j = 0; j < 4; j++) id2 += String.fromCharCode(data.getUint8(i++)); const chunkSize = data.getUint32(i, true); i += 4; i += 4; if (id2 === "SIZE") { const x = data.getUint32(i, true); i += 4; const y = data.getUint32(i, true); i += 4; const z = data.getUint32(i, true); i += 4; chunk = { palette: DEFAULT_PALETTE, size: { x, y, z } }; chunks.push(chunk); i += chunkSize - 12; } else if (id2 === "XYZI") { const numVoxels = data.getUint32(i, true); i += 4; chunk.data = new Uint8Array(buffer, i, numVoxels * 4); i += numVoxels * 4; } else if (id2 === "RGBA") { const palette = [0]; for (let j = 0; j < 256; j++) { palette[j + 1] = data.getUint32(i, true); i += 4; } chunk.palette = palette; } else i += chunkSize; } return chunks; } }; var VOXMesh = class extends Mesh { constructor(chunk) { const data = chunk.data; const size = chunk.size; const palette = chunk.palette; const vertices = []; const colors = []; const nx = [ 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1 ]; const px = [ 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0 ]; const py = [ 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1 ]; const ny = [ 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0 ]; const nz = [ 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0 ]; const pz = [ 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1 ]; function add(tile, x, y, z, r, g, b) { x -= size.x / 2; y -= size.z / 2; z += size.y / 2; for (let i = 0; i < 18; i += 3) { vertices.push(tile[i + 0] + x, tile[i + 1] + y, tile[i + 2] + z); colors.push(r, g, b); } } const offsety = size.x; const offsetz = size.x * size.y; const array = new Uint8Array(size.x * size.y * size.z); for (let j = 0; j < data.length; j += 4) { const x = data[j + 0]; const y = data[j + 1]; const z = data[j + 2]; const index = x + y * offsety + z * offsetz; array[index] = 255; } let hasColors = false; for (let j = 0; j < data.length; j += 4) { const x = data[j + 0]; const y = data[j + 1]; const z = data[j + 2]; const hex = palette[data[j + 3]]; const r = (hex >> 0 & 255) / 255; const g = (hex >> 8 & 255) / 255; const b = (hex >> 16 & 255) / 255; if (r > 0 || g > 0 || b > 0) hasColors = true; const index = x + y * offsety + z * offsetz; if (array[index + 1] === 0 || x === size.x - 1) add(px, x, z, -y, r, g, b); if (array[index - 1] === 0 || x === 0) add(nx, x, z, -y, r, g, b); if (array[index + offsety] === 0 || y === size.y - 1) add(ny, x, z, -y, r, g, b); if (array[index - offsety] === 0 || y === 0) add(py, x, z, -y, r, g, b); if (array[index + offsetz] === 0 || z === size.z - 1) add(pz, x, z, -y, r, g, b); if (array[index - offsetz] === 0 || z === 0) add(nz, x, z, -y, r, g, b); } const geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); geometry.computeVertexNormals(); const material = new MeshStandardMaterial(); if (hasColors) { geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); material.vertexColors = true; } super(geometry, material); } }; var VOXData3DTexture = class extends Data3DTexture { constructor(chunk) { const data = chunk.data; const size = chunk.size; const offsety = size.x; const offsetz = size.x * size.y; const array = new Uint8Array(size.x * size.y * size.z); for (let j = 0; j < data.length; j += 4) { const x = data[j + 0]; const y = data[j + 1]; const z = data[j + 2]; const index = x + y * offsety + z * offsetz; array[index] = 255; } super(array, size.x, size.y, size.z); this.format = RedFormat; this.minFilter = NearestFilter; this.magFilter = LinearFilter; this.unpackAlignment = 1; this.needsUpdate = true; } }; //#endregion //#region node_modules/three-stdlib/loaders/PCDLoader.js var PCDLoader = class extends Loader { constructor(manager) { super(manager); this.littleEndian = true; } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(scope.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(scope.requestHeader); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(data) { try { onLoad(scope.parse(data, url)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(data, url) { function decompressLZF(inData, outLength) { const inLength = inData.length; const outData = new Uint8Array(outLength); let inPtr = 0; let outPtr = 0; let ctrl; let len; let ref; do { ctrl = inData[inPtr++]; if (ctrl < 32) { ctrl++; if (outPtr + ctrl > outLength) throw new Error("Output buffer is not large enough"); if (inPtr + ctrl > inLength) throw new Error("Invalid compressed data"); do outData[outPtr++] = inData[inPtr++]; while (--ctrl); } else { len = ctrl >> 5; ref = outPtr - ((ctrl & 31) << 8) - 1; if (inPtr >= inLength) throw new Error("Invalid compressed data"); if (len === 7) { len += inData[inPtr++]; if (inPtr >= inLength) throw new Error("Invalid compressed data"); } ref -= inData[inPtr++]; if (outPtr + len + 2 > outLength) throw new Error("Output buffer is not large enough"); if (ref < 0) throw new Error("Invalid compressed data"); if (ref >= outPtr) throw new Error("Invalid compressed data"); do outData[outPtr++] = outData[ref++]; while (--len + 2); } } while (inPtr < inLength); return outData; } function parseHeader(data2) { const PCDheader2 = {}; const result1 = data2.search(/[\r\n]DATA\s(\S*)\s/i); const result2 = /[\r\n]DATA\s(\S*)\s/i.exec(data2.substr(result1 - 1)); PCDheader2.data = result2[1]; PCDheader2.headerLen = result2[0].length + result1; PCDheader2.str = data2.substr(0, PCDheader2.headerLen); PCDheader2.str = PCDheader2.str.replace(/\#.*/gi, ""); PCDheader2.version = /VERSION (.*)/i.exec(PCDheader2.str); PCDheader2.fields = /FIELDS (.*)/i.exec(PCDheader2.str); PCDheader2.size = /SIZE (.*)/i.exec(PCDheader2.str); PCDheader2.type = /TYPE (.*)/i.exec(PCDheader2.str); PCDheader2.count = /COUNT (.*)/i.exec(PCDheader2.str); PCDheader2.width = /WIDTH (.*)/i.exec(PCDheader2.str); PCDheader2.height = /HEIGHT (.*)/i.exec(PCDheader2.str); PCDheader2.viewpoint = /VIEWPOINT (.*)/i.exec(PCDheader2.str); PCDheader2.points = /POINTS (.*)/i.exec(PCDheader2.str); if (PCDheader2.version !== null) PCDheader2.version = parseFloat(PCDheader2.version[1]); if (PCDheader2.fields !== null) PCDheader2.fields = PCDheader2.fields[1].split(" "); if (PCDheader2.type !== null) PCDheader2.type = PCDheader2.type[1].split(" "); if (PCDheader2.width !== null) PCDheader2.width = parseInt(PCDheader2.width[1]); if (PCDheader2.height !== null) PCDheader2.height = parseInt(PCDheader2.height[1]); if (PCDheader2.viewpoint !== null) PCDheader2.viewpoint = PCDheader2.viewpoint[1]; if (PCDheader2.points !== null) PCDheader2.points = parseInt(PCDheader2.points[1], 10); if (PCDheader2.points === null) PCDheader2.points = PCDheader2.width * PCDheader2.height; if (PCDheader2.size !== null) PCDheader2.size = PCDheader2.size[1].split(" ").map(function(x) { return parseInt(x, 10); }); if (PCDheader2.count !== null) PCDheader2.count = PCDheader2.count[1].split(" ").map(function(x) { return parseInt(x, 10); }); else { PCDheader2.count = []; for (let i = 0, l = PCDheader2.fields.length; i < l; i++) PCDheader2.count.push(1); } PCDheader2.offset = {}; let sizeSum = 0; for (let i = 0, l = PCDheader2.fields.length; i < l; i++) if (PCDheader2.data === "ascii") PCDheader2.offset[PCDheader2.fields[i]] = i; else { PCDheader2.offset[PCDheader2.fields[i]] = sizeSum; sizeSum += PCDheader2.size[i] * PCDheader2.count[i]; } PCDheader2.rowSize = sizeSum; return PCDheader2; } const textData = decodeText$1(new Uint8Array(data)); const PCDheader = parseHeader(textData); const position = []; const normal = []; const color = []; if (PCDheader.data === "ascii") { const offset = PCDheader.offset; const lines = textData.substr(PCDheader.headerLen).split("\n"); for (let i = 0, l = lines.length; i < l; i++) { if (lines[i] === "") continue; const line = lines[i].split(" "); if (offset.x !== void 0) { position.push(parseFloat(line[offset.x])); position.push(parseFloat(line[offset.y])); position.push(parseFloat(line[offset.z])); } if (offset.rgb !== void 0) { const rgb = parseFloat(line[offset.rgb]); const r = rgb >> 16 & 255; const g = rgb >> 8 & 255; const b = rgb >> 0 & 255; color.push(r / 255, g / 255, b / 255); } if (offset.normal_x !== void 0) { normal.push(parseFloat(line[offset.normal_x])); normal.push(parseFloat(line[offset.normal_y])); normal.push(parseFloat(line[offset.normal_z])); } } } if (PCDheader.data === "binary_compressed") { const sizes = new Uint32Array(data.slice(PCDheader.headerLen, PCDheader.headerLen + 8)); const compressedSize = sizes[0]; const decompressedSize = sizes[1]; const decompressed = decompressLZF(new Uint8Array(data, PCDheader.headerLen + 8, compressedSize), decompressedSize); const dataview = new DataView(decompressed.buffer); const offset = PCDheader.offset; for (let i = 0; i < PCDheader.points; i++) { if (offset.x !== void 0) { position.push(dataview.getFloat32(PCDheader.points * offset.x + PCDheader.size[0] * i, this.littleEndian)); position.push(dataview.getFloat32(PCDheader.points * offset.y + PCDheader.size[1] * i, this.littleEndian)); position.push(dataview.getFloat32(PCDheader.points * offset.z + PCDheader.size[2] * i, this.littleEndian)); } if (offset.rgb !== void 0) { color.push(dataview.getUint8(PCDheader.points * offset.rgb + PCDheader.size[3] * i + 2) / 255); color.push(dataview.getUint8(PCDheader.points * offset.rgb + PCDheader.size[3] * i + 1) / 255); color.push(dataview.getUint8(PCDheader.points * offset.rgb + PCDheader.size[3] * i + 0) / 255); } if (offset.normal_x !== void 0) { normal.push(dataview.getFloat32(PCDheader.points * offset.normal_x + PCDheader.size[4] * i, this.littleEndian)); normal.push(dataview.getFloat32(PCDheader.points * offset.normal_y + PCDheader.size[5] * i, this.littleEndian)); normal.push(dataview.getFloat32(PCDheader.points * offset.normal_z + PCDheader.size[6] * i, this.littleEndian)); } } } if (PCDheader.data === "binary") { const dataview = new DataView(data, PCDheader.headerLen); const offset = PCDheader.offset; for (let i = 0, row = 0; i < PCDheader.points; i++, row += PCDheader.rowSize) { if (offset.x !== void 0) { position.push(dataview.getFloat32(row + offset.x, this.littleEndian)); position.push(dataview.getFloat32(row + offset.y, this.littleEndian)); position.push(dataview.getFloat32(row + offset.z, this.littleEndian)); } if (offset.rgb !== void 0) { color.push(dataview.getUint8(row + offset.rgb + 2) / 255); color.push(dataview.getUint8(row + offset.rgb + 1) / 255); color.push(dataview.getUint8(row + offset.rgb + 0) / 255); } if (offset.normal_x !== void 0) { normal.push(dataview.getFloat32(row + offset.normal_x, this.littleEndian)); normal.push(dataview.getFloat32(row + offset.normal_y, this.littleEndian)); normal.push(dataview.getFloat32(row + offset.normal_z, this.littleEndian)); } } } const geometry = new BufferGeometry(); if (position.length > 0) geometry.setAttribute("position", new Float32BufferAttribute(position, 3)); if (normal.length > 0) geometry.setAttribute("normal", new Float32BufferAttribute(normal, 3)); if (color.length > 0) geometry.setAttribute("color", new Float32BufferAttribute(color, 3)); geometry.computeBoundingSphere(); const material = new PointsMaterial({ size: .005 }); if (color.length > 0) material.vertexColors = true; else material.color.setHex(Math.random() * 16777215); const mesh = new Points(geometry, material); let name = url.split("").reverse().join(""); name = /([^\/]*)/.exec(name); name = name[1].split("").reverse().join(""); mesh.name = name; return mesh; } }; //#endregion //#region node_modules/three-stdlib/loaders/lwo/LWO2Parser.js var LWO2Parser = class { constructor(IFFParser) { this.IFF = IFFParser; } parseBlock() { this.IFF.debugger.offset = this.IFF.reader.offset; this.IFF.debugger.closeForms(); const blockID = this.IFF.reader.getIDTag(); let length = this.IFF.reader.getUint32(); if (length > this.IFF.reader.dv.byteLength - this.IFF.reader.offset) { this.IFF.reader.offset -= 4; length = this.IFF.reader.getUint16(); } this.IFF.debugger.dataOffset = this.IFF.reader.offset; this.IFF.debugger.length = length; switch (blockID) { case "FORM": this.IFF.parseForm(length); break; case "ICON": case "VMPA": case "BBOX": case "NORM": case "PRE ": case "POST": case "KEY ": case "SPAN": case "TIME": case "CLRS": case "CLRA": case "FILT": case "DITH": case "CONT": case "BRIT": case "SATR": case "HUE ": case "GAMM": case "NEGA": case "IFLT": case "PFLT": case "PROJ": case "AXIS": case "AAST": case "PIXB": case "AUVO": case "STCK": case "PROC": case "VALU": case "FUNC": case "PNAM": case "INAM": case "GRST": case "GREN": case "GRPT": case "FKEY": case "IKEY": case "CSYS": case "OPAQ": case "CMAP": case "NLOC": case "NZOM": case "NVER": case "NSRV": case "NVSK": case "NCRD": case "WRPW": case "WRPH": case "NMOD": case "NSEL": case "NPRW": case "NPLA": case "NODS": case "VERS": case "ENUM": case "TAG ": case "OPAC": case "CGMD": case "CGTY": case "CGST": case "CGEN": case "CGTS": case "CGTE": case "OSMP": case "OMDE": case "OUTR": case "FLAG": case "TRNL": case "GLOW": case "GVAL": case "SHRP": case "RFOP": case "RSAN": case "TROP": case "RBLR": case "TBLR": case "CLRH": case "CLRF": case "ADTR": case "LINE": case "ALPH": case "VCOL": case "ENAB": this.IFF.debugger.skipped = true; this.IFF.reader.skip(length); break; case "SURF": this.IFF.parseSurfaceLwo2(length); break; case "CLIP": this.IFF.parseClipLwo2(length); break; case "IPIX": case "IMIP": case "IMOD": case "AMOD": case "IINV": case "INCR": case "IAXS": case "IFOT": case "ITIM": case "IWRL": case "IUTI": case "IINX": case "IINY": case "IINZ": case "IREF": if (length === 4) this.IFF.currentNode[blockID] = this.IFF.reader.getInt32(); else this.IFF.reader.skip(length); break; case "OTAG": this.IFF.parseObjectTag(); break; case "LAYR": this.IFF.parseLayer(length); break; case "PNTS": this.IFF.parsePoints(length); break; case "VMAP": this.IFF.parseVertexMapping(length); break; case "AUVU": case "AUVN": this.IFF.reader.skip(length - 1); this.IFF.reader.getVariableLengthIndex(); break; case "POLS": this.IFF.parsePolygonList(length); break; case "TAGS": this.IFF.parseTagStrings(length); break; case "PTAG": this.IFF.parsePolygonTagMapping(length); break; case "VMAD": this.IFF.parseVertexMapping(length, true); break; case "DESC": this.IFF.currentForm.description = this.IFF.reader.getString(); break; case "TEXT": case "CMNT": case "NCOM": this.IFF.currentForm.comment = this.IFF.reader.getString(); break; case "NAME": this.IFF.currentForm.channelName = this.IFF.reader.getString(); break; case "WRAP": this.IFF.currentForm.wrap = { w: this.IFF.reader.getUint16(), h: this.IFF.reader.getUint16() }; break; case "IMAG": const index = this.IFF.reader.getVariableLengthIndex(); this.IFF.currentForm.imageIndex = index; break; case "OREF": this.IFF.currentForm.referenceObject = this.IFF.reader.getString(); break; case "ROID": this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32(); break; case "SSHN": this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString(); break; case "AOVN": this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString(); break; case "NSTA": this.IFF.currentForm.disabled = this.IFF.reader.getUint16(); break; case "NRNM": this.IFF.currentForm.realName = this.IFF.reader.getString(); break; case "NNME": this.IFF.currentForm.refName = this.IFF.reader.getString(); this.IFF.currentSurface.nodes[this.IFF.currentForm.refName] = this.IFF.currentForm; break; case "INME": if (!this.IFF.currentForm.nodeName) this.IFF.currentForm.nodeName = []; this.IFF.currentForm.nodeName.push(this.IFF.reader.getString()); break; case "IINN": if (!this.IFF.currentForm.inputNodeName) this.IFF.currentForm.inputNodeName = []; this.IFF.currentForm.inputNodeName.push(this.IFF.reader.getString()); break; case "IINM": if (!this.IFF.currentForm.inputName) this.IFF.currentForm.inputName = []; this.IFF.currentForm.inputName.push(this.IFF.reader.getString()); break; case "IONM": if (!this.IFF.currentForm.inputOutputName) this.IFF.currentForm.inputOutputName = []; this.IFF.currentForm.inputOutputName.push(this.IFF.reader.getString()); break; case "FNAM": this.IFF.currentForm.fileName = this.IFF.reader.getString(); break; case "CHAN": if (length === 4) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag(); else this.IFF.reader.skip(length); break; case "SMAN": const maxSmoothingAngle = this.IFF.reader.getFloat32(); this.IFF.currentSurface.attributes.smooth = maxSmoothingAngle < 0 ? false : true; break; case "COLR": this.IFF.currentSurface.attributes.Color = { value: this.IFF.reader.getFloat32Array(3) }; this.IFF.reader.skip(2); break; case "LUMI": this.IFF.currentSurface.attributes.Luminosity = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "SPEC": this.IFF.currentSurface.attributes.Specular = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "DIFF": this.IFF.currentSurface.attributes.Diffuse = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "REFL": this.IFF.currentSurface.attributes.Reflection = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "GLOS": this.IFF.currentSurface.attributes.Glossiness = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "TRAN": this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32(); this.IFF.reader.skip(2); break; case "BUMP": this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32(); this.IFF.reader.skip(2); break; case "SIDE": this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16(); break; case "RIMG": this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex(); break; case "RIND": this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32(); this.IFF.reader.skip(2); break; case "TIMG": this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex(); break; case "IMAP": this.IFF.reader.skip(2); break; case "TMAP": this.IFF.debugger.skipped = true; this.IFF.reader.skip(length); break; case "IUVI": this.IFF.currentNode.UVChannel = this.IFF.reader.getString(length); break; case "IUTL": this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32(); break; case "IVTL": this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32(); break; case "BLOK": break; default: this.IFF.parseUnknownCHUNK(blockID, length); } if (blockID != "FORM") { this.IFF.debugger.node = 1; this.IFF.debugger.nodeID = blockID; this.IFF.debugger.log(); } if (this.IFF.reader.offset >= this.IFF.currentFormEnd) this.IFF.currentForm = this.IFF.parentForm; } }; //#endregion //#region node_modules/three-stdlib/loaders/lwo/LWO3Parser.js var LWO3Parser = class { constructor(IFFParser) { this.IFF = IFFParser; } parseBlock() { this.IFF.debugger.offset = this.IFF.reader.offset; this.IFF.debugger.closeForms(); const blockID = this.IFF.reader.getIDTag(); const length = this.IFF.reader.getUint32(); this.IFF.debugger.dataOffset = this.IFF.reader.offset; this.IFF.debugger.length = length; switch (blockID) { case "FORM": this.IFF.parseForm(length); break; case "ICON": case "VMPA": case "BBOX": case "NORM": case "PRE ": case "POST": case "KEY ": case "SPAN": case "TIME": case "CLRS": case "CLRA": case "FILT": case "DITH": case "CONT": case "BRIT": case "SATR": case "HUE ": case "GAMM": case "NEGA": case "IFLT": case "PFLT": case "PROJ": case "AXIS": case "AAST": case "PIXB": case "STCK": case "VALU": case "PNAM": case "INAM": case "GRST": case "GREN": case "GRPT": case "FKEY": case "IKEY": case "CSYS": case "OPAQ": case "CMAP": case "NLOC": case "NZOM": case "NVER": case "NSRV": case "NCRD": case "NMOD": case "NSEL": case "NPRW": case "NPLA": case "VERS": case "ENUM": case "TAG ": case "CGMD": case "CGTY": case "CGST": case "CGEN": case "CGTS": case "CGTE": case "OSMP": case "OMDE": case "OUTR": case "FLAG": case "TRNL": case "SHRP": case "RFOP": case "RSAN": case "TROP": case "RBLR": case "TBLR": case "CLRH": case "CLRF": case "ADTR": case "GLOW": case "LINE": case "ALPH": case "VCOL": case "ENAB": this.IFF.debugger.skipped = true; this.IFF.reader.skip(length); break; case "IPIX": case "IMIP": case "IMOD": case "AMOD": case "IINV": case "INCR": case "IAXS": case "IFOT": case "ITIM": case "IWRL": case "IUTI": case "IINX": case "IINY": case "IINZ": case "IREF": if (length === 4) this.IFF.currentNode[blockID] = this.IFF.reader.getInt32(); else this.IFF.reader.skip(length); break; case "OTAG": this.IFF.parseObjectTag(); break; case "LAYR": this.IFF.parseLayer(length); break; case "PNTS": this.IFF.parsePoints(length); break; case "VMAP": this.IFF.parseVertexMapping(length); break; case "POLS": this.IFF.parsePolygonList(length); break; case "TAGS": this.IFF.parseTagStrings(length); break; case "PTAG": this.IFF.parsePolygonTagMapping(length); break; case "VMAD": this.IFF.parseVertexMapping(length, true); break; case "DESC": this.IFF.currentForm.description = this.IFF.reader.getString(); break; case "TEXT": case "CMNT": case "NCOM": this.IFF.currentForm.comment = this.IFF.reader.getString(); break; case "NAME": this.IFF.currentForm.channelName = this.IFF.reader.getString(); break; case "WRAP": this.IFF.currentForm.wrap = { w: this.IFF.reader.getUint16(), h: this.IFF.reader.getUint16() }; break; case "IMAG": const index = this.IFF.reader.getVariableLengthIndex(); this.IFF.currentForm.imageIndex = index; break; case "OREF": this.IFF.currentForm.referenceObject = this.IFF.reader.getString(); break; case "ROID": this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32(); break; case "SSHN": this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString(); break; case "AOVN": this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString(); break; case "NSTA": this.IFF.currentForm.disabled = this.IFF.reader.getUint16(); break; case "NRNM": this.IFF.currentForm.realName = this.IFF.reader.getString(); break; case "NNME": this.IFF.currentForm.refName = this.IFF.reader.getString(); this.IFF.currentSurface.nodes[this.IFF.currentForm.refName] = this.IFF.currentForm; break; case "INME": if (!this.IFF.currentForm.nodeName) this.IFF.currentForm.nodeName = []; this.IFF.currentForm.nodeName.push(this.IFF.reader.getString()); break; case "IINN": if (!this.IFF.currentForm.inputNodeName) this.IFF.currentForm.inputNodeName = []; this.IFF.currentForm.inputNodeName.push(this.IFF.reader.getString()); break; case "IINM": if (!this.IFF.currentForm.inputName) this.IFF.currentForm.inputName = []; this.IFF.currentForm.inputName.push(this.IFF.reader.getString()); break; case "IONM": if (!this.IFF.currentForm.inputOutputName) this.IFF.currentForm.inputOutputName = []; this.IFF.currentForm.inputOutputName.push(this.IFF.reader.getString()); break; case "FNAM": this.IFF.currentForm.fileName = this.IFF.reader.getString(); break; case "CHAN": if (length === 4) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag(); else this.IFF.reader.skip(length); break; case "SMAN": const maxSmoothingAngle = this.IFF.reader.getFloat32(); this.IFF.currentSurface.attributes.smooth = maxSmoothingAngle < 0 ? false : true; break; case "COLR": this.IFF.currentSurface.attributes.Color = { value: this.IFF.reader.getFloat32Array(3) }; this.IFF.reader.skip(2); break; case "LUMI": this.IFF.currentSurface.attributes.Luminosity = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "SPEC": this.IFF.currentSurface.attributes.Specular = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "DIFF": this.IFF.currentSurface.attributes.Diffuse = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "REFL": this.IFF.currentSurface.attributes.Reflection = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "GLOS": this.IFF.currentSurface.attributes.Glossiness = { value: this.IFF.reader.getFloat32() }; this.IFF.reader.skip(2); break; case "TRAN": this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32(); this.IFF.reader.skip(2); break; case "BUMP": this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32(); this.IFF.reader.skip(2); break; case "SIDE": this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16(); break; case "RIMG": this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex(); break; case "RIND": this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32(); this.IFF.reader.skip(2); break; case "TIMG": this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex(); break; case "IMAP": this.IFF.currentSurface.attributes.imageMapIndex = this.IFF.reader.getUint32(); break; case "IUVI": this.IFF.currentNode.UVChannel = this.IFF.reader.getString(length); break; case "IUTL": this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32(); break; case "IVTL": this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32(); break; default: this.IFF.parseUnknownCHUNK(blockID, length); } if (blockID != "FORM") { this.IFF.debugger.node = 1; this.IFF.debugger.nodeID = blockID; this.IFF.debugger.log(); } if (this.IFF.reader.offset >= this.IFF.currentFormEnd) this.IFF.currentForm = this.IFF.parentForm; } }; //#endregion //#region node_modules/three-stdlib/loaders/lwo/IFFParser.js var IFFParser = class { constructor() { this.debugger = new Debugger(); } parse(buffer) { this.reader = new DataViewReader(buffer); this.tree = { materials: {}, layers: [], tags: [], textures: [] }; this.currentLayer = this.tree; this.currentForm = this.tree; this.parseTopForm(); if (this.tree.format === void 0) return; if (this.tree.format === "LWO2") { this.parser = new LWO2Parser(this); while (!this.reader.endOfFile()) this.parser.parseBlock(); } else if (this.tree.format === "LWO3") { this.parser = new LWO3Parser(this); while (!this.reader.endOfFile()) this.parser.parseBlock(); } this.debugger.offset = this.reader.offset; this.debugger.closeForms(); return this.tree; } parseTopForm() { this.debugger.offset = this.reader.offset; if (this.reader.getIDTag() !== "FORM") { console.warn("LWOLoader: Top-level FORM missing."); return; } var length = this.reader.getUint32(); this.debugger.dataOffset = this.reader.offset; this.debugger.length = length; var type = this.reader.getIDTag(); if (type === "LWO2") this.tree.format = type; else if (type === "LWO3") this.tree.format = type; this.debugger.node = 0; this.debugger.nodeID = type; this.debugger.log(); } parseForm(length) { var type = this.reader.getIDTag(); switch (type) { case "ISEQ": case "ANIM": case "STCC": case "VPVL": case "VPRM": case "NROT": case "WRPW": case "WRPH": case "FUNC": case "FALL": case "OPAC": case "GRAD": case "ENVS": case "VMOP": case "VMBG": case "OMAX": case "STEX": case "CKBG": case "CKEY": case "VMLA": case "VMLB": this.debugger.skipped = true; this.skipForm(length); break; case "META": case "NNDS": case "NODS": case "NDTA": case "ADAT": case "AOVS": case "BLOK": case "IBGC": case "IOPC": case "IIMG": case "TXTR": this.debugger.length = 4; this.debugger.skipped = true; break; case "IFAL": case "ISCL": case "IPOS": case "IROT": case "IBMP": case "IUTD": case "IVTD": this.parseTextureNodeAttribute(type); break; case "ENVL": this.parseEnvelope(length); break; case "CLIP": if (this.tree.format === "LWO2") this.parseForm(length); else this.parseClip(length); break; case "STIL": this.parseImage(); break; case "XREF": this.reader.skip(8); this.currentForm.referenceTexture = { index: this.reader.getUint32(), refName: this.reader.getString() }; break; case "IMST": this.parseImageStateForm(length); break; case "SURF": this.parseSurfaceForm(length); break; case "VALU": this.parseValueForm(length); break; case "NTAG": this.parseSubNode(length); break; case "ATTR": case "SATR": this.setupForm("attributes", length); break; case "NCON": this.parseConnections(length); break; case "SSHA": this.parentForm = this.currentForm; this.currentForm = this.currentSurface; this.setupForm("surfaceShader", length); break; case "SSHD": this.setupForm("surfaceShaderData", length); break; case "ENTR": this.parseEntryForm(length); break; case "IMAP": this.parseImageMap(length); break; case "TAMP": this.parseXVAL("amplitude", length); break; case "TMAP": this.setupForm("textureMap", length); break; case "CNTR": this.parseXVAL3("center", length); break; case "SIZE": this.parseXVAL3("scale", length); break; case "ROTA": this.parseXVAL3("rotation", length); break; default: this.parseUnknownForm(type, length); } this.debugger.node = 0; this.debugger.nodeID = type; this.debugger.log(); } setupForm(type, length) { if (!this.currentForm) this.currentForm = this.currentNode; this.currentFormEnd = this.reader.offset + length; this.parentForm = this.currentForm; if (!this.currentForm[type]) { this.currentForm[type] = {}; this.currentForm = this.currentForm[type]; } else { console.warn("LWOLoader: form already exists on parent: ", type, this.currentForm); this.currentForm = this.currentForm[type]; } } skipForm(length) { this.reader.skip(length - 4); } parseUnknownForm(type, length) { console.warn("LWOLoader: unknown FORM encountered: " + type, length); printBuffer(this.reader.dv.buffer, this.reader.offset, length - 4); this.reader.skip(length - 4); } parseSurfaceForm(length) { this.reader.skip(8); var name = this.reader.getString(); var surface = { attributes: {}, connections: {}, name, inputName: name, nodes: {}, source: this.reader.getString() }; this.tree.materials[name] = surface; this.currentSurface = surface; this.parentForm = this.tree.materials; this.currentForm = surface; this.currentFormEnd = this.reader.offset + length; } parseSurfaceLwo2(length) { var name = this.reader.getString(); var surface = { attributes: {}, connections: {}, name, nodes: {}, source: this.reader.getString() }; this.tree.materials[name] = surface; this.currentSurface = surface; this.parentForm = this.tree.materials; this.currentForm = surface; this.currentFormEnd = this.reader.offset + length; } parseSubNode(length) { this.reader.skip(8); var node = { name: this.reader.getString() }; this.currentForm = node; this.currentNode = node; this.currentFormEnd = this.reader.offset + length; } parseConnections(length) { this.currentFormEnd = this.reader.offset + length; this.parentForm = this.currentForm; this.currentForm = this.currentSurface.connections; } parseEntryForm(length) { this.reader.skip(8); var name = this.reader.getString(); this.currentForm = this.currentNode.attributes; this.setupForm(name, length); } parseValueForm() { this.reader.skip(8); var valueType = this.reader.getString(); if (valueType === "double") this.currentForm.value = this.reader.getUint64(); else if (valueType === "int") this.currentForm.value = this.reader.getUint32(); else if (valueType === "vparam") { this.reader.skip(24); this.currentForm.value = this.reader.getFloat64(); } else if (valueType === "vparam3") { this.reader.skip(24); this.currentForm.value = this.reader.getFloat64Array(3); } } parseImageStateForm() { this.reader.skip(8); this.currentForm.mipMapLevel = this.reader.getFloat32(); } parseImageMap(length) { this.currentFormEnd = this.reader.offset + length; this.parentForm = this.currentForm; if (!this.currentForm.maps) this.currentForm.maps = []; var map = {}; this.currentForm.maps.push(map); this.currentForm = map; this.reader.skip(10); } parseTextureNodeAttribute(type) { this.reader.skip(28); this.reader.skip(20); switch (type) { case "ISCL": this.currentNode.scale = this.reader.getFloat32Array(3); break; case "IPOS": this.currentNode.position = this.reader.getFloat32Array(3); break; case "IROT": this.currentNode.rotation = this.reader.getFloat32Array(3); break; case "IFAL": this.currentNode.falloff = this.reader.getFloat32Array(3); break; case "IBMP": this.currentNode.amplitude = this.reader.getFloat32(); break; case "IUTD": this.currentNode.uTiles = this.reader.getFloat32(); break; case "IVTD": this.currentNode.vTiles = this.reader.getFloat32(); break; } this.reader.skip(2); } parseEnvelope(length) { this.reader.skip(length - 4); } parseClip(length) { if (this.reader.getIDTag() === "FORM") { this.reader.skip(16); this.currentNode.fileName = this.reader.getString(); return; } this.reader.setOffset(this.reader.offset - 4); this.currentFormEnd = this.reader.offset + length; this.parentForm = this.currentForm; this.reader.skip(8); var texture = { index: this.reader.getUint32() }; this.tree.textures.push(texture); this.currentForm = texture; } parseClipLwo2(length) { var texture = { index: this.reader.getUint32(), fileName: "" }; while (true) { var tag = this.reader.getIDTag(); var n_length = this.reader.getUint16(); if (tag === "STIL") { texture.fileName = this.reader.getString(); break; } if (n_length >= length) break; } this.tree.textures.push(texture); this.currentForm = texture; } parseImage() { this.reader.skip(8); this.currentForm.fileName = this.reader.getString(); } parseXVAL(type, length) { var endOffset = this.reader.offset + length - 4; this.reader.skip(8); this.currentForm[type] = this.reader.getFloat32(); this.reader.setOffset(endOffset); } parseXVAL3(type, length) { var endOffset = this.reader.offset + length - 4; this.reader.skip(8); this.currentForm[type] = { x: this.reader.getFloat32(), y: this.reader.getFloat32(), z: this.reader.getFloat32() }; this.reader.setOffset(endOffset); } parseObjectTag() { if (!this.tree.objectTags) this.tree.objectTags = {}; this.tree.objectTags[this.reader.getIDTag()] = { tagString: this.reader.getString() }; } parseLayer(length) { var layer = { number: this.reader.getUint16(), flags: this.reader.getUint16(), pivot: this.reader.getFloat32Array(3), name: this.reader.getString() }; this.tree.layers.push(layer); this.currentLayer = layer; var parsedLength = 16 + stringOffset(this.currentLayer.name); this.currentLayer.parent = parsedLength < length ? this.reader.getUint16() : -1; } parsePoints(length) { this.currentPoints = []; for (var i = 0; i < length / 4; i += 3) this.currentPoints.push(this.reader.getFloat32(), this.reader.getFloat32(), -this.reader.getFloat32()); } parseVertexMapping(length, discontinuous) { var finalOffset = this.reader.offset + length; var channelName = this.reader.getString(); if (this.reader.offset === finalOffset) { this.currentForm.UVChannel = channelName; return; } this.reader.setOffset(this.reader.offset - stringOffset(channelName)); var type = this.reader.getIDTag(); this.reader.getUint16(); var name = this.reader.getString(); var remainingLength = length - 6 - stringOffset(name); switch (type) { case "TXUV": this.parseUVMapping(name, finalOffset, discontinuous); break; case "MORF": case "SPOT": this.parseMorphTargets(name, finalOffset, type); break; case "APSL": case "NORM": case "WGHT": case "MNVW": case "PICK": case "RGB ": case "RGBA": this.reader.skip(remainingLength); break; default: console.warn("LWOLoader: unknown vertex map type: " + type); this.reader.skip(remainingLength); } } parseUVMapping(name, finalOffset, discontinuous) { var uvIndices = []; var polyIndices = []; var uvs = []; while (this.reader.offset < finalOffset) { uvIndices.push(this.reader.getVariableLengthIndex()); if (discontinuous) polyIndices.push(this.reader.getVariableLengthIndex()); uvs.push(this.reader.getFloat32(), this.reader.getFloat32()); } if (discontinuous) { if (!this.currentLayer.discontinuousUVs) this.currentLayer.discontinuousUVs = {}; this.currentLayer.discontinuousUVs[name] = { uvIndices, polyIndices, uvs }; } else { if (!this.currentLayer.uvs) this.currentLayer.uvs = {}; this.currentLayer.uvs[name] = { uvIndices, uvs }; } } parseMorphTargets(name, finalOffset, type) { var indices = []; var points = []; type = type === "MORF" ? "relative" : "absolute"; while (this.reader.offset < finalOffset) { indices.push(this.reader.getVariableLengthIndex()); points.push(this.reader.getFloat32(), this.reader.getFloat32(), -this.reader.getFloat32()); } if (!this.currentLayer.morphTargets) this.currentLayer.morphTargets = {}; this.currentLayer.morphTargets[name] = { indices, points, type }; } parsePolygonList(length) { var finalOffset = this.reader.offset + length; var type = this.reader.getIDTag(); var indices = []; var polygonDimensions = []; while (this.reader.offset < finalOffset) { var numverts = this.reader.getUint16(); numverts = numverts & 1023; polygonDimensions.push(numverts); for (var j = 0; j < numverts; j++) indices.push(this.reader.getVariableLengthIndex()); } var geometryData = { type, vertexIndices: indices, polygonDimensions, points: this.currentPoints }; if (polygonDimensions[0] === 1) geometryData.type = "points"; else if (polygonDimensions[0] === 2) geometryData.type = "lines"; this.currentLayer.geometry = geometryData; } parseTagStrings(length) { this.tree.tags = this.reader.getStringArray(length); } parsePolygonTagMapping(length) { var finalOffset = this.reader.offset + length; if (this.reader.getIDTag() === "SURF") this.parseMaterialIndices(finalOffset); else this.reader.skip(length - 4); } parseMaterialIndices(finalOffset) { this.currentLayer.geometry.materialIndices = []; while (this.reader.offset < finalOffset) { var polygonIndex = this.reader.getVariableLengthIndex(); var materialIndex = this.reader.getUint16(); this.currentLayer.geometry.materialIndices.push(polygonIndex, materialIndex); } } parseUnknownCHUNK(blockID, length) { console.warn("LWOLoader: unknown chunk type: " + blockID + " length: " + length); var data = this.reader.getString(length); this.currentForm[blockID] = data; } }; var DataViewReader = class { constructor(buffer) { this.dv = new DataView(buffer); this.offset = 0; this._textDecoder = new TextDecoder(); this._bytes = new Uint8Array(buffer); } size() { return this.dv.buffer.byteLength; } setOffset(offset) { if (offset > 0 && offset < this.dv.buffer.byteLength) this.offset = offset; else console.error("LWOLoader: invalid buffer offset"); } endOfFile() { if (this.offset >= this.size()) return true; return false; } skip(length) { this.offset += length; } getUint8() { var value = this.dv.getUint8(this.offset); this.offset += 1; return value; } getUint16() { var value = this.dv.getUint16(this.offset); this.offset += 2; return value; } getInt32() { var value = this.dv.getInt32(this.offset, false); this.offset += 4; return value; } getUint32() { var value = this.dv.getUint32(this.offset, false); this.offset += 4; return value; } getUint64() { var low, high = this.getUint32(); low = this.getUint32(); return high * 4294967296 + low; } getFloat32() { var value = this.dv.getFloat32(this.offset, false); this.offset += 4; return value; } getFloat32Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getFloat32()); return a; } getFloat64() { var value = this.dv.getFloat64(this.offset, this.littleEndian); this.offset += 8; return value; } getFloat64Array(size) { var a = []; for (var i = 0; i < size; i++) a.push(this.getFloat64()); return a; } getVariableLengthIndex() { var firstByte = this.getUint8(); if (firstByte === 255) return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8(); return firstByte * 256 + this.getUint8(); } getIDTag() { return this.getString(4); } getString(size) { if (size === 0) return; const start = this.offset; let result; let length; if (size) { length = size; result = this._textDecoder.decode(new Uint8Array(this.dv.buffer, start, size)); } else { length = this._bytes.indexOf(0, start) - start; result = this._textDecoder.decode(new Uint8Array(this.dv.buffer, start, length)); length++; length += length % 2; } this.skip(length); return result; } getStringArray(size) { var a = this.getString(size); a = a.split("\0"); return a.filter(Boolean); } }; var Debugger = class { constructor() { this.active = false; this.depth = 0; this.formList = []; } enable() { this.active = true; } log() { if (!this.active) return; var nodeType; switch (this.node) { case 0: nodeType = "FORM"; break; case 1: nodeType = "CHK"; break; case 2: nodeType = "S-CHK"; break; } console.log("| ".repeat(this.depth) + nodeType, this.nodeID, `( ${this.offset} ) -> ( ${this.dataOffset + this.length} )`, this.node == 0 ? " {" : "", this.skipped ? "SKIPPED" : "", this.node == 0 && this.skipped ? "}" : ""); if (this.node == 0 && !this.skipped) { this.depth += 1; this.formList.push(this.dataOffset + this.length); } this.skipped = false; } closeForms() { if (!this.active) return; for (var i = this.formList.length - 1; i >= 0; i--) if (this.offset >= this.formList[i]) { this.depth -= 1; console.log("| ".repeat(this.depth) + "}"); this.formList.splice(-1, 1); } } }; function isEven(num) { return num % 2; } function stringOffset(string) { return string.length + 1 + (isEven(string.length + 1) ? 1 : 0); } function printBuffer(buffer, from, to) { console.log(new TextDecoder().decode(new Uint8Array(buffer, from, to))); } //#endregion //#region node_modules/three-stdlib/loaders/LWOLoader.js var _lwoTree; var LWOLoader = class extends Loader { constructor(manager, parameters = {}) { super(manager); this.resourcePath = parameters.resourcePath !== void 0 ? parameters.resourcePath : ""; } load(url, onLoad, onProgress, onError) { const scope = this; const path = scope.path === "" ? extractParentUrl(url, "Objects") : scope.path; const modelName = url.split(path).pop().split(".")[0]; const loader = new FileLoader(this.manager); loader.setPath(scope.path); loader.setResponseType("arraybuffer"); loader.load(url, function(buffer) { try { onLoad(scope.parse(buffer, path, modelName)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } parse(iffBuffer, path, modelName) { _lwoTree = new IFFParser().parse(iffBuffer); return new LWOTreeParser(new TextureLoader(this.manager).setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin)).parse(modelName); } }; var LWOTreeParser = class { constructor(textureLoader) { this.textureLoader = textureLoader; } parse(modelName) { this.materials = new MaterialParser(this.textureLoader).parse(); this.defaultLayerName = modelName; this.meshes = this.parseLayers(); return { materials: this.materials, meshes: this.meshes }; } parseLayers() { const meshes = []; const finalMeshes = []; const geometryParser = new GeometryParser(); const scope = this; _lwoTree.layers.forEach(function(layer) { const geometry = geometryParser.parse(layer.geometry, layer); const mesh = scope.parseMesh(geometry, layer); meshes[layer.number] = mesh; if (layer.parent === -1) finalMeshes.push(mesh); else meshes[layer.parent].add(mesh); }); this.applyPivots(finalMeshes); return finalMeshes; } parseMesh(geometry, layer) { let mesh; const materials = this.getMaterials(geometry.userData.matNames, layer.geometry.type); if (UV1 === "uv2") this.duplicateUVs(geometry, materials); if (layer.geometry.type === "points") mesh = new Points(geometry, materials); else if (layer.geometry.type === "lines") mesh = new LineSegments(geometry, materials); else mesh = new Mesh(geometry, materials); if (layer.name) mesh.name = layer.name; else mesh.name = this.defaultLayerName + "_layer_" + layer.number; mesh.userData.pivot = layer.pivot; return mesh; } applyPivots(meshes) { meshes.forEach(function(mesh) { mesh.traverse(function(child) { const pivot = child.userData.pivot; child.position.x += pivot[0]; child.position.y += pivot[1]; child.position.z += pivot[2]; if (child.parent) { const parentPivot = child.parent.userData.pivot; child.position.x -= parentPivot[0]; child.position.y -= parentPivot[1]; child.position.z -= parentPivot[2]; } }); }); } getMaterials(namesArray, type) { const materials = []; const scope = this; namesArray.forEach(function(name, i) { materials[i] = scope.getMaterialByName(name); }); if (type === "points" || type === "lines") materials.forEach(function(mat, i) { const spec = { color: mat.color }; if (type === "points") { spec.size = .1; spec.map = mat.map; spec.morphTargets = mat.morphTargets; materials[i] = new PointsMaterial(spec); } else if (type === "lines") materials[i] = new LineBasicMaterial(spec); }); const filtered = materials.filter(Boolean); if (filtered.length === 1) return filtered[0]; return materials; } getMaterialByName(name) { return this.materials.filter(function(m) { return m.name === name; })[0]; } duplicateUVs(geometry, materials) { let duplicateUVs = false; if (!Array.isArray(materials)) { if (materials.aoMap) duplicateUVs = true; } else materials.forEach(function(material) { if (material.aoMap) duplicateUVs = true; }); if (!duplicateUVs) return; geometry.setAttribute("uv2", new BufferAttribute(geometry.attributes.uv.array, 2)); } }; var MaterialParser = class { constructor(textureLoader) { this.textureLoader = textureLoader; } parse() { const materials = []; this.textures = {}; for (const name in _lwoTree.materials) if (_lwoTree.format === "LWO3") materials.push(this.parseMaterial(_lwoTree.materials[name], name, _lwoTree.textures)); else if (_lwoTree.format === "LWO2") materials.push(this.parseMaterialLwo2(_lwoTree.materials[name], name, _lwoTree.textures)); return materials; } parseMaterial(materialData, name, textures) { let params = { name, side: this.getSide(materialData.attributes), flatShading: this.getSmooth(materialData.attributes) }; const connections = this.parseConnections(materialData.connections, materialData.nodes); const maps = this.parseTextureNodes(connections.maps); this.parseAttributeImageMaps(connections.attributes, textures, maps, materialData.maps); const attributes = this.parseAttributes(connections.attributes, maps); this.parseEnvMap(connections, maps, attributes); params = Object.assign(maps, params); params = Object.assign(params, attributes); return new (this.getMaterialType(connections.attributes))(params); } parseMaterialLwo2(materialData, name) { let params = { name, side: this.getSide(materialData.attributes), flatShading: this.getSmooth(materialData.attributes) }; const attributes = this.parseAttributes(materialData.attributes, {}); params = Object.assign(params, attributes); return new MeshPhongMaterial(params); } getSide(attributes) { if (!attributes.side) return 1; switch (attributes.side) { case 0: case 1: return 1; case 2: return 0; case 3: return 2; } } getSmooth(attributes) { if (!attributes.smooth) return true; return !attributes.smooth; } parseConnections(connections, nodes) { const materialConnections = { maps: {} }; const inputName = connections.inputName; const inputNodeName = connections.inputNodeName; const nodeName = connections.nodeName; const scope = this; inputName.forEach(function(name, index) { if (name === "Material") { const matNode = scope.getNodeByRefName(inputNodeName[index], nodes); materialConnections.attributes = matNode.attributes; materialConnections.envMap = matNode.fileName; materialConnections.name = inputNodeName[index]; } }); nodeName.forEach(function(name, index) { if (name === materialConnections.name) materialConnections.maps[inputName[index]] = scope.getNodeByRefName(inputNodeName[index], nodes); }); return materialConnections; } getNodeByRefName(refName, nodes) { for (const name in nodes) if (nodes[name].refName === refName) return nodes[name]; } parseTextureNodes(textureNodes) { const maps = {}; for (const name in textureNodes) { const node = textureNodes[name]; const path = node.fileName; if (!path) return; const texture = this.loadTexture(path); if (node.widthWrappingMode !== void 0) texture.wrapS = this.getWrappingType(node.widthWrappingMode); if (node.heightWrappingMode !== void 0) texture.wrapT = this.getWrappingType(node.heightWrappingMode); switch (name) { case "Color": maps.map = texture; break; case "Roughness": maps.roughnessMap = texture; maps.roughness = .5; break; case "Specular": maps.specularMap = texture; maps.specular = 16777215; break; case "Luminous": maps.emissiveMap = texture; maps.emissive = 8421504; break; case "Luminous Color": maps.emissive = 8421504; break; case "Metallic": maps.metalnessMap = texture; maps.metalness = .5; break; case "Transparency": case "Alpha": maps.alphaMap = texture; maps.transparent = true; break; case "Normal": maps.normalMap = texture; if (node.amplitude !== void 0) maps.normalScale = new Vector2(node.amplitude, node.amplitude); break; case "Bump": maps.bumpMap = texture; break; } } if (maps.roughnessMap && maps.specularMap) delete maps.specularMap; return maps; } parseAttributeImageMaps(attributes, textures, maps) { for (const name in attributes) { const attribute = attributes[name]; if (attribute.maps) { const mapData = attribute.maps[0]; const path = this.getTexturePathByIndex(mapData.imageIndex, textures); if (!path) return; const texture = this.loadTexture(path); if (mapData.wrap !== void 0) texture.wrapS = this.getWrappingType(mapData.wrap.w); if (mapData.wrap !== void 0) texture.wrapT = this.getWrappingType(mapData.wrap.h); switch (name) { case "Color": maps.map = texture; break; case "Diffuse": maps.aoMap = texture; break; case "Roughness": maps.roughnessMap = texture; maps.roughness = 1; break; case "Specular": maps.specularMap = texture; maps.specular = 16777215; break; case "Luminosity": maps.emissiveMap = texture; maps.emissive = 8421504; break; case "Metallic": maps.metalnessMap = texture; maps.metalness = 1; break; case "Transparency": case "Alpha": maps.alphaMap = texture; maps.transparent = true; break; case "Normal": maps.normalMap = texture; break; case "Bump": maps.bumpMap = texture; break; } } } } parseAttributes(attributes, maps) { const params = {}; if (attributes.Color && !maps.map) params.color = new Color().fromArray(attributes.Color.value); else params.color = new Color(); if (attributes.Transparency && attributes.Transparency.value !== 0) { params.opacity = 1 - attributes.Transparency.value; params.transparent = true; } if (attributes["Bump Height"]) params.bumpScale = attributes["Bump Height"].value * .1; if (attributes["Refraction Index"]) params.refractionRatio = 1 / attributes["Refraction Index"].value; this.parsePhysicalAttributes(params, attributes, maps); this.parseStandardAttributes(params, attributes, maps); this.parsePhongAttributes(params, attributes, maps); return params; } parsePhysicalAttributes(params, attributes) { if (attributes.Clearcoat && attributes.Clearcoat.value > 0) { params.clearcoat = attributes.Clearcoat.value; if (attributes["Clearcoat Gloss"]) params.clearcoatRoughness = .5 * (1 - attributes["Clearcoat Gloss"].value); } } parseStandardAttributes(params, attributes, maps) { if (attributes.Luminous) { params.emissiveIntensity = attributes.Luminous.value; if (attributes["Luminous Color"] && !maps.emissive) params.emissive = new Color().fromArray(attributes["Luminous Color"].value); else params.emissive = new Color(8421504); } if (attributes.Roughness && !maps.roughnessMap) params.roughness = attributes.Roughness.value; if (attributes.Metallic && !maps.metalnessMap) params.metalness = attributes.Metallic.value; } parsePhongAttributes(params, attributes, maps) { if (attributes.Diffuse) params.color.multiplyScalar(attributes.Diffuse.value); if (attributes.Reflection) { params.reflectivity = attributes.Reflection.value; params.combine = 2; } if (attributes.Luminosity) { params.emissiveIntensity = attributes.Luminosity.value; if (!maps.emissiveMap && !maps.map) params.emissive = params.color; else params.emissive = new Color(8421504); } if (!attributes.Roughness && attributes.Specular && !maps.specularMap) if (attributes["Color Highlight"]) params.specular = new Color().setScalar(attributes.Specular.value).lerp(params.color.clone().multiplyScalar(attributes.Specular.value), attributes["Color Highlight"].value); else params.specular = new Color().setScalar(attributes.Specular.value); if (params.specular && attributes.Glossiness) params.shininess = 7 + Math.pow(2, attributes.Glossiness.value * 12 + 2); } parseEnvMap(connections, maps, attributes) { if (connections.envMap) { const envMap = this.loadTexture(connections.envMap); if (attributes.transparent && attributes.opacity < .999) { envMap.mapping = 304; if (attributes.reflectivity !== void 0) { delete attributes.reflectivity; delete attributes.combine; } if (attributes.metalness !== void 0) delete attributes.metalness; } else envMap.mapping = 303; maps.envMap = envMap; } } getTexturePathByIndex(index) { let fileName = ""; if (!_lwoTree.textures) return fileName; _lwoTree.textures.forEach(function(texture) { if (texture.index === index) fileName = texture.fileName; }); return fileName; } loadTexture(path) { if (!path) return null; return this.textureLoader.load(path, void 0, void 0, function() { console.warn("LWOLoader: non-standard resource hierarchy. Use `resourcePath` parameter to specify root content directory."); }); } getWrappingType(num) { switch (num) { case 0: console.warn("LWOLoader: \"Reset\" texture wrapping type is not supported in three.js"); return ClampToEdgeWrapping; case 1: return RepeatWrapping; case 2: return MirroredRepeatWrapping; case 3: return ClampToEdgeWrapping; } } getMaterialType(nodeData) { if (nodeData.Clearcoat && nodeData.Clearcoat.value > 0) return MeshPhysicalMaterial; if (nodeData.Roughness) return MeshStandardMaterial; return MeshPhongMaterial; } }; var GeometryParser = class { parse(geoData, layer) { const geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute(geoData.points, 3)); const indices = this.splitIndices(geoData.vertexIndices, geoData.polygonDimensions); geometry.setIndex(indices); this.parseGroups(geometry, geoData); geometry.computeVertexNormals(); this.parseUVs(geometry, layer, indices); this.parseMorphTargets(geometry, layer, indices); geometry.translate(-layer.pivot[0], -layer.pivot[1], -layer.pivot[2]); return geometry; } splitIndices(indices, polygonDimensions) { const remappedIndices = []; let i = 0; polygonDimensions.forEach(function(dim) { if (dim < 4) for (let k = 0; k < dim; k++) remappedIndices.push(indices[i + k]); else if (dim === 4) remappedIndices.push(indices[i], indices[i + 1], indices[i + 2], indices[i], indices[i + 2], indices[i + 3]); else if (dim > 4) { for (let k = 1; k < dim - 1; k++) remappedIndices.push(indices[i], indices[i + k], indices[i + k + 1]); console.warn("LWOLoader: polygons with greater than 4 sides are not supported"); } i += dim; }); return remappedIndices; } parseGroups(geometry, geoData) { const tags = _lwoTree.tags; const matNames = []; let elemSize = 3; if (geoData.type === "lines") elemSize = 2; if (geoData.type === "points") elemSize = 1; const remappedIndices = this.splitMaterialIndices(geoData.polygonDimensions, geoData.materialIndices); let indexNum = 0; const indexPairs = {}; let prevMaterialIndex; let materialIndex; let prevStart = 0; let currentCount = 0; for (let i = 0; i < remappedIndices.length; i += 2) { materialIndex = remappedIndices[i + 1]; if (i === 0) matNames[indexNum] = tags[materialIndex]; if (prevMaterialIndex === void 0) prevMaterialIndex = materialIndex; if (materialIndex !== prevMaterialIndex) { let currentIndex; if (indexPairs[tags[prevMaterialIndex]]) currentIndex = indexPairs[tags[prevMaterialIndex]]; else { currentIndex = indexNum; indexPairs[tags[prevMaterialIndex]] = indexNum; matNames[indexNum] = tags[prevMaterialIndex]; indexNum++; } geometry.addGroup(prevStart, currentCount, currentIndex); prevStart += currentCount; prevMaterialIndex = materialIndex; currentCount = 0; } currentCount += elemSize; } if (geometry.groups.length > 0) { let currentIndex; if (indexPairs[tags[materialIndex]]) currentIndex = indexPairs[tags[materialIndex]]; else { currentIndex = indexNum; indexPairs[tags[materialIndex]] = indexNum; matNames[indexNum] = tags[materialIndex]; } geometry.addGroup(prevStart, currentCount, currentIndex); } geometry.userData.matNames = matNames; } splitMaterialIndices(polygonDimensions, indices) { const remappedIndices = []; polygonDimensions.forEach(function(dim, i) { if (dim <= 3) remappedIndices.push(indices[i * 2], indices[i * 2 + 1]); else if (dim === 4) remappedIndices.push(indices[i * 2], indices[i * 2 + 1], indices[i * 2], indices[i * 2 + 1]); else for (let k = 0; k < dim - 2; k++) remappedIndices.push(indices[i * 2], indices[i * 2 + 1]); }); return remappedIndices; } parseUVs(geometry, layer) { const remappedUVs = Array.from(Array(geometry.attributes.position.count * 2), function() { return 0; }); for (const name in layer.uvs) { const uvs = layer.uvs[name].uvs; layer.uvs[name].uvIndices.forEach(function(i, j) { remappedUVs[i * 2] = uvs[j * 2]; remappedUVs[i * 2 + 1] = uvs[j * 2 + 1]; }); } geometry.setAttribute("uv", new Float32BufferAttribute(remappedUVs, 2)); } parseMorphTargets(geometry, layer) { let num = 0; for (const name in layer.morphTargets) { const remappedPoints = geometry.attributes.position.array.slice(); if (!geometry.morphAttributes.position) geometry.morphAttributes.position = []; const morphPoints = layer.morphTargets[name].points; const morphIndices = layer.morphTargets[name].indices; const type = layer.morphTargets[name].type; morphIndices.forEach(function(i, j) { if (type === "relative") { remappedPoints[i * 3] += morphPoints[j * 3]; remappedPoints[i * 3 + 1] += morphPoints[j * 3 + 1]; remappedPoints[i * 3 + 2] += morphPoints[j * 3 + 2]; } else { remappedPoints[i * 3] = morphPoints[j * 3]; remappedPoints[i * 3 + 1] = morphPoints[j * 3 + 1]; remappedPoints[i * 3 + 2] = morphPoints[j * 3 + 2]; } }); geometry.morphAttributes.position[num] = new Float32BufferAttribute(remappedPoints, 3); geometry.morphAttributes.position[num].name = name; num++; } geometry.morphTargetsRelative = false; } }; function extractParentUrl(url, dir) { const index = url.indexOf(dir); if (index === -1) return "./"; return url.substr(0, index); } //#endregion //#region node_modules/three-stdlib/loaders/PLYLoader.js var PLYLoader = class extends Loader { constructor(manager) { super(manager); this.propertyNameMapping = {}; } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function(text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) onError(e); else console.error(e); scope.manager.itemError(url); } }, onProgress, onError); } setPropertyNameMapping(mapping) { this.propertyNameMapping = mapping; } parse(data) { function parseHeader(data2) { const patternHeader = /ply([\s\S]*)end_header\r?\n/; let headerText = ""; let headerLength = 0; const result = patternHeader.exec(data2); if (result !== null) { headerText = result[1]; headerLength = new Blob([result[0]]).size; } const header = { comments: [], elements: [], headerLength, objInfo: "" }; const lines = headerText.split("\n"); let currentElement; function make_ply_element_property(propertValues, propertyNameMapping) { const property = { type: propertValues[0] }; if (property.type === "list") { property.name = propertValues[3]; property.countType = propertValues[1]; property.itemType = propertValues[2]; } else property.name = propertValues[1]; if (property.name in propertyNameMapping) property.name = propertyNameMapping[property.name]; return property; } for (let i = 0; i < lines.length; i++) { let line = lines[i]; line = line.trim(); if (line === "") continue; const lineValues = line.split(/\s+/); const lineType = lineValues.shift(); line = lineValues.join(" "); switch (lineType) { case "format": header.format = lineValues[0]; header.version = lineValues[1]; break; case "comment": header.comments.push(line); break; case "element": if (currentElement !== void 0) header.elements.push(currentElement); currentElement = {}; currentElement.name = lineValues[0]; currentElement.count = parseInt(lineValues[1]); currentElement.properties = []; break; case "property": currentElement.properties.push(make_ply_element_property(lineValues, scope.propertyNameMapping)); break; case "obj_info": header.objInfo = line; break; default: console.log("unhandled", lineType, lineValues); } } if (currentElement !== void 0) header.elements.push(currentElement); return header; } function parseASCIINumber(n, type) { switch (type) { case "char": case "uchar": case "short": case "ushort": case "int": case "uint": case "int8": case "uint8": case "int16": case "uint16": case "int32": case "uint32": return parseInt(n); case "float": case "double": case "float32": case "float64": return parseFloat(n); } } function parseASCIIElement(properties, line) { const values = line.split(/\s+/); const element = {}; for (let i = 0; i < properties.length; i++) if (properties[i].type === "list") { const list = []; const n = parseASCIINumber(values.shift(), properties[i].countType); for (let j = 0; j < n; j++) list.push(parseASCIINumber(values.shift(), properties[i].itemType)); element[properties[i].name] = list; } else element[properties[i].name] = parseASCIINumber(values.shift(), properties[i].type); return element; } function parseASCII(data2, header) { const buffer = { indices: [], vertices: [], normals: [], uvs: [], faceVertexUvs: [], colors: [] }; let result; const patternBody = /end_header\s([\s\S]*)$/; let body = ""; if ((result = patternBody.exec(data2)) !== null) body = result[1]; const lines = body.split("\n"); let currentElement = 0; let currentElementCount = 0; for (let i = 0; i < lines.length; i++) { let line = lines[i]; line = line.trim(); if (line === "") continue; if (currentElementCount >= header.elements[currentElement].count) { currentElement++; currentElementCount = 0; } const element = parseASCIIElement(header.elements[currentElement].properties, line); handleElement(buffer, header.elements[currentElement].name, element); currentElementCount++; } return postProcess(buffer); } function postProcess(buffer) { let geometry2 = new BufferGeometry(); if (buffer.indices.length > 0) geometry2.setIndex(buffer.indices); geometry2.setAttribute("position", new Float32BufferAttribute(buffer.vertices, 3)); if (buffer.normals.length > 0) geometry2.setAttribute("normal", new Float32BufferAttribute(buffer.normals, 3)); if (buffer.uvs.length > 0) geometry2.setAttribute("uv", new Float32BufferAttribute(buffer.uvs, 2)); if (buffer.colors.length > 0) geometry2.setAttribute("color", new Float32BufferAttribute(buffer.colors, 3)); if (buffer.faceVertexUvs.length > 0) { geometry2 = geometry2.toNonIndexed(); geometry2.setAttribute("uv", new Float32BufferAttribute(buffer.faceVertexUvs, 2)); } geometry2.computeBoundingSphere(); return geometry2; } function handleElement(buffer, elementName, element) { if (elementName === "vertex") { buffer.vertices.push(element.x, element.y, element.z); if ("nx" in element && "ny" in element && "nz" in element) buffer.normals.push(element.nx, element.ny, element.nz); if ("s" in element && "t" in element) buffer.uvs.push(element.s, element.t); if ("red" in element && "green" in element && "blue" in element) buffer.colors.push(element.red / 255, element.green / 255, element.blue / 255); } else if (elementName === "face") { const vertex_indices = element.vertex_indices || element.vertex_index; const texcoord = element.texcoord; if (vertex_indices.length === 3) { buffer.indices.push(vertex_indices[0], vertex_indices[1], vertex_indices[2]); if (texcoord && texcoord.length === 6) { buffer.faceVertexUvs.push(texcoord[0], texcoord[1]); buffer.faceVertexUvs.push(texcoord[2], texcoord[3]); buffer.faceVertexUvs.push(texcoord[4], texcoord[5]); } } else if (vertex_indices.length === 4) { buffer.indices.push(vertex_indices[0], vertex_indices[1], vertex_indices[3]); buffer.indices.push(vertex_indices[1], vertex_indices[2], vertex_indices[3]); } } } function binaryRead(dataview, at, type, little_endian) { switch (type) { case "int8": case "char": return [dataview.getInt8(at), 1]; case "uint8": case "uchar": return [dataview.getUint8(at), 1]; case "int16": case "short": return [dataview.getInt16(at, little_endian), 2]; case "uint16": case "ushort": return [dataview.getUint16(at, little_endian), 2]; case "int32": case "int": return [dataview.getInt32(at, little_endian), 4]; case "uint32": case "uint": return [dataview.getUint32(at, little_endian), 4]; case "float32": case "float": return [dataview.getFloat32(at, little_endian), 4]; case "float64": case "double": return [dataview.getFloat64(at, little_endian), 8]; } } function binaryReadElement(dataview, at, properties, little_endian) { const element = {}; let result, read = 0; for (let i = 0; i < properties.length; i++) if (properties[i].type === "list") { const list = []; result = binaryRead(dataview, at + read, properties[i].countType, little_endian); const n = result[0]; read += result[1]; for (let j = 0; j < n; j++) { result = binaryRead(dataview, at + read, properties[i].itemType, little_endian); list.push(result[0]); read += result[1]; } element[properties[i].name] = list; } else { result = binaryRead(dataview, at + read, properties[i].type, little_endian); element[properties[i].name] = result[0]; read += result[1]; } return [element, read]; } function parseBinary(data2, header) { const buffer = { indices: [], vertices: [], normals: [], uvs: [], faceVertexUvs: [], colors: [] }; const little_endian = header.format === "binary_little_endian"; const body = new DataView(data2, header.headerLength); let result, loc = 0; for (let currentElement = 0; currentElement < header.elements.length; currentElement++) for (let currentElementCount = 0; currentElementCount < header.elements[currentElement].count; currentElementCount++) { result = binaryReadElement(body, loc, header.elements[currentElement].properties, little_endian); loc += result[1]; const element = result[0]; handleElement(buffer, header.elements[currentElement].name, element); } return postProcess(buffer); } let geometry; const scope = this; if (data instanceof ArrayBuffer) { const text = decodeText$1(new Uint8Array(data)); const header = parseHeader(text); geometry = header.format === "ascii" ? parseASCII(text, header) : parseBinary(data, header); } else geometry = parseASCII(data, parseHeader(data)); return geometry; } }; //#endregion //#region node_modules/three-stdlib/lines/LineSegmentsGeometry.js var _box$1 = /* @__PURE__ */ new Box3(); var _vector = /* @__PURE__ */ 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 ]; this.setIndex([ 0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5 ]); this.setAttribute("position", new Float32BufferAttribute(positions, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } applyMatrix4(matrix) { const start = this.attributes.instanceStart; const end = this.attributes.instanceEnd; if (start !== void 0) { start.applyMatrix4(matrix); end.applyMatrix4(matrix); 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 colors; if (array instanceof Float32Array) colors = array; else if (Array.isArray(array)) colors = new Float32Array(array); const instanceColorBuffer = new InstancedInterleavedBuffer(colors, itemSize * 2, 1); this.setAttribute("instanceColorStart", new InterleavedBufferAttribute(instanceColorBuffer, itemSize, 0)); this.setAttribute("instanceColorEnd", new InterleavedBufferAttribute(instanceColorBuffer, itemSize, itemSize)); return this; } fromWireframeGeometry(geometry) { this.setPositions(geometry.attributes.position.array); return this; } fromEdgesGeometry(geometry) { this.setPositions(geometry.attributes.position.array); return this; } fromMesh(mesh) { this.fromWireframeGeometry(new WireframeGeometry(mesh.geometry)); return this; } fromLineSegments(lineSegments) { const geometry = lineSegments.geometry; this.setPositions(geometry.attributes.position.array); return this; } computeBoundingBox() { if (this.boundingBox === null) this.boundingBox = new Box3(); const start = this.attributes.instanceStart; const end = this.attributes.instanceEnd; if (start !== void 0 && end !== void 0) { this.boundingBox.setFromBufferAttribute(start); _box$1.setFromBufferAttribute(end); this.boundingBox.union(_box$1); } } computeBoundingSphere() { if (this.boundingSphere === null) this.boundingSphere = new Sphere(); if (this.boundingBox === null) this.computeBoundingBox(); const start = this.attributes.instanceStart; const end = this.attributes.instanceEnd; if (start !== void 0 && end !== void 0) { const center = this.boundingSphere.center; this.boundingBox.getCenter(center); let maxRadiusSq = 0; for (let i = 0, il = start.count; i < il; i++) { _vector.fromBufferAttribute(start, i); maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector)); _vector.fromBufferAttribute(end, i); maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector)); } 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(matrix) { console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4()."); return this.applyMatrix4(matrix); } }; //#endregion //#region node_modules/three-stdlib/lines/LineGeometry.js var LineGeometry = class extends LineSegmentsGeometry { constructor() { super(); this.isLineGeometry = true; this.type = "LineGeometry"; } setPositions(array) { const length = array.length - 3; const points = new Float32Array(2 * length); for (let i = 0; i < length; i += 3) { points[2 * i] = array[i]; points[2 * i + 1] = array[i + 1]; points[2 * i + 2] = array[i + 2]; points[2 * i + 3] = array[i + 3]; points[2 * i + 4] = array[i + 4]; points[2 * i + 5] = array[i + 5]; } super.setPositions(points); return this; } setColors(array, itemSize = 3) { const length = array.length - itemSize; const colors = new Float32Array(2 * length); if (itemSize === 3) for (let i = 0; i < length; i += itemSize) { colors[2 * i] = array[i]; colors[2 * i + 1] = array[i + 1]; colors[2 * i + 2] = array[i + 2]; colors[2 * i + 3] = array[i + 3]; colors[2 * i + 4] = array[i + 4]; colors[2 * i + 5] = array[i + 5]; } else for (let i = 0; i < length; i += itemSize) { colors[2 * i] = array[i]; colors[2 * i + 1] = array[i + 1]; colors[2 * i + 2] = array[i + 2]; colors[2 * i + 3] = array[i + 3]; colors[2 * i + 4] = array[i + 4]; colors[2 * i + 5] = array[i + 5]; colors[2 * i + 6] = array[i + 6]; colors[2 * i + 7] = array[i + 7]; } super.setColors(colors, itemSize); return this; } fromLine(line) { const geometry = line.geometry; this.setPositions(geometry.attributes.position.array); return this; } }; //#endregion //#region 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 } } ])), vertexShader: ` #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: ` 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 }); 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); } }; //#endregion //#region node_modules/three-stdlib/lines/Wireframe.js var _start$1 = /* @__PURE__ */ new Vector3(); var _end$1 = /* @__PURE__ */ new Vector3(); var _viewport$1 = /* @__PURE__ */ new Vector4(); var Wireframe = class extends Mesh { constructor(geometry = new LineSegmentsGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) { super(geometry, material); this.isWireframe = true; this.type = "Wireframe"; } computeLineDistances() { const geometry = this.geometry; const instanceStart = geometry.attributes.instanceStart; const instanceEnd = geometry.attributes.instanceEnd; const lineDistances = new Float32Array(2 * instanceStart.count); for (let i = 0, j = 0, l = instanceStart.count; i < l; i++, j += 2) { _start$1.fromBufferAttribute(instanceStart, i); _end$1.fromBufferAttribute(instanceEnd, i); lineDistances[j] = j === 0 ? 0 : lineDistances[j - 1]; lineDistances[j + 1] = lineDistances[j] + _start$1.distanceTo(_end$1); } const instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1); geometry.setAttribute("instanceDistanceStart", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0)); geometry.setAttribute("instanceDistanceEnd", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1)); return this; } onBeforeRender(renderer) { const uniforms = this.material.uniforms; if (uniforms && uniforms.resolution) { renderer.getViewport(_viewport$1); this.material.uniforms.resolution.value.set(_viewport$1.z, _viewport$1.w); } } }; //#endregion //#region node_modules/three-stdlib/lines/WireframeGeometry2.js var WireframeGeometry2 = class extends LineSegmentsGeometry { constructor(geometry) { super(); this.isWireframeGeometry2 = true; this.type = "WireframeGeometry2"; this.fromWireframeGeometry(new WireframeGeometry(geometry)); } }; //#endregion //#region node_modules/three-stdlib/lines/LineSegments2.js var _viewport = /* @__PURE__ */ new Vector4(); var _start = /* @__PURE__ */ new Vector3(); var _end = /* @__PURE__ */ new Vector3(); var _start4 = /* @__PURE__ */ new Vector4(); var _end4 = /* @__PURE__ */ new Vector4(); var _ssOrigin = /* @__PURE__ */ new Vector4(); var _ssOrigin3 = /* @__PURE__ */ new Vector3(); var _mvMatrix = /* @__PURE__ */ new Matrix4(); var _line = /* @__PURE__ */ new Line3(); var _closestPoint = /* @__PURE__ */ new Vector3(); var _box = /* @__PURE__ */ new Box3(); var _sphere = /* @__PURE__ */ new Sphere(); var _clipToWorldVector = /* @__PURE__ */ new Vector4(); var _ray, _lineWidth; function getWorldSpaceHalfWidth(camera, distance, resolution) { _clipToWorldVector.set(0, 0, -distance, 1).applyMatrix4(camera.projectionMatrix); _clipToWorldVector.multiplyScalar(1 / _clipToWorldVector.w); _clipToWorldVector.x = _lineWidth / resolution.width; _clipToWorldVector.y = _lineWidth / resolution.height; _clipToWorldVector.applyMatrix4(camera.projectionMatrixInverse); _clipToWorldVector.multiplyScalar(1 / _clipToWorldVector.w); return Math.abs(Math.max(_clipToWorldVector.x, _clipToWorldVector.y)); } function raycastWorldUnits(lineSegments, intersects) { const matrixWorld = lineSegments.matrixWorld; const geometry = lineSegments.geometry; const instanceStart = geometry.attributes.instanceStart; const instanceEnd = geometry.attributes.instanceEnd; const segmentCount = Math.min(geometry.instanceCount, instanceStart.count); for (let i = 0, l = segmentCount; i < l; i++) { _line.start.fromBufferAttribute(instanceStart, i); _line.end.fromBufferAttribute(instanceEnd, i); _line.applyMatrix4(matrixWorld); const pointOnLine = new Vector3(); const point = new Vector3(); _ray.distanceSqToSegment(_line.start, _line.end, point, pointOnLine); if (point.distanceTo(pointOnLine) < _lineWidth * .5) intersects.push({ point, pointOnLine, distance: _ray.origin.distanceTo(point), object: lineSegments, face: null, faceIndex: i, uv: null, [UV1]: null }); } } function raycastScreenSpace(lineSegments, camera, intersects) { const projectionMatrix = camera.projectionMatrix; const resolution = lineSegments.material.resolution; const matrixWorld = lineSegments.matrixWorld; const geometry = lineSegments.geometry; const instanceStart = geometry.attributes.instanceStart; const instanceEnd = geometry.attributes.instanceEnd; const segmentCount = Math.min(geometry.instanceCount, instanceStart.count); const near = -camera.near; _ray.at(1, _ssOrigin); _ssOrigin.w = 1; _ssOrigin.applyMatrix4(camera.matrixWorldInverse); _ssOrigin.applyMatrix4(projectionMatrix); _ssOrigin.multiplyScalar(1 / _ssOrigin.w); _ssOrigin.x *= resolution.x / 2; _ssOrigin.y *= resolution.y / 2; _ssOrigin.z = 0; _ssOrigin3.copy(_ssOrigin); _mvMatrix.multiplyMatrices(camera.matrixWorldInverse, matrixWorld); for (let i = 0, l = segmentCount; i < l; i++) { _start4.fromBufferAttribute(instanceStart, i); _end4.fromBufferAttribute(instanceEnd, i); _start4.w = 1; _end4.w = 1; _start4.applyMatrix4(_mvMatrix); _end4.applyMatrix4(_mvMatrix); if (_start4.z > near && _end4.z > near) continue; if (_start4.z > near) { const deltaDist = _start4.z - _end4.z; const t = (_start4.z - near) / deltaDist; _start4.lerp(_end4, t); } else if (_end4.z > near) { const deltaDist = _end4.z - _start4.z; const t = (_end4.z - near) / deltaDist; _end4.lerp(_start4, t); } _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, _closestPoint); const zPos = MathUtils.lerp(_start4.z, _end4.z, param); const isInClipSpace = zPos >= -1 && zPos <= 1; const isInside = _ssOrigin3.distanceTo(_closestPoint) < _lineWidth * .5; if (isInClipSpace && isInside) { _line.start.fromBufferAttribute(instanceStart, i); _line.end.fromBufferAttribute(instanceEnd, i); _line.start.applyMatrix4(matrixWorld); _line.end.applyMatrix4(matrixWorld); const pointOnLine = new Vector3(); const point = new Vector3(); _ray.distanceSqToSegment(_line.start, _line.end, point, pointOnLine); intersects.push({ point, pointOnLine, distance: _ray.origin.distanceTo(point), object: lineSegments, face: null, faceIndex: i, uv: null, [UV1]: null }); } } } var LineSegments2 = class extends Mesh { constructor(geometry = new LineSegmentsGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) { super(geometry, material); this.isLineSegments2 = true; this.type = "LineSegments2"; } computeLineDistances() { const geometry = this.geometry; const instanceStart = geometry.attributes.instanceStart; const instanceEnd = geometry.attributes.instanceEnd; const lineDistances = new Float32Array(2 * instanceStart.count); for (let i = 0, j = 0, l = instanceStart.count; i < l; i++, j += 2) { _start.fromBufferAttribute(instanceStart, i); _end.fromBufferAttribute(instanceEnd, i); lineDistances[j] = j === 0 ? 0 : lineDistances[j - 1]; lineDistances[j + 1] = lineDistances[j] + _start.distanceTo(_end); } const instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1); geometry.setAttribute("instanceDistanceStart", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0)); geometry.setAttribute("instanceDistanceEnd", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1)); return this; } 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; _ray = raycaster.ray; const matrixWorld = this.matrixWorld; const geometry = this.geometry; const material = this.material; _lineWidth = material.linewidth + threshold; if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); _sphere.copy(geometry.boundingSphere).applyMatrix4(matrixWorld); let sphereMargin; if (worldUnits) sphereMargin = _lineWidth * .5; else sphereMargin = getWorldSpaceHalfWidth(camera, Math.max(camera.near, _sphere.distanceToPoint(_ray.origin)), material.resolution); _sphere.radius += sphereMargin; if (_ray.intersectsSphere(_sphere) === false) return; if (geometry.boundingBox === null) geometry.computeBoundingBox(); _box.copy(geometry.boundingBox).applyMatrix4(matrixWorld); let boxMargin; if (worldUnits) boxMargin = _lineWidth * .5; else boxMargin = getWorldSpaceHalfWidth(camera, Math.max(camera.near, _box.distanceToPoint(_ray.origin)), material.resolution); _box.expandByScalar(boxMargin); if (_ray.intersectsBox(_box) === 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(_viewport); this.material.uniforms.resolution.value.set(_viewport.z, _viewport.w); } } }; //#endregion //#region node_modules/three-stdlib/lines/Line2.js var Line2 = class extends LineSegments2 { constructor(geometry = new LineGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) { super(geometry, material); this.isLine2 = true; this.type = "Line2"; } }; //#endregion //#region node_modules/three-stdlib/helpers/LightProbeHelper.js var LightProbeHelper = class extends Mesh { constructor(lightProbe, size) { const material = new ShaderMaterial({ type: "LightProbeHelperMaterial", uniforms: { sh: { value: lightProbe.sh.coefficients }, intensity: { value: lightProbe.intensity } }, vertexShader: [ "varying vec3 vNormal;", "void main() {", " vNormal = normalize( normalMatrix * normal );", " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}" ].join("\n"), fragmentShader: [ "#define RECIPROCAL_PI 0.318309886", "vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {", " // matrix is assumed to be orthogonal", " return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );", "}", "// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf", "vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {", " // normal is assumed to have unit length", " float x = normal.x, y = normal.y, z = normal.z;", " // band 0", " vec3 result = shCoefficients[ 0 ] * 0.886227;", " // band 1", " result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;", " result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;", " result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;", " // band 2", " result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;", " result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;", " result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );", " result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;", " result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );", " return result;", "}", "uniform vec3 sh[ 9 ]; // sh coefficients", "uniform float intensity; // light probe intensity", "varying vec3 vNormal;", "void main() {", " vec3 normal = normalize( vNormal );", " vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );", " vec3 irradiance = shGetIrradianceAt( worldNormal, sh );", " vec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;", " gl_FragColor = linearToOutputTexel( vec4( outgoingLight, 1.0 ) );", "}" ].join("\n") }); const geometry = new SphereGeometry(1, 32, 16); super(geometry, material); this.lightProbe = lightProbe; this.size = size; this.type = "LightProbeHelper"; this.onBeforeRender(); } dispose() { this.geometry.dispose(); this.material.dispose(); } onBeforeRender() { this.position.copy(this.lightProbe.position); this.scale.set(1, 1, 1).multiplyScalar(this.size); this.material.uniforms.intensity.value = this.lightProbe.intensity; } }; //#endregion //#region node_modules/three-stdlib/helpers/RaycasterHelper.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 _o = /* @__PURE__ */ new Object3D(); var _v = /* @__PURE__ */ new Vector3(); var RaycasterHelper = class extends Object3D { constructor(raycaster, numberOfHitsToVisualize = 20) { super(); __publicField(this, "raycaster"); __publicField(this, "hits"); __publicField(this, "origin"); __publicField(this, "near"); __publicField(this, "far"); __publicField(this, "nearToFar"); __publicField(this, "originToNear"); __publicField(this, "hitPoints"); __publicField(this, "colors", { near: 16777215, far: 16777215, originToNear: 3355443, nearToFar: 16777215, origin: [978050, 16711771] }); __publicField(this, "setColors", (colors) => { const _colors = { ...this.colors, ...colors }; this.near.material.color.set(_colors.near); this.far.material.color.set(_colors.far); this.nearToFar.material.color.set(_colors.nearToFar); this.originToNear.material.color.set(_colors.originToNear); }); __publicField(this, "update", () => { var _a; const origin = this.raycaster.ray.origin; const direction = this.raycaster.ray.direction; this.origin.position.copy(origin); this.near.position.copy(origin).add(direction.clone().multiplyScalar(this.raycaster.near)); this.far.position.copy(origin).add(direction.clone().multiplyScalar(this.raycaster.far)); this.far.lookAt(origin); this.near.lookAt(origin); let pos = this.nearToFar.geometry.getAttribute("position"); pos.set([...this.near.position.toArray(), ...this.far.position.toArray()]); pos.needsUpdate = true; pos = this.originToNear.geometry.getAttribute("position"); pos.set([...origin.toArray(), ...this.near.position.toArray()]); pos.needsUpdate = true; for (let i = 0; i < this.numberOfHitsToVisualize; i++) { const hit = (_a = this.hits) == null ? void 0 : _a[i]; if (hit) { const { point } = hit; _o.position.copy(point); _o.scale.setScalar(1); } else _o.scale.setScalar(0); _o.updateMatrix(); this.hitPoints.setMatrixAt(i, _o.matrix); } this.hitPoints.instanceMatrix.needsUpdate = true; this.origin.material.color.set(this.hits.length > 0 ? this.colors.origin[0] : this.colors.origin[1]); }); __publicField(this, "dispose", () => { this.origin.geometry.dispose(); this.origin.material.dispose(); this.near.geometry.dispose(); this.near.material.dispose(); this.far.geometry.dispose(); this.far.material.dispose(); this.nearToFar.geometry.dispose(); this.nearToFar.material.dispose(); this.originToNear.geometry.dispose(); this.originToNear.material.dispose(); this.hitPoints.dispose(); }); this.numberOfHitsToVisualize = numberOfHitsToVisualize; this.raycaster = raycaster; this.hits = []; this.origin = new Mesh(new SphereGeometry(.04, 32), new MeshBasicMaterial()); this.origin.name = "RaycasterHelper_origin"; this.origin.raycast = () => null; const size = .1; let geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute([ -.1, size, 0, size, size, 0, size, -.1, 0, -.1, -.1, 0, -.1, size, 0 ], 3)); this.near = new Line(geometry, new LineBasicMaterial()); this.near.name = "RaycasterHelper_near"; this.near.raycast = () => null; this.far = new Line(geometry, new LineBasicMaterial()); this.far.name = "RaycasterHelper_far"; this.far.raycast = () => null; this.nearToFar = new Line(new BufferGeometry(), new LineBasicMaterial()); this.nearToFar.name = "RaycasterHelper_nearToFar"; this.nearToFar.raycast = () => null; this.nearToFar.geometry.setFromPoints([_v, _v]); this.originToNear = new Line(this.nearToFar.geometry.clone(), new LineBasicMaterial()); this.originToNear.name = "RaycasterHelper_originToNear"; this.originToNear.raycast = () => null; this.hitPoints = new InstancedMesh(new SphereGeometry(.04), new MeshBasicMaterial(), this.numberOfHitsToVisualize); this.hitPoints.name = "RaycasterHelper_hits"; this.hitPoints.raycast = () => null; this.add(this.nearToFar); this.add(this.originToNear); this.add(this.near); this.add(this.far); this.add(this.origin); this.add(this.hitPoints); this.setColors(); } }; //#endregion //#region node_modules/three-stdlib/helpers/VertexTangentsHelper.js var _v1$1 = /* @__PURE__ */ new Vector3(); var _v2$1 = /* @__PURE__ */ new Vector3(); var VertexTangentsHelper = class extends LineSegments { constructor(object, size = 1, color = 65535) { const geometry = new BufferGeometry(); const nTangents = object.geometry.attributes.tangent.count; const positions = new Float32BufferAttribute(nTangents * 2 * 3, 3); geometry.setAttribute("position", positions); super(geometry, new LineBasicMaterial({ color, toneMapped: false })); this.object = object; this.size = size; this.type = "VertexTangentsHelper"; this.matrixAutoUpdate = false; this.update(); } update() { this.object.updateMatrixWorld(true); const matrixWorld = this.object.matrixWorld; const position = this.geometry.attributes.position; const objGeometry = this.object.geometry; const objPos = objGeometry.attributes.position; const objTan = objGeometry.attributes.tangent; let idx = 0; for (let j = 0, jl = objPos.count; j < jl; j++) { _v1$1.fromBufferAttribute(objPos, j).applyMatrix4(matrixWorld); _v2$1.fromBufferAttribute(objTan, j); _v2$1.transformDirection(matrixWorld).multiplyScalar(this.size).add(_v1$1); position.setXYZ(idx, _v1$1.x, _v1$1.y, _v1$1.z); idx = idx + 1; position.setXYZ(idx, _v2$1.x, _v2$1.y, _v2$1.z); idx = idx + 1; } position.needsUpdate = true; } dispose() { this.geometry.dispose(); this.material.dispose(); } }; //#endregion //#region node_modules/three-stdlib/helpers/PositionalAudioHelper.js var PositionalAudioHelper = class extends Line { constructor(audio, range = 1, divisionsInnerAngle = 16, divisionsOuterAngle = 2) { const geometry = new BufferGeometry(); const divisions = divisionsInnerAngle + divisionsOuterAngle * 2; const positions = new Float32Array((divisions * 3 + 3) * 3); geometry.setAttribute("position", new BufferAttribute(positions, 3)); const materialInnerAngle = new LineBasicMaterial({ color: 65280 }); const materialOuterAngle = new LineBasicMaterial({ color: 16776960 }); super(geometry, [materialOuterAngle, materialInnerAngle]); this.type = "PositionalAudioHelper"; this.audio = audio; this.range = range; this.divisionsInnerAngle = divisionsInnerAngle; this.divisionsOuterAngle = divisionsOuterAngle; this.update(); } update() { const audio = this.audio; const range = this.range; const divisionsInnerAngle = this.divisionsInnerAngle; const divisionsOuterAngle = this.divisionsOuterAngle; const coneInnerAngle = MathUtils.degToRad(audio.panner.coneInnerAngle); const coneOuterAngle = MathUtils.degToRad(audio.panner.coneOuterAngle); const halfConeInnerAngle = coneInnerAngle / 2; const halfConeOuterAngle = coneOuterAngle / 2; let start = 0; let count = 0; let i, stride; const geometry = this.geometry; const positionAttribute = geometry.attributes.position; geometry.clearGroups(); function generateSegment(from, to, divisions, materialIndex) { const step = (to - from) / divisions; positionAttribute.setXYZ(start, 0, 0, 0); count++; for (i = from; i < to; i += step) { stride = start + count; positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range); positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range); positionAttribute.setXYZ(stride + 2, 0, 0, 0); count += 3; } geometry.addGroup(start, count, materialIndex); start += count; count = 0; } generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0); generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1); generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0); positionAttribute.needsUpdate = true; if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false; } dispose() { this.geometry.dispose(); this.material[0].dispose(); this.material[1].dispose(); } }; //#endregion //#region node_modules/three-stdlib/helpers/VertexNormalsHelper.js var _v1 = /* @__PURE__ */ new Vector3(); var _v2 = /* @__PURE__ */ new Vector3(); var _normalMatrix = /* @__PURE__ */ new Matrix3(); var VertexNormalsHelper = class extends LineSegments { constructor(object, size = 1, color = 16711680) { const geometry = new BufferGeometry(); const nNormals = object.geometry.attributes.normal.count; const positions = new Float32BufferAttribute(nNormals * 2 * 3, 3); geometry.setAttribute("position", positions); super(geometry, new LineBasicMaterial({ color, toneMapped: false })); this.object = object; this.size = size; this.type = "VertexNormalsHelper"; this.matrixAutoUpdate = false; this.update(); } update() { this.object.updateMatrixWorld(true); _normalMatrix.getNormalMatrix(this.object.matrixWorld); const matrixWorld = this.object.matrixWorld; const position = this.geometry.attributes.position; const objGeometry = this.object.geometry; if (objGeometry) { const objPos = objGeometry.attributes.position; const objNorm = objGeometry.attributes.normal; let idx = 0; for (let j = 0, jl = objPos.count; j < jl; j++) { _v1.fromBufferAttribute(objPos, j).applyMatrix4(matrixWorld); _v2.fromBufferAttribute(objNorm, j); _v2.applyMatrix3(_normalMatrix).normalize().multiplyScalar(this.size).add(_v1); position.setXYZ(idx, _v1.x, _v1.y, _v1.z); idx = idx + 1; position.setXYZ(idx, _v2.x, _v2.y, _v2.z); idx = idx + 1; } } position.needsUpdate = true; } dispose() { this.geometry.dispose(); this.material.dispose(); } }; //#endregion //#region node_modules/three-stdlib/helpers/RectAreaLightHelper.js var RectAreaLightHelper = class extends Line { constructor(light, color) { const positions = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0 ]; const geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); geometry.computeBoundingSphere(); const material = new LineBasicMaterial({ fog: false }); super(geometry, material); this.light = light; this.color = color; this.type = "RectAreaLightHelper"; const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ]; const geometry2 = new BufferGeometry(); geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3)); geometry2.computeBoundingSphere(); this.add(new Mesh(geometry2, new MeshBasicMaterial({ side: 1, fog: false }))); } updateMatrixWorld() { this.scale.set(.5 * this.light.width, .5 * this.light.height, 1); if (this.color !== void 0) { this.material.color.set(this.color); this.children[0].material.color.set(this.color); } else { this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity); const c = this.material.color; const max = Math.max(c.r, c.g, c.b); if (max > 1) c.multiplyScalar(1 / max); this.children[0].material.color.copy(this.material.color); } this.matrixWorld.extractRotation(this.light.matrixWorld).scale(this.scale).copyPosition(this.light.matrixWorld); this.children[0].matrixWorld.copy(this.matrixWorld); } dispose() { this.geometry.dispose(); this.material.dispose(); this.children[0].geometry.dispose(); this.children[0].material.dispose(); } }; //#endregion //#region node_modules/three-stdlib/lights/RectAreaLightUniformsLib.js var RectAreaLightUniformsLib = { init() { const LTC_MAT_1 = [ 1, 0, 0, 2e-5, 1, 0, 0, 503905e-9, 1, 0, 0, .00201562, 1, 0, 0, .00453516, 1, 0, 0, .00806253, 1, 0, 0, .0125978, 1, 0, 0, .018141, 1, 0, 0, .0246924, 1, 0, 0, .0322525, 1, 0, 0, .0408213, 1, 0, 0, .0503999, 1, 0, 0, .0609894, 1, 0, 0, .0725906, 1, 0, 0, .0852058, 1, 0, 0, .0988363, 1, 0, 0, .113484, 1, 0, 0, .129153, 1, 0, 0, .145839, 1, 0, 0, .163548, 1, 0, 0, .182266, 1, 0, 0, .201942, 1, 0, 0, .222314, 1, 0, 0, .241906, 1, 0, 0, .262314, 1, 0, 0, .285754, 1, 0, 0, .310159, 1, 0, 0, .335426, 1, 0, 0, .361341, 1, 0, 0, .387445, 1, 0, 0, .412784, 1, 0, 0, .438197, 1, 0, 0, .466966, 1, 0, 0, .49559, 1, 0, 0, .523448, 1, 0, 0, .549938, 1, 0, 0, .57979, 1, 0, 0, .608746, 1, 0, 0, .636185, 1, 0, 0, .664748, 1, 0, 0, .69313, 1, 0, 0, .71966, 1, 0, 0, .747662, 1, 0, 0, .774023, 1, 0, 0, .799775, 1, 0, 0, .825274, 1, 0, 0, .849156, 1, 0, 0, .873248, 1, 0, 0, .89532, 1, 0, 0, .917565, 1, 0, 0, .937863, 1, 0, 0, .958139, 1, 0, 0, .976563, 1, 0, 0, .994658, 1, 0, 0, 1.0112, 1, 0, 0, 1.02712, 1, 0, 0, 1.04189, 1, 0, 0, 1.05568, 1, 0, 0, 1.06877, 1, 0, 0, 1.08058, 1, 0, 0, 1.09194, 1, 0, 0, 1.10191, 1, 0, 0, 1.11161, 1, 0, 0, 1.1199, 1, 0, 0, 1.12813, .999547, -4.48815e-7, .0224417, 199902e-10, .999495, -113079e-10, .0224406, 503651e-9, .999496, -452317e-10, .0224406, .00201461, .999496, -101772e-9, .0224406, .00453287, .999495, -180928e-9, .0224406, .00805845, .999497, -282702e-9, .0224406, .0125914, .999496, -407096e-9, .0224406, .0181319, .999498, -554114e-9, .0224406, .02468, .999499, -723768e-9, .0224406, .0322363, .999495, -916058e-9, .0224405, .0408009, .999499, -.00113101, .0224408, .050375, .999494, -.00136863, .0224405, .0609586, .999489, -.00162896, .0224401, .0725537, .999489, -.00191201, .0224414, .0851619, .999498, -.00221787, .0224413, .0987867, .999492, -.00254642, .0224409, .113426, .999507, -.00289779, .0224417, .129088, .999494, -.0032716, .0224386, .145767, .999546, -.0036673, .0224424, .163472, .999543, -.00408166, .0224387, .182182, .999499, -.00450056, .0224338, .201843, .999503, -.00483661, .0224203, .222198, .999546, -.00452928, .022315, .241714, .999508, -.00587403, .0224329, .262184, .999509, -.00638806, .0224271, .285609, .999501, -.00691028, .0224166, .309998, .999539, -.00741979, .0223989, .335262, .999454, -.00786282, .0223675, .361154, .999529, -.00811928, .0222828, .387224, .999503, -.00799941, .0221063, .41252, .999561, -.00952753, .0223057, .438006, .999557, -.0099134, .0222065, .466735, .999541, -.0100935, .0220402, .495332, .999562, -.00996821, .0218067, .523197, .999556, -.0105031, .0217096, .550223, .999561, -.0114191, .0217215, .579498, .999588, -.0111818, .0213357, .608416, .999633, -.0107725, .0208689, .635965, .999527, -.0121671, .0210149, .664476, .999508, -.0116005, .020431, .692786, .999568, -.0115604, .0199791, .719709, .999671, -.0121117, .0197415, .74737, .999688, -.0110769, .0188846, .773692, .99962, -.0122368, .0188452, .799534, .999823, -.0110325, .0178001, .825046, .999599, -.0114923, .0174221, .849075, .999619, -.0105923, .0164345, .872999, .999613, -.0105988, .0158227, .895371, .99964, -.00979861, .0148131, .917364, .99977, -.00967238, .0140721, .938002, .999726, -.00869175, .0129543, .957917, .99973, -.00866872, .0122329, .976557, .999773, -.00731956, .0108958, .994459, .999811, -.00756027, .0102715, 1.01118, .999862, -.00583732, .00878781, 1.02701, .999835, -.00631438, .00827529, 1.04186, .999871, -.00450785, .00674583, 1.05569, .999867, -.00486079, .00621041, 1.06861, .999939, -.00322072, .00478301, 1.08064, .999918, -.00318199, .00406395, 1.09181, 1.00003, -.00193348, .00280682, 1.10207, .999928, -.00153729, .00198741, 1.11152, .999933, -623666e-9, 917714e-9, 1.12009, 1, -102387e-11, 9.07581e-7, 1.12813, .997866, -8.96716e-7, .0448334, 199584e-10, .997987, -225945e-10, .0448389, 502891e-9, .997987, -903781e-10, .0448388, .00201156, .997985, -203351e-9, .0448388, .00452602, .997986, -361514e-9, .0448388, .00804629, .997987, -56487e-8, .0448389, .0125724, .997988, -813423e-9, .0448389, .0181045, .997984, -.00110718, .0448387, .0246427, .997985, -.00144616, .0448388, .0321875, .997987, -.00183038, .044839, .0407392, .997983, -.00225987, .0448387, .0502986, .997991, -.00273467, .0448389, .0608667, .997984, -.00325481, .0448384, .0724444, .998002, -.00382043, .044839, .0850348, .997997, -.00443145, .0448396, .0986372, .998007, -.00508796, .0448397, .113255, .998008, -.00578985, .04484, .128891, .998003, -.00653683, .0448384, .145548, .997983, -.00732713, .0448358, .163221, .997985, -.00815454, .0448358, .181899, .998005, -.00898985, .0448286, .201533, .998026, -.00964404, .0447934, .221821, .998055, -.00922677, .044611, .241282, .99804, -.0117361, .0448245, .261791, .998048, -.0127628, .0448159, .285181, .998088, -.0138055, .0447996, .30954, .998058, -.0148206, .0447669, .334751, .998099, -.0156998, .044697, .36061, .998116, -.0161976, .0445122, .386603, .998195, -.015945, .0441711, .411844, .998168, -.0183947, .0444255, .43773, .998184, -.0197913, .0443809, .466009, .998251, -.0201426, .0440689, .494574, .998305, -.0198847, .0435632, .522405, .998273, -.0210577, .043414, .549967, .998254, -.0227901, .0433943, .578655, .998349, -.0223108, .0426529, .60758, .99843, -.0223088, .042, .635524, .998373, -.0241141, .0418987, .663621, .998425, -.0231446, .0408118, .691906, .998504, -.0233684, .0400565, .719339, .998443, -.0241652, .0394634, .74643, .99848, -.0228715, .0380002, .773086, .998569, -.023519, .0372322, .798988, .998619, -.0223108, .0356468, .824249, .998594, -.0223105, .034523, .848808, .998622, -.0213426, .0328887, .87227, .998669, -.0207912, .0314374, .895157, .998705, -.0198416, .0296925, .916769, .998786, -.0189168, .0279634, .937773, .998888, -.0178811, .0261597, .957431, .99906, -.0166845, .0242159, .976495, .999038, -.0155464, .0222638, .994169, .999237, -.0141349, .0201967, 1.01112, .999378, -.0129324, .0181744, 1.02692, .999433, -.0113192, .0159898, 1.04174, .999439, -.0101244, .0140385, 1.05559, .999614, -.00837456, .0117826, 1.06852, .999722, -.00721769, .00983745, 1.08069, .999817, -.00554067, .00769002, 1.09176, .99983, -.00426961, .005782, 1.10211, .999964, -.00273904, .00374503, 1.11152, 1.00001, -.00136739, .00187176, 1.12031, .999946, 393227e-10, -28919e-9, 1.12804, .995847, -13435e-10, .0671785, 19916e-9, .995464, -338387e-10, .0671527, 501622e-9, .99547, -135355e-9, .0671531, .00200649, .995471, -30455e-8, .0671532, .00451461, .99547, -541423e-9, .0671531, .008026, .995471, -84598e-8, .0671531, .0125407, .99547, -.00121823, .0671531, .0180589, .99547, -.00165817, .0671531, .0245806, .995463, -.00216583, .0671526, .0321062, .995468, -.00274127, .0671527, .0406366, .995474, -.00338447, .0671534, .0501717, .995473, -.00409554, .0671533, .0607131, .995478, -.00487451, .0671531, .0722618, .995476, -.00572148, .0671532, .0848191, .995477, -.00663658, .0671539, .0983882, .995498, -.00761986, .0671541, .112972, .995509, -.00867094, .0671542, .128568, .995509, -.00978951, .0671531, .145183, .995503, -.0109725, .0671491, .162808, .995501, -.012211, .0671465, .181441, .99553, -.0134565, .0671371, .201015, .99555, -.014391, .0670831, .221206, .99558, -.014351, .0668883, .240813, .995577, -.0173997, .0671055, .261257, .995602, -.0191111, .0671178, .284467, .995623, -.0206705, .0670946, .308765, .995658, -.022184, .0670472, .333905, .995705, -.0234832, .0669417, .359677, .995719, -.0241933, .0666714, .385554, .995786, -.0243539, .066266, .410951, .995887, -.0271866, .0664367, .437163, .995944, -.0296012, .0664931, .464842, .996004, -.0301045, .0660105, .49332, .996128, -.0298311, .0652694, .521131, .996253, -.0316426, .0650739, .549167, .996244, -.0339043, .0649433, .57737, .996309, -.033329, .0638926, .606073, .996417, -.0338935, .0630849, .634527, .996372, -.0353104, .0625083, .66256, .996542, -.0348942, .0611986, .690516, .996568, -.0351614, .060069, .718317, .996711, -.0354317, .0588522, .74528, .996671, -.0349513, .0571902, .772061, .996865, -.0345622, .0555321, .798089, .996802, -.0342566, .0537816, .823178, .996992, -.0330862, .0516095, .847949, .996944, -.0324666, .0495537, .871431, .997146, -.0309544, .0470302, .894357, .997189, -.0299372, .0446043, .916142, .997471, -.0281389, .0418812, .937193, .997515, -.0268702, .0391823, .957, .997812, -.0247166, .0361338, .975936, .998027, -.0233525, .0333945, .99391, .998233, -.0209839, .0301917, 1.01075, .998481, -.0194309, .027271, 1.02669, .998859, -.0169728, .0240162, 1.04173, .99894, -.0152322, .0210517, 1.05551, .999132, -.0127497, .0178632, 1.06856, .999369, -.0108282, .014787, 1.08054, .999549, -.00845886, .0116185, 1.09185, .999805, -.0063937, .00867209, 1.10207, .99985, -.00414582, .00566823, 1.1117, .999912, -.00207443, .00277562, 1.12022, 1.00001, 870226e-10, -53766e-9, 1.12832, .991943, -178672e-11, .0893382, 198384e-10, .991952, -450183e-10, .089339, 499849e-9, .991956, -180074e-9, .0893394, .0019994, .991955, -405167e-9, .0893393, .00449867, .991953, -720298e-9, .0893391, .00799764, .991955, -.00112548, .0893393, .0124964, .991957, -.0016207, .0893395, .0179951, .991958, -.00220601, .0893396, .0244939, .991947, -.00288137, .0893385, .0319929, .991962, -.00364693, .0893399, .0404933, .991965, -.00450264, .0893399, .049995, .99198, -.00544862, .0893411, .0604995, .99197, -.00648491, .0893397, .0720074, .991976, -.00761164, .089341, .0845207, .99198, -.00882891, .0893405, .0980413, .991982, -.0101367, .0893396, .112571, .992008, -.011535, .0893415, .128115, .992026, -.0130228, .0893414, .144672, .992064, -.0145966, .0893418, .162241, .992041, -.0162421, .0893359, .180801, .992086, -.0178888, .0893214, .200302, .992157, -.0190368, .0892401, .220332, .992181, -.0195584, .0890525, .240144, .992175, -.0227257, .0892153, .260728, .99221, -.0254195, .089304, .283473, .99222, -.0274883, .0892703, .307673, .992317, -.0294905, .0892027, .332729, .992374, -.0311861, .0890577, .358387, .992505, -.0320656, .0886994, .384102, .992568, -.0329715, .0883198, .409767, .992675, -.036006, .0883602, .436145, .992746, -.0392897, .0884591, .463217, .992873, -.0399337, .0878287, .491557, .992934, -.040231, .0870108, .519516, .993091, -.0422013, .0865857, .547741, .993259, -.0443503, .0861937, .575792, .993455, -.0446368, .0851187, .604233, .993497, -.0454299, .0840576, .632925, .993694, -.0463296, .0829671, .660985, .993718, -.0470619, .0817185, .688714, .993973, -.0468838, .0800294, .716743, .994207, -.046705, .0781286, .74377, .994168, -.0469698, .0763337, .77042, .9945, -.0456816, .0738184, .796659, .994356, -.0455518, .0715545, .821868, .994747, -.0439488, .0686085, .846572, .994937, -.0430056, .065869, .870435, .995142, -.0413414, .0626446, .893272, .995451, -.0396521, .05929, .915376, .995445, -.0378453, .0558503, .936196, .995967, -.0355219, .0520949, .956376, .996094, -.0335146, .048377, .975327, .996622, -.030682, .0442575, .993471, .996938, -.0285504, .0404693, 1.01052, .997383, -.0253399, .0360903, 1.02637, .997714, -.0231651, .0322176, 1.04139, .998249, -.0198138, .0278433, 1.05542, .998596, -.0174337, .0238759, 1.06846, .998946, -.0141349, .0195944, 1.08056, .99928, -.0115603, .0156279, 1.09181, .999507, -.00839065, .0114607, 1.10213, .999697, -.005666, .00763325, 1.11169, .999869, -.00269902, .00364946, 1.12042, 1.00001, 623836e-10, -319288e-10, 1.12832, .987221, -222675e-11, .111332, 197456e-10, .98739, -561116e-10, .111351, 497563e-9, .987448, -224453e-9, .111357, .00199031, .987441, -505019e-9, .111357, .0044782, .987442, -897816e-9, .111357, .00796129, .987442, -.00140284, .111357, .0124396, .987444, -.00202012, .111357, .0179132, .987442, -.00274964, .111357, .0243824, .987446, -.00359147, .111357, .0318474, .987435, -.00454562, .111356, .0403086, .987461, -.00561225, .111358, .0497678, .987458, -.00679125, .111358, .0602239, .987443, -.0080828, .111356, .0716792, .987476, -.0094872, .111358, .0841364, .98749, -.0110044, .111361, .097597, .987508, -.0126344, .111362, .112062, .987494, -.0143767, .111357, .127533, .987526, -.0162307, .111359, .144015, .987558, -.0181912, .111361, .161502, .987602, -.0202393, .111355, .179979, .987692, -.022273, .111346, .199386, .987702, -.0235306, .111215, .219183, .987789, -.0247628, .111061, .239202, .987776, -.0280668, .111171, .259957, .987856, -.0316751, .111327, .282198, .987912, -.0342468, .111282, .306294, .988, -.0367205, .111198, .331219, .988055, -.0387766, .110994, .356708, .988241, -.0397722, .110547, .382234, .988399, -.0416076, .110198, .408227, .988539, -.0448192, .110137, .434662, .988661, -.0483793, .110143, .461442, .988967, -.0495895, .109453, .489318, .989073, -.0506797, .108628, .517516, .989274, -.0526953, .108003, .545844, .989528, -.054578, .107255, .573823, .989709, -.0561503, .106294, .601944, .989991, -.056866, .104896, .630855, .990392, -.0572914, .103336, .658925, .990374, -.0586224, .10189, .686661, .990747, -.0584764, .099783, .714548, .991041, -.0582662, .0974309, .74186, .991236, -.0584118, .0951678, .768422, .991585, -.0573055, .0921581, .794817, .991984, -.0564241, .0891167, .820336, .9921, -.0553608, .085805, .84493, .992749, -.0533816, .0820354, .868961, .99288, -.0518661, .0782181, .891931, .993511, -.0492492, .0738935, .914186, .993617, -.0471956, .0696402, .93532, .99411, -.044216, .0649659, .95543, .994595, -.0416654, .0603177, .974685, .994976, -.0384314, .0553493, .992807, .995579, -.0353491, .0503942, 1.00996, .996069, -.0319787, .0452123, 1.02606, .996718, -.028472, .0400112, 1.04114, .997173, -.0250789, .0349456, 1.05517, .997818, -.0213326, .029653, 1.0683, .998318, -.0178509, .024549, 1.0805, .998853, -.0141118, .0194197, 1.09177, .999218, -.0105914, .0143869, 1.1022, .999594, -.00693474, .00943517, 1.11175, .99975, -.00340478, .00464051, 1.12056, 1.00001, 109172e-9, -112821e-9, 1.12853, .983383, -266524e-11, .133358, 196534e-10, .981942, -671009e-10, .133162, 494804e-9, .981946, -268405e-9, .133163, .00197923, .981944, -603912e-9, .133163, .00445326, .981941, -.00107362, .133162, .00791693, .981946, -.00167755, .133163, .0123703, .981944, -.00241569, .133162, .0178135, .981945, -.00328807, .133163, .0242466, .981945, -.00429472, .133162, .03167, .981955, -.00543573, .133164, .0400846, .981951, -.00671105, .133163, .0494901, .981968, -.00812092, .133165, .0598886, .981979, -.00966541, .133166, .0712811, .981996, -.0113446, .133168, .083669, .982014, -.0131585, .133169, .0970533, .982011, -.0151073, .133167, .111438, .982062, -.0171906, .133172, .126826, .9821, -.0194067, .133175, .143215, .982149, -.0217502, .133176, .160609, .982163, -.0241945, .133173, .178981, .982247, -.0265907, .133148, .198249, .982291, -.027916, .132974, .217795, .982396, -.0299663, .132868, .238042, .982456, -.0334544, .132934, .258901, .982499, -.0378636, .133137, .280639, .982617, -.0409274, .133085, .304604, .98274, -.0438523, .132985, .329376, .982944, -.0462288, .132728, .354697, .98308, -.0475995, .132228, .380102, .983391, -.0501901, .131924, .406256, .983514, -.0535899, .131737, .432735, .98373, -.0571858, .131567, .459359, .984056, -.0592353, .130932, .486637, .984234, -.0610488, .130092, .51509, .984748, -.0630758, .12923, .543461, .985073, -.0647398, .128174, .571376, .985195, -.0671941, .127133, .599414, .985734, -.0681345, .125576, .628134, .986241, -.0686089, .123639, .656399, .986356, -.0698511, .121834, .684258, .986894, -.0700931, .119454, .711818, .987382, -.0698321, .116718, .739511, .988109, -.0693975, .113699, .766267, .988363, -.0689584, .110454, .792456, .989112, -.0672353, .106602, .81813, .989241, -.0662034, .10267, .842889, .990333, -.0638938, .0981381, .867204, .990591, -.0618534, .0935388, .89038, .991106, -.0593117, .088553, .912576, .991919, -.0562676, .0832187, .934118, .992111, -.0534085, .0778302, .954254, .992997, -.0495459, .0720453, .973722, .993317, -.0463707, .0663458, .991949, .994133, -.0421245, .0601883, 1.00936, .994705, -.0384977, .0542501, 1.02559, .995495, -.0340956, .0479862, 1.04083, .996206, -.030105, .041887, 1.05497, .996971, -.0256095, .0355355, 1.06824, .997796, -.0213932, .0293655, 1.08056, .998272, -.0169612, .0232926, 1.09182, .998857, -.0126756, .0172786, 1.10219, .99939, -.00832486, .0113156, 1.11192, .999752, -.00410826, .00557892, 1.12075, 1, 150957e-9, -119101e-9, 1.12885, .975169, -309397e-11, .154669, 195073e-10, .975439, -779608e-10, .154712, 491534e-9, .975464, -311847e-9, .154716, .00196617, .975464, -701656e-9, .154716, .00442387, .975462, -.0012474, .154715, .0078647, .975461, -.00194906, .154715, .0122886, .975464, -.00280667, .154715, .0176959, .975468, -.00382025, .154716, .0240867, .975471, -.00498985, .154716, .0314612, .975472, -.00631541, .154717, .0398199, .975486, -.00779719, .154718, .0491639, .975489, -.00943505, .154718, .0594932, .975509, -.0112295, .154721, .0708113, .97554, -.0131802, .154724, .0831176, .975557, -.0152876, .154726, .096415, .975585, -.0175512, .154728, .110705, .975605, -.0199713, .154729, .125992, .975645, -.0225447, .154729, .142272, .975711, -.0252649, .154735, .159549, .975788, -.0280986, .154736, .177805, .975872, -.0308232, .154704, .196911, .975968, -.0324841, .154525, .216324, .976063, -.0351281, .154432, .236628, .976157, -.0388618, .15446, .257539, .976204, -.0437704, .154665, .278975, .976358, -.047514, .154652, .302606, .976571, -.0508638, .154535, .327204, .976725, -.0534995, .154221, .352276, .977013, -.0555547, .153737, .377696, .977294, -.0586728, .153403, .403855, .977602, -.0622715, .15312, .430333, .977932, -.0658166, .152755, .456855, .978241, -.0689877, .152233, .483668, .978602, -.0712805, .15132, .512097, .979234, -.0732775, .150235, .540455, .97977, -.075163, .148978, .568486, .979995, -.0778026, .147755, .596524, .98078, -.0791854, .146019, .624825, .981628, -.0799666, .143906, .653403, .982067, -.0808532, .141561, .681445, .98271, -.0816024, .139025, .708918, .983734, -.0812511, .135764, .736594, .98431, -.0806201, .132152, .763576, .985071, -.0801605, .12846, .789797, .98618, -.0784208, .124084, .815804, .986886, -.0766643, .1193, .840869, .987485, -.0747744, .114236, .864952, .988431, -.0716701, .108654, .888431, .988886, -.0691609, .102994, .910963, .990024, -.0654048, .0967278, .932629, .990401, -.0619765, .090384, .95313, .991093, -.0579296, .0837885, .972587, .992018, -.0536576, .0770171, .991184, .992536, -.0493719, .0701486, 1.00863, .993421, -.0444813, .062953, 1.02494, .993928, -.040008, .0560455, 1.04017, .994994, -.0347982, .04856, 1.05463, .995866, -.0301017, .0416152, 1.06807, .996916, -.0248225, .0342597, 1.08039, .997766, -.0199229, .0271668, 1.09177, .998479, -.0147422, .0201387, 1.10235, .99921, -.00980173, .0131944, 1.11206, .999652, -.0047426, .00640712, 1.12104, .999998, 891673e-10, -10379e-8, 1.12906, .967868, -351885e-11, .175947, 193569e-10, .968001, -886733e-10, .175972, 487782e-9, .96801, -354697e-9, .175973, .00195115, .968012, -798063e-9, .175974, .00439006, .968011, -.00141879, .175973, .00780461, .968011, -.00221686, .175973, .0121948, .968016, -.00319231, .175974, .0175607, .968019, -.00434515, .175974, .0239027, .968018, -.00567538, .175974, .0312208, .968033, -.00718308, .175977, .0395158, .968049, -.00886836, .175979, .0487885, .968047, -.0107312, .175978, .0590394, .968072, -.0127719, .175981, .0702705, .968108, -.0149905, .175986, .0824836, .968112, -.0173866, .175985, .0956783, .968173, -.0199611, .175993, .109862, .96827, -.0227128, .176008, .125033, .968292, -.025639, .17601, .141193, .968339, -.0287299, .176007, .158336, .968389, -.0319399, .176001, .176441, .968501, -.034941, .175962, .195359, .968646, -.0370812, .175793, .214686, .968789, -.0402329, .175708, .234973, .96886, -.0442601, .1757, .255871, .969013, -.049398, .175876, .277238, .969242, -.0539932, .17594, .300326, .969419, -.0577299, .175781, .324702, .969763, -.0605643, .175432, .349527, .970093, -.0634488, .174992, .374976, .970361, -.0670589, .174611, .401097, .970825, -.0708246, .174226, .427496, .971214, -.0742871, .173684, .453858, .971622, -.0782608, .173186, .480637, .972175, -.0813151, .172288, .508655, .972944, -.0832678, .170979, .536973, .973595, -.0855964, .169573, .565138, .974345, -.0882163, .168152, .593222, .975233, -.0901671, .166314, .621201, .976239, -.0912111, .163931, .649919, .977289, -.0916959, .161106, .678011, .978076, -.0927061, .158272, .705717, .979533, -.0925562, .15475, .733228, .980335, -.0918159, .150638, .760454, .981808, -.0908508, .146201, .786918, .983061, -.0896172, .141386, .812953, .984148, -.0871588, .135837, .838281, .985047, -.0850624, .130135, .862594, .986219, -.0818541, .123882, .88633, .987043, -.0784523, .117126, .908952, .988107, -.0749601, .110341, .930744, .988955, -.0703548, .102885, .951728, .989426, -.0662798, .0954167, .971166, .990421, -.0610834, .0876331, .989984, .991032, -.0562936, .0797785, 1.00765, .992041, -.0508154, .0718166, 1.02434, .992794, -.0454045, .0637125, 1.03976, .993691, -.0398194, .0555338, 1.05418, .994778, -.0341482, .0473388, 1.06772, .995915, -.028428, .0391016, 1.08028, .997109, -.022642, .0309953, 1.09185, .998095, -.0168738, .0230288, 1.10247, .998985, -.0111274, .0150722, 1.11229, .999581, -.00543881, .00740605, 1.12131, 1.00003, 162239e-9, -105549e-9, 1.12946, .959505, -393734e-11, .196876, 191893e-10, .959599, -992157e-10, .196895, 483544e-9, .959641, -396868e-9, .196903, .0019342, .959599, -892948e-9, .196895, .00435193, .959603, -.00158747, .196896, .0077368, .959604, -.00248042, .196896, .0120888, .959605, -.00357184, .196896, .0174082, .959605, -.00486169, .196896, .0236949, .959613, -.00635008, .196897, .0309497, .959619, -.00803696, .196898, .0391725, .959636, -.00992255, .196901, .0483649, .959634, -.0120067, .1969, .0585266, .959675, -.0142898, .196906, .0696609, .959712, -.0167717, .196911, .0817678, .959752, -.0194524, .196918, .0948494, .959807, -.0223321, .196925, .10891, .959828, -.0254091, .196924, .123947, .959906, -.0286815, .196934, .139968, .960005, -.0321371, .196944, .156968, .960071, -.0357114, .196936, .17491, .960237, -.0389064, .196882, .193597, .960367, -.041623, .196731, .21285, .960562, -.0452655, .196654, .233075, .960735, -.0496207, .196643, .253941, .960913, -.0549379, .196774, .275278, .961121, -.0603414, .196893, .297733, .96139, -.0644244, .196717, .321877, .961818, -.067556, .196314, .346476, .962175, -.0712709, .195917, .371907, .96255, -.0752848, .1955, .397916, .963164, -.0792073, .195026, .424229, .963782, -.0828225, .194424, .450637, .964306, -.0873119, .193831, .477288, .964923, -.0911051, .192973, .504716, .966048, -.093251, .19151, .533053, .967024, -.0958983, .190013, .561366, .968038, -.09835, .188253, .589464, .969152, -.100754, .186257, .617433, .970557, -.102239, .183775, .645801, .972104, -.102767, .180645, .674278, .973203, -.103492, .177242, .702004, .975123, -.103793, .17345, .729529, .97641, -.102839, .168886, .756712, .978313, -.101687, .163892, .783801, .980036, -.100314, .158439, .809671, .981339, -.097836, .152211, .835402, .982794, -.0950006, .145679, .860081, .984123, -.0920994, .138949, .883757, .984918, -.0878641, .131283, .90685, .985999, -.083939, .123464, .928786, .987151, -.0791234, .115324, .94983, .987827, -.0739332, .106854, .96962, .988806, -.0688088, .0982691, .98861, .989588, -.0628962, .0893456, 1.00667, .990438, -.0573146, .0805392, 1.02344, .991506, -.0509433, .0713725, 1.03933, .992492, -.0448724, .0623732, 1.05378, .993663, -.0383497, .0530838, 1.06747, .994956, -.0319593, .0439512, 1.08007, .99634, -.025401, .0347803, 1.09182, .99761, -.0189687, .0257954, 1.1025, .99863, -.0124441, .0169893, 1.11247, .99947, -.00614003, .00829498, 1.12151, 1.00008, 216624e-9, -146107e-9, 1.12993, .950129, -434955e-11, .217413, 190081e-10, .950264, -10957e-8, .217444, 47884e-8, .9503, -438299e-9, .217451, .00191543, .950246, -986124e-9, .21744, .00430951, .950246, -.00175311, .21744, .00766137, .950245, -.00273923, .21744, .011971, .950253, -.00394453, .217441, .0172385, .950258, -.00536897, .217442, .0234641, .950267, -.00701262, .217444, .030648, .950277, -.00887551, .217446, .038791, .950284, -.0109576, .217446, .0478931, .950312, -.0132591, .217451, .0579568, .950334, -.01578, .217454, .0689821, .950378, -.0185204, .217462, .0809714, .950417, -.0214803, .217467, .0939265, .950488, -.0246594, .217479, .10785, .950534, -.0280565, .217483, .122743, .950633, -.0316685, .217498, .138611, .950698, -.0354787, .217499, .155442, .950844, -.0394003, .217507, .173208, .950999, -.0426812, .217419, .191605, .951221, -.0461302, .217317, .21084, .951412, -.0502131, .217238, .230945, .951623, -.0549183, .21722, .251745, .951867, -.0604493, .217306, .273001, .952069, -.0665189, .217466, .294874, .952459, -.0709179, .217266, .318732, .952996, -.0746112, .216891, .34318, .953425, -.0789252, .216503, .36849, .953885, -.0833293, .216042, .394373, .954617, -.087371, .215469, .420505, .955429, -.0914054, .214802, .446907, .956068, -.0961671, .214146, .473522, .957094, -.10048, .213286, .50052, .958372, -.103248, .211796, .528715, .959654, -.106033, .21016, .557065, .961305, -.108384, .208149, .585286, .962785, -.111122, .206024, .613334, .964848, -.112981, .203442, .641334, .966498, -.113717, .19996, .669955, .968678, -.114121, .196105, .698094, .970489, -.114524, .191906, .725643, .972903, -.113792, .186963, .752856, .974701, -.112406, .181343, .780013, .976718, -.110685, .175185, .806268, .978905, -.108468, .168535, .832073, .980267, -.105061, .161106, .857149, .981967, -.101675, .153387, .881145, .983063, -.0974492, .145199, .904255, .984432, -.0925815, .136527, .926686, .985734, -.0877983, .127584, .947901, .986228, -.081884, .118125, .968111, .98719, -.0761208, .108594, .98719, .988228, -.0698196, .0989996, 1.00559, .989046, -.0632739, .0890074, 1.02246, .990242, -.056522, .0790832, 1.03841, .991252, -.0495272, .0689182, 1.05347, .992542, -.0425373, .0588592, 1.06724, .994096, -.0353198, .0486833, 1.08009, .995593, -.028235, .0385977, 1.09177, .99711, -.0209511, .0286457, 1.10274, .998263, -.0139289, .0188497, 1.11262, .999254, -.0067359, .009208, 1.12191, .999967, 141846e-9, -657764e-10, 1.13024, .935608, -474692e-11, .236466, 187817e-10, .93996, -11971e-8, .237568, 473646e-9, .939959, -478845e-9, .237567, .0018946, .939954, -.0010774, .237566, .00426284, .939956, -.00191538, .237566, .00757842, .939954, -.00299277, .237566, .0118413, .93996, -.00430961, .237567, .0170518, .939969, -.00586589, .237569, .02321, .939982, -.00766166, .237572, .0303164, .939987, -.00969686, .237572, .0383711, .939997, -.0119715, .237574, .0473751, .940031, -.0144858, .237581, .0573298, .940073, -.0172399, .237589, .0682366, .94012, -.0202335, .237598, .080097, .940162, -.0234663, .237604, .0929116, .940237, -.0269387, .237615, .106686, .940328, -.0306489, .237632, .121421, .940419, -.0345917, .237645, .137115, .940522, -.0387481, .237654, .153766, .940702, -.0429906, .237661, .17133, .940871, -.0465089, .237561, .189502, .941103, -.050531, .23748, .208616, .941369, -.0550657, .237423, .228595, .941641, -.0601337, .237399, .249287, .941903, -.0658804, .237443, .270467, .942224, -.0722674, .237597, .292024, .942633, -.0771788, .237419, .315272, .943172, -.0815623, .237068, .339579, .943691, -.0863973, .236682, .364717, .944382, -.0911536, .236213, .390435, .945392, -.0952967, .235562, .416425, .946185, -.0998948, .234832, .442772, .947212, -.104796, .234114, .469347, .948778, -.10928, .233222, .496162, .950149, -.113081, .231845, .523978, .951989, -.115893, .230005, .552295, .953921, -.11846, .227862, .580569, .955624, -.12115, .225439, .608698, .958234, -.123373, .222635, .636696, .960593, -.124519, .219093, .665208, .963201, -.124736, .214749, .693557, .965642, -.125012, .210059, .721334, .968765, -.124661, .204935, .748613, .971753, -.122996, .198661, .776224, .973751, -.120998, .191823, .802461, .976709, -.118583, .184359, .828399, .977956, -.115102, .176437, .853693, .979672, -.111077, .167681, .877962, .981816, -.10688, .158872, .901564, .98238, -.101469, .149398, .924057, .983964, -.0960013, .139436, .945751, .984933, -.0899626, .12943, .966272, .985694, -.0832973, .11894, .985741, .986822, -.0767082, .108349, 1.00407, .987725, -.0693614, .0976026, 1.02154, .98877, -.06211, .086652, 1.03757, .990129, -.0544143, .0756182, 1.05296, .991337, -.046744, .0645753, 1.06683, .992978, -.0387931, .0534683, 1.0798, .994676, -.030973, .0424137, 1.09181, .99645, -.0230311, .0314035, 1.10286, .997967, -.0152065, .0206869, 1.11291, .99922, -.00744837, .010155, 1.12237, 1.00002, 240209e-9, -752767e-10, 1.13089, .922948, -515351e-11, .255626, 186069e-10, .928785, -129623e-9, .257244, 468009e-9, .928761, -51849e-8, .257237, .00187202, .928751, -.0011666, .257235, .00421204, .928751, -.00207395, .257234, .0074881, .928754, -.00324055, .257235, .0117002, .92876, -.00466639, .257236, .0168486, .928763, -.00635149, .257237, .0229334, .928774, -.00829584, .257239, .029955, .928791, -.0104995, .257243, .0379139, .928804, -.0129623, .257245, .0468108, .928847, -.0156846, .257255, .0566473, .92889, -.0186661, .257263, .0674246, .928924, -.0219067, .257268, .0791433, .928989, -.0254066, .257282, .0918076, .92909, -.0291651, .257301, .105419, .92918, -.0331801, .257316, .119978, .92929, -.0374469, .257332, .135491, .929453, -.041939, .257357, .151948, .929586, -.0464612, .257347, .169275, .929858, -.0503426, .257269, .187257, .930125, -.0548409, .257199, .206204, .930403, -.0598063, .257149, .22601, .930726, -.0652437, .257122, .246561, .931098, -.0712376, .257153, .267618, .931396, -.0777506, .257237, .288993, .931947, -.0832374, .257124, .311527, .932579, -.0883955, .25683, .335697, .933194, -.0937037, .256444, .360634, .934013, -.0987292, .255939, .386126, .935307, -.103215, .255282, .412018, .936374, -.108234, .254538, .438292, .93776, -.113234, .253728, .464805, .939599, -.118013, .25275, .491464, .941036, -.122661, .251404, .518751, .94337, -.125477, .249435, .547133, .945318, -.128374, .247113, .575456, .947995, -.130996, .244441, .60372, .950818, -.133438, .241352, .63174, .954378, -.135004, .237849, .659971, .957151, -.135313, .233188, .688478, .960743, -.13521, .228001, .716767, .964352, -.135007, .222249, .744349, .967273, -.133523, .21542, .771786, .969767, -.131155, .208039, .798639, .973195, -.128492, .200076, .824774, .975557, -.125094, .191451, .850222, .977692, -.120578, .18184, .874761, .98026, -.115882, .172102, .898497, .981394, -.110372, .161859, .921636, .982386, -.10415, .15108, .943467, .983783, -.0978128, .140407, .964045, .98422, -.0906171, .129058, .98398, .985447, -.0832921, .117614, 1.00276, .986682, -.0754412, .10585, 1.02047, .987326, -.0673885, .0940943, 1.03678, .988707, -.0592565, .0822093, 1.05218, .990185, -.050717, .070192, 1.06652, .991866, -.0423486, .0582081, 1.07965, .993897, -.0336118, .0460985, 1.09188, .995841, -.0252178, .0342737, 1.10307, .997605, -.0164893, .0224829, 1.11324, .999037, -.00817112, .0110647, 1.12262, 1.00003, 291686e-9, -168673e-9, 1.13139, .915304, -552675e-11, .275999, 183285e-10, .91668, -139285e-9, .276414, 461914e-9, .916664, -55713e-8, .276409, .00184763, .916653, -.00125354, .276406, .00415715, .916651, -.00222851, .276405, .00739053, .916655, -.00348205, .276406, .0115478, .916653, -.00501414, .276405, .0166291, .916667, -.00682478, .276409, .0226346, .91668, -.00891398, .276412, .0295648, .91669, -.0112817, .276413, .0374199, .916727, -.013928, .276422, .0462016, .916759, -.0168528, .276429, .0559101, .916793, -.0200558, .276436, .0665466, .916849, -.0235373, .276448, .0781139, .916964, -.0272973, .276474, .0906156, .917047, -.0313344, .276491, .104051, .917152, -.0356465, .276511, .118424, .917286, -.0402271, .276533, .133736, .917469, -.0450408, .276564, .149978, .917686, -.0497872, .276563, .167057, .917953, -.0540937, .276493, .184846, .918228, -.0590709, .276437, .203614, .918572, -.0644277, .276398, .223212, .918918, -.0702326, .276362, .243584, .919356, -.076484, .276383, .264465, .919842, -.0830808, .276434, .285701, .920451, -.0892972, .276407, .307559, .921113, -.095016, .276128, .331501, .921881, -.100771, .275754, .356207, .923027, -.106029, .275254, .381477, .924364, -.111029, .274595, .40722, .925818, -.116345, .273841, .433385, .92746, -.121424, .272913, .459848, .929167, -.12657, .271837, .486493, .931426, -.131581, .270575, .513432, .934001, -.135038, .268512, .541502, .936296, -.138039, .266135, .569658, .939985, -.140687, .263271, .598375, .943516, -.143247, .260058, .626563, .94782, -.145135, .256138, .654711, .951023, -.145733, .251154, .683285, .955338, -.145554, .245562, .711831, .959629, -.145008, .239265, .739573, .963123, -.144003, .232064, .767027, .966742, -.141289, .224036, .794359, .969991, -.138247, .215305, .820361, .973403, -.134786, .206051, .846548, .975317, -.129966, .195914, .871541, .977647, -.12471, .185184, .895313, .980137, -.119086, .174161, .918398, .981031, -.112297, .162792, .940679, .982037, -.105372, .150952, .961991, .983164, -.097821, .138921, .981913, .983757, -.0897245, .126611, 1.00109, .985036, -.0815974, .114228, 1.01902, .986289, -.0727725, .101389, 1.03604, .987329, -.0639323, .0886476, 1.05149, .989193, -.0548109, .0756837, 1.06619, .990716, -.045687, .0627581, 1.07948, .992769, -.0364315, .0498337, 1.09172, .99524, -.0271761, .0370305, 1.1033, .997154, -.0179609, .0243959, 1.11353, .998845, -.00878063, .0119567, 1.12319, 1.00002, 259038e-9, -108146e-9, 1.13177, .903945, -591681e-11, .295126, 181226e-10, .903668, -148672e-9, .295037, 455367e-9, .903677, -594683e-9, .29504, .00182145, .903673, -.00133805, .295039, .00409831, .903666, -.00237872, .295036, .00728584, .903668, -.00371676, .295037, .0113842, .903679, -.00535212, .29504, .0163936, .903684, -.00728479, .295041, .0223141, .903698, -.00951473, .295044, .0291462, .903718, -.0120419, .295049, .0368904, .903754, -.0148664, .295058, .0455477, .903801, -.017988, .29507, .0551194, .903851, -.0214064, .295082, .0656058, .903921, -.0251219, .295097, .0770109, .904002, -.0291337, .295116, .0893354, .904111, -.033441, .29514, .102583, .904246, -.0380415, .295169, .116755, .904408, -.0429258, .295202, .131853, .904637, -.0480468, .295245, .147869, .904821, -.0529208, .295214, .164658, .905163, -.0577748, .295185, .182274, .905469, -.0631763, .295143, .200828, .905851, -.068917, .295112, .2202, .906322, -.0750861, .295104, .240372, .906761, -.0815855, .295086, .261082, .90735, -.0882138, .295095, .282123, .908087, -.095082, .295139, .303563, .908826, -.101488, .29492, .327028, .909832, -.107577, .294577, .351464, .911393, -.113033, .294115, .376497, .912804, -.118629, .293446, .402115, .914081, -.124232, .292581, .428111, .91637, -.129399, .29166, .454442, .91814, -.134892, .290422, .481024, .921179, -.140069, .289194, .507924, .924544, -.144431, .287421, .535557, .927995, -.147498, .284867, .563984, .931556, -.150197, .281722, .5923, .935777, -.152711, .278207, .620832, .940869, -.154836, .274148, .649069, .945994, -.155912, .269057, .677746, .949634, -.155641, .262799, .706293, .955032, -.154809, .256097, .734278, .95917, -.153678, .248618, .761751, .962931, -.151253, .239794, .789032, .966045, -.147625, .230281, .815422, .96971, -.143964, .220382, .841787, .972747, -.139464, .209846, .867446, .975545, -.133459, .198189, .892004, .978381, -.127424, .186362, .915458, .979935, -.120506, .173964, .937948, .980948, -.11282, .161429, .959732, .982234, -.104941, .148557, .980118, .982767, -.0962905, .135508, .999463, .983544, -.0873625, .122338, 1.01756, .984965, -.0783447, .108669, 1.03492, .986233, -.0684798, .0949911, 1.05087, .987796, -.0590867, .0811386, 1.0656, .989885, -.0489145, .0673099, 1.0794, .991821, -.0391, .0535665, 1.09174, .99448, -.029087, .0397529, 1.10341, .996769, -.019114, .0261463, 1.11383, .998641, -.00947007, .0128731, 1.1237, .999978, 446316e-9, -169093e-9, 1.13253, .888362, -627064e-11, .312578, 178215e-10, .889988, -157791e-9, .313148, 448451e-9, .889825, -631076e-9, .313092, .00179356, .88984, -.00141994, .313097, .00403554, .889828, -.0025243, .313092, .00717429, .889831, -.00394421, .313093, .0112099, .889831, -.00567962, .313093, .0161425, .889844, -.00773051, .313096, .0219724, .889858, -.0100968, .3131, .0286999, .889882, -.0127786, .313106, .0363256, .889918, -.0157757, .313116, .0448509, .889967, -.0190878, .313129, .0542758, .89003, -.022715, .313145, .0646032, .890108, -.0266566, .313165, .0758339, .890218, -.0309131, .313193, .0879729, .890351, -.0354819, .313226, .101019, .89051, -.0403613, .313263, .114979, .890672, -.0455385, .313294, .129848, .890882, -.0509444, .313333, .145616, .891189, -.0559657, .313324, .162122, .891457, -.0613123, .313281, .179524, .891856, -.0671488, .313281, .197855, .892312, -.0732732, .313268, .216991, .892819, -.0797865, .313263, .236924, .893369, -.0865269, .313247, .257433, .894045, -.0931592, .313205, .278215, .894884, -.100532, .313276, .299467, .895832, -.107716, .313205, .322276, .897043, -.114099, .312873, .34642, .898515, -.119941, .312331, .371187, .900191, -.126044, .311731, .396656, .90188, -.131808, .310859, .422488, .904359, -.137289, .309857, .448744, .906923, -.142991, .308714, .475239, .910634, -.148253, .307465, .501983, .914502, -.153332, .305774, .529254, .919046, -.156646, .303156, .557709, .923194, -.159612, .299928, .586267, .928858, -.162027, .296245, .614925, .934464, -.164203, .291832, .643187, .939824, -.165602, .286565, .671601, .944582, -.165383, .280073, .700213, .949257, -.164439, .272891, .728432, .954389, -.162953, .264771, .756082, .958595, -.161007, .255927, .78369, .962138, -.157243, .245769, .810769, .966979, -.152872, .235127, .836999, .969566, -.148209, .22347, .862684, .972372, -.142211, .211147, .887847, .975916, -.135458, .198606, .911843, .978026, -.128398, .185498, .934795, .979686, -.120313, .17171, .956787, .980748, -.11166, .158159, .978046, .981622, -.103035, .144399, .997693, .982356, -.0930328, .13001, 1.01642, .983308, -.0834627, .115778, 1.03366, .985037, -.0732249, .101327, 1.05014, .986493, -.0628145, .086554, 1.06507, .988484, -.0526556, .0720413, 1.07907, .991051, -.0415744, .0571151, 1.09189, .993523, -.0314275, .0426643, 1.10369, .99628, -.0203603, .0279325, 1.11423, .998344, -.0102446, .0138182, 1.12421, .999997, 42612e-8, -193628e-9, 1.1333, .871555, -660007e-11, .329176, 174749e-10, .875255, -166579e-9, .330571, 441051e-9, .875644, -666394e-9, .330718, .00176441, .875159, -.00149903, .330536, .00396899, .87516, -.00266493, .330536, .007056, .875158, -.00416393, .330535, .0110251, .87516, -.00599598, .330535, .0158764, .875163, -.00816108, .330536, .0216101, .875174, -.0106591, .330538, .0282266, .875199, -.0134899, .330545, .0357266, .875257, -.0166538, .330563, .0441117, .875304, -.0201501, .330575, .0533821, .875373, -.0239785, .330595, .0635395, .875464, -.0281389, .330619, .0745872, .875565, -.0326301, .330645, .0865255, .875691, -.0374516, .330676, .0993599, .875897, -.0425993, .330733, .113093, .876091, -.0480576, .330776, .127722, .876353, -.0537216, .330826, .143227, .876649, -.0589807, .330809, .159462, .877034, -.0647865, .330819, .176642, .877443, -.0709789, .330817, .194702, .877956, -.0774782, .330832, .213577, .878499, -.0843175, .330822, .233246, .879144, -.0912714, .330804, .253512, .879982, -.0980824, .330766, .274137, .88097, -.105823, .330864, .295209, .882051, -.113671, .330896, .317226, .883397, -.120303, .330545, .341068, .884987, -.12667, .330068, .365613, .886789, -.133118, .329418, .390807, .889311, -.139024, .328683, .416494, .891995, -.144971, .327729, .442618, .895106, -.150747, .326521, .469131, .899527, -.156283, .325229, .495921, .90504, -.161707, .32378, .523162, .909875, -.165661, .32122, .55092, .91561, -.168755, .317942, .579928, .921225, -.171193, .313983, .608539, .927308, -.17319, .309636, .636854, .933077, -.174819, .304262, .66523, .938766, -.175002, .297563, .693609, .943667, -.173946, .289613, .722157, .949033, -.172221, .281227, .750021, .953765, -.169869, .271545, .777466, .95804, -.166578, .261034, .804853, .962302, -.161761, .249434, .831569, .966544, -.156636, .237484, .857779, .969372, -.150784, .224395, .883051, .972486, -.143672, .210786, .907864, .975853, -.135772, .196556, .931223, .977975, -.127942, .182307, .954061, .979122, -.118347, .167607, .97531, .980719, -.109112, .152739, .995666, .981223, -.0991789, .137932, 1.01475, .98216, -.0883553, .122692, 1.03253, .983379, -.0780825, .107493, 1.04917, .985434, -.0665646, .0917791, 1.06464, .987332, -.0557714, .0764949, 1.07896, .990004, -.0442805, .060721, 1.09199, .992975, -.0331676, .0452284, 1.10393, .995811, -.0219547, .0297934, 1.11476, .9982, -.0107613, .0146415, 1.12484, 1.00002, 248678e-9, -14555e-8, 1.13413, .859519, -693595e-11, .347264, 171673e-10, .859843, -17503e-8, .347394, 433219e-9, .859656, -700076e-9, .347319, .00173277, .859671, -.00157517, .347325, .00389875, .859669, -.00280028, .347324, .00693112, .85967, -.0043754, .347324, .01083, .859665, -.00630049, .347321, .0155954, .859685, -.0085755, .347328, .0212278, .859694, -.0112003, .347329, .0277273, .859718, -.0141747, .347336, .0350946, .85976, -.0174988, .347348, .0433314, .85982, -.0211722, .347366, .0524384, .859892, -.0251941, .347387, .0624168, .860006, -.0295649, .347422, .0732708, .860122, -.0342825, .347453, .0849999, .860282, -.0393462, .347499, .0976102, .860482, -.0447513, .347554, .111104, .860719, -.0504775, .347614, .125479, .860998, -.0563577, .347666, .140703, .861322, -.0619473, .347662, .156681, .861724, -.0681277, .347684, .173597, .862198, -.0746567, .347709, .191371, .862733, -.0815234, .347727, .209976, .863371, -.0886643, .347744, .229351, .86414, -.0957908, .347734, .24934, .865138, -.102912, .34772, .269797, .866182, -.110924, .3478, .290654, .867436, -.119223, .347911, .312074, .869087, -.126197, .347649, .335438, .870859, -.133145, .347222, .359732, .872997, -.139869, .346645, .38467, .875939, -.146089, .345935, .41019, .879012, -.152334, .345012, .436218, .883353, -.15821, .343924, .462641, .888362, -.164097, .342636, .489449, .895026, -.169528, .341351, .516629, .900753, -.174408, .339115, .544109, .906814, -.17751, .335809, .572857, .912855, -.180101, .331597, .601554, .919438, -.182116, .32698, .630198, .925962, -.183494, .321449, .658404, .931734, -.184159, .314595, .686625, .93762, -.18304, .306462, .71531, .943858, -.181323, .297514, .744272, .948662, -.178683, .287447, .771462, .953299, -.175379, .276166, .798593, .957346, -.170395, .263758, .8256, .962565, -.165042, .251019, .852575, .966075, -.158655, .237011, .878316, .969048, -.151707, .222518, .90329, .972423, -.143271, .207848, .927745, .975833, -.134824, .192463, .950859, .977629, -.125444, .1768, .972947, .978995, -.114949, .161033, .993263, .980533, -.104936, .145523, 1.01337, .980745, -.0935577, .129799, 1.03128, .981814, -.0822956, .113486, 1.04825, .983943, -.0710082, .0972925, 1.06405, .986141, -.0587931, .0808138, 1.0785, .988878, -.0472755, .0644915, 1.09204, .992132, -.0349128, .0478128, 1.10413, .9953, -.0232407, .031621, 1.11527, .998117, -.0112713, .0154935, 1.12551, 1.00003, 339743e-9, -195763e-9, 1.13504, .845441, -729126e-11, .364305, 169208e-10, .843588, -183164e-9, .363506, 425067e-9, .843412, -73253e-8, .36343, .00169999, .843401, -.00164818, .363426, .00382495, .843399, -.00293008, .363425, .00679993, .843401, -.00457822, .363425, .010625, .843394, -.00659249, .363421, .0153002, .843398, -.00897282, .363421, .0208258, .843415, -.0117191, .363426, .0272024, .843438, -.0148312, .363432, .0344305, .843483, -.018309, .363447, .0425116, .84356, -.0221521, .363472, .0514471, .843646, -.0263597, .363499, .061238, .843743, -.0309315, .363527, .0718873, .84388, -.0358658, .363569, .0833969, .844079, -.0411624, .363631, .0957742, .844279, -.0468128, .363688, .109015, .844549, -.0527923, .363761, .123124, .844858, -.0588204, .363817, .138044, .84522, -.0647573, .36383, .153755, .845669, -.0713181, .363879, .170394, .846155, -.0781697, .363908, .187861, .846789, -.0853913, .363969, .206176, .847502, -.0928086, .363999, .225244, .8484, -.10005, .363997, .244926, .849461, -.107615, .364008, .265188, .850562, -.115814, .364055, .28587, .851962, -.124334, .364179, .306926, .854326, -.131995, .364233, .329605, .856295, -.139338, .363856, .35359, .858857, -.146346, .363347, .37831, .862428, -.152994, .362807, .403722, .866203, -.159463, .361963, .429537, .871629, -.165623, .36112, .456, .877365, -.171649, .359917, .482773, .883744, -.177151, .35848, .509705, .890693, -.182381, .356523, .537215, .897278, -.186076, .3533, .565493, .903958, -.188602, .349095, .594293, .910908, -.190755, .344215, .623165, .918117, -.192063, .338606, .651573, .924644, -.192758, .331544, .679869, .931054, -.192238, .323163, .708668, .937303, -.190035, .313529, .737201, .943387, -.187162, .303152, .764977, .948494, -.183876, .29146, .792683, .952546, -.178901, .277917, .819228, .958077, -.173173, .264753, .846559, .962462, -.16645, .25002, .872962, .966569, -.159452, .234873, .898729, .969108, -.15074, .218752, .923126, .973072, -.141523, .202673, .947278, .975452, -.132075, .186326, .969938, .977784, -.121257, .169396, .991325, .97899, -.110182, .153044, 1.01123, .979777, -.0989634, .136485, 1.0299, .980865, -.0865894, .119343, 1.04727, .982432, -.0746115, .102452, 1.06341, .984935, -.0621822, .0852423, 1.07834, .987776, -.0495694, .0678546, 1.092, .99103, -.0372386, .0506917, 1.1043, .99474, -.0244353, .0333316, 1.11576, .997768, -.0121448, .0164348, 1.12617, 1.00003, 31774e-8, -169504e-9, 1.13598, .825551, -756799e-11, .378425, 165099e-10, .82664, -190922e-9, .378923, 416504e-9, .826323, -763495e-9, .378779, .0016656, .826359, -.00171789, .378795, .00374768, .82636, -.00305402, .378795, .00666259, .826368, -.00477185, .378798, .0104104, .826364, -.00687131, .378795, .0149912, .826368, -.00935232, .378795, .0204054, .826376, -.0122146, .378797, .0266532, .826399, -.0154581, .378803, .0337355, .82646, -.0190825, .378824, .0416537, .826525, -.0230873, .378846, .0504091, .826614, -.0274719, .378876, .0600032, .82674, -.0322355, .378917, .0704393, .826888, -.0373766, .378964, .0817195, .827078, -.0428936, .379024, .0938492, .827318, -.0487778, .379099, .106828, .82764, -.0549935, .379199, .120659, .827926, -.0611058, .379227, .13526, .828325, -.0675054, .379275, .150713, .828801, -.0743455, .379332, .167034, .8294, -.0815523, .379415, .184209, .830094, -.0890779, .379495, .202203, .8309, -.096736, .379555, .220945, .831943, -.104135, .379577, .240306, .833037, -.112106, .379604, .260317, .834278, -.120554, .379668, .2808, .836192, -.129128, .3799, .301654, .838671, -.137541, .380109, .323502, .840939, -.14523, .379809, .347176, .844575, -.15248, .379593, .371706, .848379, -.159607, .37909, .39688, .853616, -.166267, .378617, .422702, .858921, -.172698, .377746, .448919, .865324, -.178823, .376749, .475661, .872207, -.184542, .375363, .502599, .880018, -.189836, .373657, .529914, .88694, -.194294, .370673, .557683, .894779, -.197022, .36662, .586848, .902242, -.199108, .36138, .615831, .909914, -.200398, .355434, .644478, .917088, -.20094, .348173, .672905, .923888, -.200671, .339482, .701327, .930495, -.198773, .32956, .730101, .937247, -.195394, .318363, .758383, .943108, -.191956, .306323, .786539, .948296, -.187227, .292576, .813637, .953472, -.181165, .278234, .840793, .958485, -.174119, .263054, .867712, .962714, -.166564, .246756, .893635, .966185, -.158181, .229945, .919028, .970146, -.148275, .212633, .943413, .973491, -.138157, .195229, .966627, .975741, -.127574, .178048, .988817, .977238, -.11554, .160312, 1.00924, .978411, -.10364, .142857, 1.02845, .979811, -.0913122, .125317, 1.04648, .98116, -.0782558, .107627, 1.06284, .983543, -.0655957, .0895862, 1.07798, .986789, -.0520411, .0713756, 1.092, .990292, -.0389727, .053228, 1.10484, .994187, -.025808, .0351945, 1.11642, .997499, -.0126071, .0173198, 1.12703, .999999, 275604e-9, -148602e-9, 1.13674, .81075, -78735e-10, .394456, 161829e-10, .808692, -198293e-9, .393453, 407564e-9, .80846, -792877e-9, .39334, .00162965, .808595, -.00178416, .393407, .00366711, .808597, -.00317182, .393408, .00651934, .808598, -.00495589, .393408, .0101866, .808591, -.00713627, .393403, .0146689, .808592, -.00971285, .393402, .0199667, .80861, -.0126855, .393407, .0260803, .808633, -.0160538, .393413, .0330107, .80868, -.0198175, .393429, .0407589, .808748, -.0239758, .393453, .0493264, .808854, -.0285286, .39349, .0587161, .808992, -.0334748, .39354, .0689304, .809141, -.0388116, .393588, .0799707, .809352, -.0445375, .39366, .0918432, .809608, -.0506427, .393742, .104549, .809915, -.0570708, .393834, .118085, .810253, -.0633526, .393885, .132377, .810687, -.0700966, .393953, .147537, .811233, -.0772274, .394047, .163543, .811865, -.0847629, .394148, .180394, .812648, -.0925663, .394265, .198051, .813583, -.100416, .394363, .216443, .814683, -.108119, .394402, .235502, .815948, -.11644, .394489, .255242, .817278, -.125036, .394542, .275441, .819605, -.133655, .39486, .296094, .822256, -.142682, .395248, .317309, .825349, -.150756, .395241, .340516, .829605, -.158392, .395285, .364819, .83391, -.165801, .394922, .389736, .839808, -.172677, .394691, .415409, .845708, -.179448, .394006, .441546, .853025, -.185746, .393279, .46832, .859666, -.191684, .391655, .495302, .86789, -.197146, .390068, .52262, .875845, -.201904, .38727, .550336, .882634, -.205023, .382688, .578825, .891076, -.207098, .377543, .608103, .900589, -.208474, .371752, .63723, .90791, -.209068, .364016, .665769, .915971, -.208655, .355593, .694428, .923455, -.20729, .345439, .723224, .931514, -.203821, .334099, .751925, .937885, -.19986, .321069, .780249, .943136, -.194993, .306571, .8077, .948818, -.189132, .291556, .83497, .954433, -.181617, .275745, .86188, .959078, -.173595, .258695, .888562, .962705, -.164855, .240825, .914008, .966753, -.155129, .22268, .939145, .970704, -.144241, .204542, .963393, .973367, -.133188, .185927, .985983, .975984, -.121146, .167743, 1.00704, .976994, -.108366, .149218, 1.02715, .978485, -.0956746, .13131, 1.0455, .980074, -.0820733, .112513, 1.06221, .98225, -.0684061, .0938323, 1.07782, .98553, -.0549503, .0749508, 1.09199, .989529, -.0407857, .055848, 1.10508, .993536, -.0271978, .0368581, 1.11684, .997247, -.0132716, .0181845, 1.12789, 1, 431817e-9, -198809e-9, 1.13792, .785886, -812608e-11, .405036, 157669e-10, .790388, -205278e-9, .407355, 398297e-9, .790145, -820824e-9, .407231, .00159263, .790135, -.00184681, .407226, .00358336, .790119, -.00328316, .407218, .00637039, .790126, -.00512988, .40722, .0099539, .79013, -.00738684, .407221, .0143339, .790135, -.0100538, .407221, .0195107, .790134, -.0131306, .407217, .0254848, .79016, -.0166169, .407224, .0322572, .790197, -.020512, .407236, .0398284, .790273, -.0248157, .407263, .0482014, .790381, -.029527, .407304, .0573777, .790521, -.0346446, .407355, .0673602, .790704, -.0401665, .40742, .0781522, .790925, -.0460896, .407499, .0897582, .791195, -.0524017, .407589, .10218, .791522, -.0590121, .407691, .11541, .791878, -.0654876, .407748, .12939, .792361, -.0725207, .407849, .144237, .792942, -.0799844, .407963, .159924, .79362, -.0877896, .408087, .176425, .794529, -.0958451, .408259, .193733, .795521, -.103827, .408362, .211756, .796778, -.111937, .408482, .230524, .798027, -.120521, .408547, .249967, .799813, -.129242, .408721, .269926, .802387, -.138048, .409148, .290338, .805279, -.147301, .409641, .311193, .809251, -.155895, .410154, .333611, .813733, -.163942, .410297, .357615, .819081, -.171666, .410373, .382339, .825427, -.178905, .410348, .407828, .83172, -.185812, .409486, .434034, .83877, -.192318, .408776, .460493, .845817, -.198249, .407176, .487346, .854664, -.204034, .405719, .514832, .863495, -.208908, .403282, .542401, .871883, -.212765, .399293, .570683, .88065, -.214911, .393803, .599947, .89004, -.216214, .387536, .62932, .898476, -.216745, .379846, .658319, .906738, -.216387, .370625, .687138, .914844, -.215053, .360139, .71601, .923877, -.212007, .348849, .745124, .931925, -.207481, .335639, .773366, .938054, -.202418, .320798, .801636, .943895, -.196507, .304772, .829055, .949468, -.189009, .288033, .856097, .955152, -.180539, .270532, .88301, .959403, -.171437, .251639, .909296, .963309, -.161661, .232563, .934868, .967399, -.150425, .213231, .959662, .972009, -.138659, .194247, .98302, .97433, -.126595, .174718, 1.00517, .975823, -.113205, .155518, 1.02566, .976371, -.0996096, .136709, 1.04418, .978705, -.0860754, .117571, 1.06146, .981477, -.0714438, .0980046, 1.07777, .984263, -.0572304, .0782181, 1.09214, .988423, -.0428875, .0584052, 1.10553, .993, -.0282442, .038522, 1.11758, .99704, -.0140183, .0190148, 1.12864, .999913, 369494e-9, -145203e-9, 1.13901, .777662, -84153e-10, .423844, 154403e-10, .770458, -211714e-9, .419915, 38845e-8, .770716, -846888e-9, .420055, .00155386, .770982, -.00190567, .420202, .00349653, .770981, -.00338782, .420201, .00621606, .77098, -.00529338, .4202, .00971274, .770983, -.00762223, .4202, .0139867, .770985, -.0103741, .420198, .0190381, .770996, -.0135489, .4202, .0248677, .771029, -.0171461, .420212, .0314764, .771052, -.0211647, .420215, .0388648, .771131, -.0256048, .420245, .047036, .771235, -.0304647, .420284, .0559911, .771383, -.0357436, .420341, .0657346, .771591, -.0414392, .420423, .0762694, .771819, -.0475462, .420506, .0875984, .772123, -.0540506, .420617, .099727, .772464, -.060797, .42072, .112637, .772855, -.0675393, .420799, .126313, .773317, -.0748323, .420893, .140824, .773981, -.0825681, .421058, .15617, .774746, -.0906307, .421226, .172322, .77566, -.0988982, .421397, .189253, .776837, -.106994, .421569, .206912, .778097, -.115528, .421704, .225359, .779588, -.124317, .421849, .24447, .781574, -.133139, .422097, .264156, .784451, -.142179, .422615, .284318, .787682, -.15165, .423269, .304902, .792433, -.160771, .424396, .3265, .797359, -.169166, .424772, .35014, .803986, -.177149, .425475, .374768, .809504, -.184745, .424996, .399928, .815885, -.19173, .424247, .425796, .823513, -.198525, .423515, .452287, .832549, -.204709, .422787, .479321, .841653, -.210447, .421187, .506718, .850401, -.215501, .418519, .53432, .859854, -.219752, .414715, .56242, .869364, -.222305, .409462, .591558, .878837, -.223744, .402926, .621074, .888636, -.224065, .395043, .650538, .898132, -.223742, .38564, .679538, .907181, -.222308, .375378, .708674, .915621, -.219837, .363212, .737714, .9239, -.215233, .349313, .767014, .931644, -.209592, .334162, .795133, .938887, -.203644, .317943, .823228, .945282, -.196349, .300581, .850822, .950758, -.18742, .282195, .877594, .956146, -.177879, .262481, .904564, .960355, -.167643, .242487, .930741, .965256, -.156671, .222668, .955868, .968029, -.144123, .201907, .979869, .97251, -.131305, .18202, 1.00291, .974925, -.118335, .161909, 1.02392, .975402, -.103714, .142129, 1.0433, .976987, -.089415, .122447, 1.06089, .979677, -.0748858, .102248, 1.07713, .983184, -.0596086, .0814851, 1.09218, .987466, -.0447671, .0609484, 1.10585, .992348, -.0295217, .0401835, 1.11829, .996674, -.0143917, .0198163, 1.12966, 1.00003, 321364e-9, -149983e-9, 1.1402, .757901, -869074e-11, .436176, 151011e-10, .751195, -217848e-9, .432317, 378533e-9, .751178, -871373e-9, .432307, .0015141, .751195, -.00196061, .432317, .0034068, .751198, -.00348552, .432318, .00605659, .751195, -.00544599, .432315, .00946353, .751207, -.00784203, .43232, .013628, .751213, -.0106732, .43232, .0185499, .751221, -.0139393, .432319, .0242302, .751244, -.0176398, .432325, .0306694, .7513, -.0217743, .432348, .0378698, .751358, -.0263412, .432367, .0458321, .751458, -.0313396, .432404, .0545587, .751608, -.0367682, .432464, .0640543, .7518, -.0426246, .43254, .0743222, .752065, -.0489031, .432645, .0853668, .752376, -.0555828, .432762, .0971911, .752715, -.0623861, .432859, .109768, .753137, -.069415, .432958, .123126, .753676, -.0770039, .433099, .137308, .754345, -.084971, .433272, .15229, .755235, -.0932681, .433504, .168075, .756186, -.10171, .433693, .184625, .757363, -.110019, .433857, .201897, .75884, -.11887, .434102, .220014, .760467, -.127881, .434306, .238778, .762969, -.136766, .434751, .258172, .765823, -.14612, .43529, .278062, .769676, -.15566, .436236, .298437, .774909, -.165177, .437754, .319532, .77994, -.17402, .438343, .342505, .785757, -.182201, .438609, .366693, .792487, -.190104, .438762, .391668, .80038, -.197438, .438795, .417494, .808494, -.204365, .438226, .443933, .817695, -.210714, .437283, .470929, .828111, -.216651, .436087, .498569, .837901, -.221804, .433717, .526165, .847813, -.226318, .430133, .554155, .858314, -.229297, .425213, .582822, .868891, -.230999, .418576, .612847, .878941, -.231155, .410405, .642445, .888809, -.230935, .400544, .672024, .898089, -.229343, .389613, .701366, .908081, -.226886, .377197, .730763, .916819, -.222676, .363397, .759642, .924968, -.216835, .347437, .788775, .932906, -.210245, .32995, .817135, .940025, -.202992, .312262, .844912, .946101, -.19436, .293313, .872164, .952835, -.184125, .273638, .899443, .957347, -.173657, .252385, .926389, .961434, -.162204, .231038, .951947, .965522, -.14979, .209834, .976751, .969412, -.136307, .188821, 1.00022, .973902, -.122527, .168013, 1.02229, .974045, -.108213, .147634, 1.04199, .975775, -.0927397, .12705, 1.06019, .978383, -.0778212, .106309, 1.07711, .98211, -.0621216, .0849279, 1.09245, .986517, -.0463847, .0633519, 1.10651, .991696, -.0309353, .0419698, 1.11903, .996349, -.0150914, .0206272, 1.13073, 1.00003, 442449e-9, -231396e-9, 1.14146, .727498, -885074e-11, .441528, 145832e-10, .730897, -223525e-9, .443589, 368298e-9, .730796, -893996e-9, .443528, .00147303, .730805, -.00201149, .443533, .00331433, .730814, -.00357596, .443538, .00589222, .730815, -.00558734, .443538, .00920678, .730822, -.00804544, .44354, .0132582, .730836, -.0109501, .443545, .0180468, .730848, -.0143008, .443546, .0235732, .730871, -.0180969, .443552, .0298382, .730915, -.022338, .443567, .0368438, .730982, -.0270225, .443591, .044591, .731076, -.0321491, .443627, .0530831, .731245, -.0377166, .443699, .0623243, .73144, -.0437216, .443777, .0723181, .7317, -.0501576, .443881, .0830691, .732034, -.0569942, .444014, .0945809, .732388, -.0638756, .444113, .106825, .732853, -.071203, .444247, .119859, .733473, -.0790076, .444442, .13369, .734195, -.0871937, .444645, .148304, .735069, -.095696, .444877, .163702, .736169, -.10426, .445133, .179861, .73747, -.112853, .44537, .196778, .738991, -.12199, .445651, .214496, .740865, -.131153, .445958, .232913, .743637, -.140245, .446548, .251977, .746797, -.149722, .447246, .271551, .751517, -.159341, .448656, .291774, .756156, -.169106, .449866, .312455, .761519, -.178436, .450919, .334552, .768295, -.186904, .451776, .358491, .776613, -.195117, .452832, .383446, .783966, -.202695, .45249, .408945, .793542, -.20985, .452587, .435364, .803192, -.216403, .451852, .462336, .813892, -.22251, .450708, .48987, .824968, -.227676, .4486, .517697, .835859, -.232443, .445156, .545975, .846825, -.235775, .440351, .574483, .858085, -.237897, .433641, .604246, .868825, -.238074, .425354, .634101, .879638, -.237661, .415383, .664201, .889966, -.236186, .404136, .693918, .899479, -.233599, .390917, .723481, .908769, -.229737, .376352, .75258, .917966, -.223836, .360372, .781764, .926304, -.217067, .342551, .811139, .934626, -.209309, .324238, .839585, .941841, -.20071, .304484, .867044, .94789, -.190602, .283607, .894579, .954196, -.179253, .262205, .921743, .958383, -.167646, .239847, .948026, .963119, -.155073, .218078, .973296, .966941, -.141426, .195899, .998135, .970836, -.126849, .174121, 1.02021, .973301, -.112296, .153052, 1.04085, .97448, -.0964965, .131733, 1.05946, .977045, -.080489, .10997, 1.07693, .980751, -.064844, .0881657, 1.09254, .985475, -.0481938, .0657987, 1.10697, .991089, -.0319185, .0435215, 1.12004, .996122, -.0158088, .0214779, 1.13173, 1.00001, 372455e-9, -200295e-9, 1.14291, .708622, -907597e-11, .45304, 141962e-10, .711162, -228911e-9, .454662, 358052e-9, .709812, -914446e-9, .453797, .00143034, .709865, -.00205819, .453834, .00321935, .709864, -.00365894, .453833, .00572331, .709855, -.00571692, .453826, .00894278, .709862, -.00823201, .453828, .012878, .709875, -.011204, .453832, .0175295, .709896, -.0146323, .453839, .0228978, .709925, -.0185163, .453847, .0289839, .709974, -.0228551, .453866, .0357894, .710045, -.0276473, .453892, .0433161, .710133, -.032891, .453924, .0515665, .710292, -.0385851, .453992, .0605458, .710485, -.0447254, .45407, .0702574, .710769, -.0513051, .454192, .0807077, .711106, -.0582733, .454329, .091896, .711516, -.0652866, .45446, .103814, .712071, -.0728426, .454653, .116508, .712676, -.0808307, .45484, .129968, .713476, -.0892216, .455096, .144206, .714377, -.0979047, .455346, .159212, .715579, -.106531, .455647, .174973, .716977, -.115492, .455961, .191504, .71862, -.124821, .456315, .208835, .72084, -.134079, .4568, .226869, .723786, -.143427, .457521, .245582, .727464, -.153061, .458475, .264957, .732771, -.162768, .460239, .284948, .736515, -.172627, .460899, .30522, .743519, -.182487, .463225, .326717, .750041, -.191295, .464027, .350113, .758589, -.199746, .465227, .374782, .767703, -.207584, .465877, .400226, .777484, -.214973, .465996, .426442, .788792, -.221796, .466019, .453688, .800194, -.228038, .465083, .481246, .811234, -.233346, .462506, .509086, .822859, -.238073, .459257, .537338, .835082, -.241764, .454863, .566108, .846332, -.244241, .448163, .595126, .858355, -.244736, .439709, .625574, .87034, -.244278, .429837, .65617, .881027, -.24255, .418002, .686029, .891007, -.239912, .404325, .716039, .900874, -.236133, .389222, .745518, .911072, -.230672, .373269, .775026, .920359, -.22356, .355083, .804521, .928604, -.215591, .335533, .834045, .937175, -.206503, .315278, .861612, .942825, -.196684, .293653, .889131, .949805, -.185116, .271503, .916853, .955535, -.172703, .248821, .943541, .959843, -.159978, .225591, .970132, .964393, -.146375, .202719, .994709, .968008, -.131269, .179928, 1.0186, .971013, -.11569, .158007, 1.03928, .973334, -.1003, .13624, 1.05887, .975775, -.0833352, .1138, 1.07652, .979579, -.0668981, .0913141, 1.09297, .984323, -.0500902, .0683051, 1.10734, .990351, -.0332377, .0451771, 1.12084, .995823, -.0161491, .0221705, 1.13296, 1.0001, 234083e-9, -108712e-9, 1.14441, .683895, -924677e-11, .46015, 137429e-10, .68833, -233383e-9, .463134, 346865e-9, .688368, -933547e-9, .463159, .00138748, .688367, -.00210049, .463159, .00312187, .688369, -.00373415, .463159, .00555004, .688377, -.00583449, .463163, .00867216, .688386, -.00840128, .463166, .0124884, .688398, -.0114343, .463169, .0169993, .688418, -.0149329, .463175, .0222054, .688453, -.0188964, .463188, .028108, .688515, -.0233239, .463214, .0347085, .68857, -.0282136, .463231, .0420091, .688679, -.033564, .463276, .0500132, .688854, -.0393733, .463356, .0587255, .689038, -.0456354, .46343, .0681476, .689321, -.0523433, .463553, .0782897, .689662, -.059412, .463693, .0891501, .690188, -.0665736, .4639, .100735, .690755, -.0743106, .464107, .113074, .691405, -.0824722, .464329, .126161, .692198, -.0910484, .464585, .140007, .693196, -.0998778, .464893, .154612, .69454, -.108651, .465285, .169984, .695921, -.117855, .465596, .186106, .697749, -.12734, .466056, .203034, .700375, -.136714, .466771, .220703, .703395, -.146386, .467579, .239062, .707904, -.156096, .469067, .258188, .711673, -.165904, .469851, .277759, .717489, -.175812, .471815, .297935, .724051, -.185931, .47389, .318916, .731965, -.195238, .47587, .341591, .741151, -.204021, .477523, .366062, .751416, -.212113, .478881, .391396, .761848, -.21979, .479226, .417599, .771886, -.2267, .478495, .444401, .783998, -.232991, .477622, .472084, .796523, -.238645, .475833, .500193, .808851, -.243396, .472568, .52865, .821191, -.247226, .467857, .557362, .834261, -.250102, .461871, .586768, .846762, -.251056, .453543, .617085, .859867, -.250604, .443494, .647659, .871948, -.248783, .431711, .678119, .882967, -.245855, .417911, .708399, .892826, -.242168, .401993, .738256, .90332, -.237062, .385371, .767999, .913633, -.22997, .366837, .798191, .922774, -.221687, .346372, .827756, .931371, -.212345, .325682, .856425, .938929, -.20206, .303665, .884299, .944821, -.190981, .280786, .912023, .951792, -.178065, .2573, .939669, .957712, -.164634, .233448, .96655, .961912, -.150863, .209504, .992366, .966382, -.13577, .18597, 1.01633, .969588, -.119593, .162905, 1.03843, .971777, -.103203, .14053, 1.05841, .97433, -.0865888, .117909, 1.07632, .978686, -.0690829, .0944101, 1.09326, .983281, -.0516568, .0705671, 1.10796, .989562, -.034558, .0468592, 1.12182, .995465, -.0167808, .0229846, 1.1342, .999991, 373016e-9, -235606e-9, 1.1459, .662251, -939016e-11, .468575, 132714e-10, .666634, -237624e-9, .471675, 335842e-9, .666411, -950385e-9, .471516, .00134321, .666399, -.00213833, .471509, .00302221, .666386, -.0038014, .471499, .00537283, .666405, -.00593958, .471511, .00839533, .666406, -.00855253, .471508, .0120898, .666428, -.0116401, .471519, .0164569, .666444, -.0152015, .471522, .0214971, .66649, -.0192362, .471543, .027212, .666537, -.0237428, .471558, .033603, .666617, -.0287198, .471591, .0406728, .666718, -.0341647, .471631, .0484238, .666889, -.0400759, .47171, .0568621, .667104, -.0464479, .471805, .0659915, .667374, -.0532677, .471923, .0758178, .667772, -.0603805, .472098, .0863425, .668371, -.0677392, .472363, .0975917, .668971, -.0756028, .472596, .109567, .669696, -.0839293, .472869, .122272, .670481, -.0926683, .473126, .135718, .6715, -.1016, .473442, .149914, .672911, -.110566, .47389, .164882, .674512, -.119984, .474354, .180602, .67651, -.129574, .474922, .19711, .679292, -.139106, .475764, .214371, .682798, -.148993, .476886, .232405, .686955, -.158737, .478179, .251153, .691406, -.168754, .479432, .270436, .697438, -.178703, .481481, .290374, .704761, -.188955, .484143, .311044, .713599, -.198814, .487007, .333003, .723194, -.207869, .488962, .357144, .732601, -.216189, .489815, .382169, .744193, -.22398, .490888, .408227, .754907, -.231156, .490355, .434928, .767403, -.23747, .489548, .462599, .78107, -.243503, .488274, .490908, .793893, -.248114, .484843, .519421, .807296, -.25222, .4803, .548561, .820529, -.255265, .474097, .577772, .833716, -.256741, .466041, .607782, .848403, -.25637, .456547, .638807, .860755, -.254804, .443946, .670058, .874012, -.251834, .430852, .700749, .885619, -.247867, .414903, .731446, .896069, -.242634, .397276, .761191, .906266, -.236093, .378535, .791053, .916759, -.227543, .358038, .821298, .92523, -.21783, .335705, .850747, .93436, -.207534, .313797, .879258, .941631, -.195983, .289671, .907734, .947564, -.183567, .265319, .935206, .953681, -.169345, .240815, .962739, .960008, -.154909, .216119, .989227, .964145, -.140161, .192096, 1.01465, .968171, -.123411, .167855, 1.03737, .969859, -.106525, .144817, 1.05767, .972666, -.0891023, .12149, 1.0761, .977055, -.0718094, .0975306, 1.09336, .982527, -.0534213, .0730217, 1.10878, .989001, -.0355579, .0483366, 1.12285, .99512, -.0176383, .023938, 1.13548, 1.00007, 368831e-9, -211581e-9, 1.14744, .651047, -960845e-11, .484101, 12922e-9, .644145, -241347e-9, .478968, 324578e-9, .64396, -965142e-9, .478831, .00129798, .64396, -.00217154, .47883, .00292046, .643968, -.00386049, .478835, .00519202, .643974, -.00603186, .478838, .0081128, .643977, -.0086854, .478836, .011683, .643982, -.0118207, .478834, .0159031, .644024, -.0154374, .478856, .0207743, .644059, -.0195343, .478868, .0262975, .644122, -.0241103, .478896, .0324747, .644207, -.0291638, .478933, .039309, .64432, -.0346919, .478981, .0468029, .644481, -.0406919, .479053, .0549614, .644722, -.047159, .479169, .0637909, .645013, -.0540748, .479302, .0732974, .645503, -.0612001, .479541, .0834898, .646117, -.0687303, .479829, .0943873, .646707, -.0767846, .480061, .105991, .647431, -.0852465, .480343, .11831, .64831, -.0940719, .48066, .131348, .649486, -.103056, .481083, .14514, .650864, -.112261, .481528, .159676, .652604, -.121852, .482102, .174979, .654825, -.131505, .482813, .191079, .657876, -.141189, .483876, .207927, .661339, -.151239, .48499, .225586, .665463, -.161091, .486279, .243947, .670542, -.171235, .487968, .262957, .677361, -.181347, .49053, .282781, .685672, -.191679, .493862, .303311, .694551, -.201781, .49699, .324607, .703753, -.211164, .498884, .347916, .713703, -.219675, .500086, .372628, .725911, -.227836, .501554, .398694, .73862, -.23533, .502193, .425529, .752118, -.241786, .501811, .453209, .76579, -.247865, .500185, .481381, .779568, -.252696, .497159, .51011, .793991, -.256802, .492765, .539322, .808182, -.259942, .486827, .569078, .821698, -.261703, .478386, .598818, .836009, -.262006, .468772, .629762, .849824, -.260333, .456352, .661366, .863888, -.257398, .442533, .69295, .876585, -.253264, .426573, .723608, .888665, -.248026, .408964, .754378, .899537, -.241487, .389677, .784761, .9094, -.233463, .368516, .814688, .920166, -.223397, .346624, .845009, .928899, -.21255, .322717, .874431, .937156, -.200869, .298698, .902922, .943861, -.188387, .273491, .931356, .949557, -.174341, .247866, .958854, .955862, -.158994, .222496, .986098, .961721, -.143664, .197522, 1.01229, .965976, -.127412, .17302, 1.03571, .968652, -.109798, .148954, 1.05699, .971084, -.0916787, .125044, 1.07587, .975584, -.0739634, .100577, 1.09372, .98122, -.055322, .0753666, 1.10948, .988253, -.0366825, .0498899, 1.12394, .99482, -.0180389, .024611, 1.13694, 1.00001, 229839e-9, -188283e-9, 1.14919, .613867, -964198e-11, .479449, 123452e-10, .621485, -244534e-9, .485399, 313091e-9, .621429, -978202e-9, .485353, .00125245, .62112, -.00220004, .485114, .00281687, .621119, -.0039111, .485112, .00500783, .621122, -.00611091, .485112, .00782498, .621133, -.00879922, .485117, .0112687, .621152, -.0119756, .485125, .0153394, .621183, -.0156396, .485139, .0200382, .621227, -.0197898, .485158, .0253663, .621298, -.0244253, .485192, .0313261, .621388, -.0295441, .485233, .0379204, .621507, -.0351432, .485286, .0451523, .621693, -.0412198, .485378, .0530277, .621933, -.0477673, .485495, .0615522, .622232, -.0547574, .485635, .0707316, .622809, -.0619417, .485943, .0805883, .623407, -.069625, .486232, .0911267, .62406, -.077796, .486516, .102354, .624835, -.0863731, .486838, .114279, .625758, -.095251, .487188, .126902, .627043, -.104299, .487695, .140285, .628438, -.113724, .488163, .154397, .630325, -.123417, .488858, .169267, .632801, -.133137, .489754, .184941, .635784, -.143052, .490815, .20136, .639406, -.153132, .492048, .218643, .643872, -.163143, .49363, .236615, .6499, -.17333, .496009, .255449, .657201, -.183622, .498994, .275006, .666221, -.194019, .502888, .295354, .674419, -.204192, .505459, .316244, .683729, -.21406, .507771, .33849, .695584, -.222854, .510245, .363166, .708583, -.231315, .512293, .389071, .721233, -.238911, .512747, .415737, .735134, -.245657, .512482, .443331, .750179, -.251879, .511526, .471891, .765073, -.256911, .508935, .500892, .779794, -.261144, .504341, .530294, .794801, -.264316, .498515, .560144, .810339, -.266276, .491015, .590213, .824818, -.266981, .481126, .620865, .839375, -.265778, .468685, .652687, .853043, -.262748, .453925, .684759, .867335, -.258474, .437912, .716209, .88037, -.253187, .419648, .747508, .891711, -.246476, .39982, .77797, .902896, -.238735, .37879, .808586, .913601, -.22885, .355891, .838843, .923019, -.217656, .331773, .869014, .933432, -.205539, .307356, .898512, .939691, -.192595, .281321, .9269, .946938, -.178945, .255441, .955297, .952372, -.163587, .229013, .983231, .95909, -.147214, .203179, 1.00971, .963675, -.13064, .17792, 1.03438, .968247, -.113121, .152898, 1.05625, .97001, -.0945824, .128712, 1.07598, .974458, -.0755648, .103349, 1.094, .980168, -.0571998, .0776731, 1.1104, .987295, -.0377994, .0514445, 1.12491, .994432, -.0186417, .025429, 1.13851, .999975, 542714e-9, -282356e-9, 1.15108, .592656, -980249e-11, .486018, 119532e-10, .598467, -247275e-9, .490781, 301531e-9, .597934, -988317e-9, .490343, .00120517, .597903, -.00222366, .490319, .0027116, .597913, -.00395315, .490327, .00482077, .597919, -.00617653, .490329, .00753264, .597936, -.00889375, .490339, .0108478, .597956, -.0121043, .490347, .0147668, .597992, -.0158073, .490365, .0192905, .598032, -.0200017, .490382, .0244204, .598109, -.0246865, .49042, .0301593, .598215, -.0298594, .490474, .03651, .59833, -.0355167, .490524, .0434757, .598525, -.0416559, .490624, .0510629, .598778, -.0482692, .490753, .0592781, .599135, -.0553114, .49094, .0681304, .599802, -.062542, .491328, .0776467, .600361, -.0703638, .491598, .0878184, .60101, -.0786256, .491882, .0986573, .601811, -.0872962, .492232, .11018, .602861, -.0962284, .492684, .1224, .604167, -.10538, .493213, .135354, .605693, -.114896, .493799, .149034, .607682, -.124654, .494576, .163469, .610672, -.13456, .4959, .178747, .613313, -.144581, .496713, .194723, .617603, -.154703, .498499, .211617, .622174, -.16489, .500188, .229183, .628855, -.175164, .503072, .247786, .636963, -.185565, .506798, .267116, .644866, -.195911, .509719, .28702, .653741, -.206104, .512776, .307763, .664942, -.216447, .516812, .329631, .67633, -.22552, .519181, .353515, .690012, -.234316, .521681, .379226, .704243, -.242032, .523129, .405901, .719396, -.249172, .523768, .433585, .734471, -.255543, .522541, .462085, .750539, -.260697, .520217, .491233, .766365, -.26501, .516293, .521094, .781677, -.268409, .509708, .551014, .797132, -.270399, .501944, .581463, .812655, -.271247, .492025, .612402, .828592, -.270708, .480424, .643798, .844044, -.268085, .465955, .67682, .857305, -.263459, .448425, .708496, .87114, -.258151, .430243, .74046, .884936, -.251171, .410578, .771583, .895772, -.243305, .38862, .802234, .906961, -.234037, .365214, .833179, .917775, -.222714, .34116, .86353, .927883, -.210175, .31572, .893557, .936617, -.196925, .289159, .922976, .943384, -.182788, .261996, .951606, .949713, -.167965, .235324, .979958, .955818, -.151109, .208408, 1.00765, .961344, -.133834, .182591, 1.03329, .965469, -.115987, .156958, 1.0557, .968693, -.09746, .132239, 1.07583, .973165, -.0778514, .106195, 1.09451, .979387, -.0585067, .0797669, 1.11137, .98671, -.0390409, .0530263, 1.12643, .994093, -.019408, .0263163, 1.14016, 1.00002, 540029e-9, -194487e-9, 1.15299, .574483, -989066e-11, .494533, 114896e-10, .574478, -249127e-9, .494528, 289403e-9, .574607, -996811e-9, .494637, .00115797, .574396, -.00224241, .494458, .00260498, .574377, -.00398632, .49444, .00463102, .574386, -.00622836, .494445, .00723623, .574401, -.0089683, .494453, .010421, .574419, -.0122056, .49446, .0141859, .574459, -.0159396, .494481, .0185322, .574525, -.0201692, .49452, .0234617, .574587, -.0248924, .494547, .0289762, .574697, -.0301074, .494604, .0350797, .574853, -.0358114, .494688, .0417767, .575027, -.041999, .494772, .0490718, .575294, -.0486618, .494915, .0569728, .575733, -.0557148, .495173, .0654955, .576356, -.0630489, .495537, .0746612, .576944, -.0709285, .495836, .0844615, .57765, -.0792723, .496177, .0949142, .578491, -.0880167, .496563, .10603, .579639, -.0969462, .497096, .117841, .580989, -.10622, .497684, .130367, .582587, -.115861, .498337, .143609, .584951, -.125605, .499414, .157625, .587602, -.135608, .500518, .172413, .59076, -.145742, .501767, .187999, .594992, -.155934, .503542, .20445, .600656, -.166303, .506135, .221764, .607816, -.176681, .509542, .24002, .61522, -.187071, .51263, .258992, .623702, -.197465, .516021, .278773, .634192, -.207816, .520422, .299377, .644936, -.218183, .524073, .320802, .657888, -.2278, .528049, .34384, .670666, -.236747, .52986, .36916, .685626, -.24484, .531892, .395867, .701304, -.252071, .532727, .423488, .717727, -.258714, .532146, .452201, .733914, -.264211, .529883, .481579, .750529, -.26859, .5259, .511558, .76747, -.272046, .51999, .542042, .785189, -.274225, .513083, .572799, .800954, -.275189, .502936, .603816, .816962, -.274946, .490921, .635461, .83336, -.272695, .47684, .6676, .848143, -.268223, .459405, .70051, .861818, -.262768, .440319, .732902, .876828, -.255872, .420123, .765084, .889312, -.247703, .398379, .796391, .900412, -.238381, .374496, .827333, .912251, -.227783, .349874, .858385, .921792, -.214832, .323181, .888652, .931273, -.200949, .296624, .917763, .940295, -.186537, .269211, .947878, .946812, -.171538, .241447, .977016, .953588, -.155254, .213829, 1.00501, .958841, -.137156, .186807, 1.03179, .963746, -.118699, .160706, 1.05502, .966468, -.0998358, .135504, 1.07568, .971178, -.0805186, .109131, 1.09479, .97831, -.0599348, .0818293, 1.1123, .985886, -.0399661, .0545872, 1.12771, .994021, -.0198682, .0269405, 1.14186, 1.00009, 271022e-9, -12989e-8, 1.15514, .538716, -990918e-11, .486732, 109675e-10, .550656, -250642e-9, .497518, 277412e-9, .55057, -.00100265, .497441, .00110974, .550903, -.00225672, .497733, .00249779, .550568, -.00401046, .497438, .00443906, .550574, -.00626613, .49744, .00693637, .550591, -.0090226, .497449, .00998921, .550623, -.0122795, .497469, .0135984, .550667, -.0160361, .497495, .0177654, .550724, -.0202908, .497526, .0224915, .550792, -.0250421, .497557, .0277795, .550918, -.0302878, .49763, .0336334, .551058, -.0360241, .497701, .0400573, .551276, -.0422473, .497824, .0470585, .551551, -.0489441, .497977, .0546433, .552074, -.0559596, .498312, .0628367, .552681, -.0633978, .498679, .071646, .553324, -.0713176, .499031, .0810746, .554011, -.0797268, .499365, .091129, .55488, -.0885238, .499779, .101837, .556171, -.0974417, .500444, .113239, .557498, -.106841, .501025, .125316, .559299, -.116533, .501864, .138128, .561647, -.126298, .502967, .151695, .564347, -.136388, .504129, .16604, .567863, -.146576, .505713, .181207, .572569, -.156832, .507953, .197259, .578919, -.167323, .511186, .214258, .585387, -.177712, .514042, .232038, .593134, -.188184, .517484, .250733, .603295, -.198717, .522345, .270454, .613854, -.209177, .526751, .290807, .626092, -.219644, .531595, .312202, .637868, -.229494, .534721, .334435, .652458, -.238718, .538304, .359184, .666985, -.247061, .539875, .385637, .683301, -.254652, .541042, .41328, .69998, -.261376, .540735, .441903, .717824, -.267085, .539139, .471609, .734617, -.271465, .534958, .501446, .753663, -.27528, .53032, .532571, .770512, -.277617, .522134, .563641, .787356, -.278525, .51206, .595067, .806252, -.278512, .50119, .627226, .822061, -.277023, .486791, .659402, .838959, -.273175, .470467, .692874, .85379, -.267238, .450688, .725702, .868268, -.260327, .429741, .75832, .881994, -.251946, .407223, .790189, .893885, -.242432, .383214, .821625, .905118, -.231904, .357297, .853011, .916045, -.219545, .330733, .883773, .927614, -.205378, .303916, .914435, .936005, -.190388, .275941, .944502, .944533, -.1749, .247493, .974439, .950758, -.158588, .218996, 1.00286, .957078, -.141027, .191559, 1.0304, .962448, -.121507, .164457, 1.05466, .964993, -.102068, .138636, 1.0761, .970017, -.0822598, .111861, 1.09541, .97661, -.062033, .0843438, 1.11317, .985073, -.0409832, .0558496, 1.12911, .993515, -.020146, .0275331, 1.1438, 1.00006, 27329e-8, -107883e-9, 1.15736, .525324, -999341e-11, .498153, 105385e-10, .526513, -251605e-9, .499277, 265329e-9, .526517, -.00100641, .499282, .0010613, .526588, -.00226466, .499337, .00238823, .526539, -.0040255, .499302, .00424535, .526547, -.00628954, .499306, .00663364, .526561, -.00905628, .499313, .00955337, .526593, -.0123253, .499334, .0130054, .526642, -.0160957, .499365, .0169911, .5267, -.0203661, .499396, .0215122, .526792, -.0251347, .499451, .0265718, .526904, -.0303985, .499511, .0321732, .527079, -.0361554, .499617, .0383231, .527285, -.0423982, .499731, .045026, .527602, -.0491121, .499924, .0522936, .528166, -.0561127, .500306, .0601528, .52879, -.0635988, .5007, .0686059, .529421, -.071581, .501048, .0776518, .530144, -.0799854, .501421, .0873148, .531062, -.0888032, .501884, .0976084, .532374, -.0977643, .50259, .108588, .533828, -.107197, .50329, .120234, .53581, -.116887, .504312, .132602, .538063, -.126755, .505365, .145721, .5409, -.136819, .506668, .159617, .544882, -.147117, .508731, .174369, .550238, -.157446, .511601, .190028, .556038, -.167988, .514431, .206587, .563031, -.178364, .517808, .224046, .571543, -.189007, .521937, .242503, .582255, -.199546, .527415, .261977, .59272, -.210084, .531682, .282162, .605648, -.220448, .537123, .303426, .61785, -.230593, .540664, .325323, .632223, -.240238, .544467, .348993, .648819, -.24887, .547594, .375462, .665825, -.256657, .54912, .403024, .683389, -.263711, .549294, .431773, .701495, -.269666, .547649, .461494, .719197, -.274169, .543786, .491623, .737906, -.278124, .538644, .522994, .756652, -.280632, .531057, .554775, .775279, -.281741, .521972, .586441, .792688, -.281652, .509613, .618596, .811894, -.280345, .496497, .651462, .827938, -.277128, .47968, .684023, .844837, -.271646, .460688, .718024, .859239, -.264397, .438872, .751207, .874088, -.256144, .41577, .784232, .887693, -.246311, .391369, .816191, .899402, -.235497, .365872, .847828, .910973, -.223631, .338618, .87934, .92204, -.209874, .310803, .910325, .930987, -.194265, .281802, .940695, .94, -.178125, .252836, .970958, .948018, -.161479, .224239, 1.00078, .955141, -.144038, .195857, 1.0288, .960513, -.124915, .168487, 1.05371, .963964, -.104284, .141495, 1.07596, .968713, -.0838732, .114437, 1.09628, .975524, -.0635579, .0863105, 1.11448, .98431, -.042291, .0574774, 1.13069, .992916, -.0209131, .0284343, 1.14568, .999926, 743097e-9, -379265e-9, 1.15955, .501042, -998428e-11, .498726, 100306e-10, .502992, -252112e-9, .500665, 253283e-9, .502417, -.00100791, .500092, .00101259, .502965, -.00226919, .500621, .00227978, .502318, -.00403109, .499994, .00405011, .502333, -.00629832, .500005, .00632868, .502362, -.00906907, .500027, .00911446, .502369, -.0123423, .500023, .0124078, .50243, -.0161178, .500066, .016211, .502493, -.0203937, .500103, .0205256, .502592, -.0251684, .500166, .0253548, .502707, -.0304389, .50023, .0307029, .502881, -.0362015, .500335, .0365753, .503124, -.0424507, .500488, .0429798, .503443, -.0491582, .500686, .0499268, .504083, -.0561476, .501155, .0574541, .504668, -.0636846, .501524, .0655408, .505319, -.0716834, .501904, .0742072, .50609, -.0800925, .502321, .0834699, .507122, -.0888425, .502896, .0933603, .508414, -.097855, .503603, .10391, .509955, -.107304, .504416, .115113, .512061, -.116921, .505565, .127054, .514419, -.12689, .506732, .139709, .517529, -.136934, .508338, .153173, .522085, -.147327, .510987, .167528, .526986, -.157612, .513527, .182708, .533122, -.168213, .516717, .198881, .540807, -.178688, .520832, .215986, .550687, -.189511, .52632, .234335, .560567, -.199998, .531009, .253375, .571698, -.210652, .535839, .273499, .584364, -.220917, .541091, .294355, .599066, -.23137, .546875, .316525, .614148, -.241206, .551306, .339671, .631157, -.250379, .555187, .36531, .647919, -.258397, .556595, .392767, .666112, -.265528, .556949, .421397, .686158, -.271827, .556617, .451433, .704838, -.27674, .552975, .482131, .723957, -.280733, .547814, .513458, .74262, -.283359, .53997, .545446, .762009, -.284541, .530422, .57775, .781314, -.284507, .518546, .610434, .799116, -.283309, .504178, .643178, .817604, -.280378, .48843, .676248, .83459, -.275619, .469457, .709698, .850974, -.26856, .447698, .744245, .866747, -.260094, .424791, .777695, .881412, -.249929, .399913, .810392, .8936, -.239137, .37308, .842872, .905943, -.226818, .345705, .874677, .916408, -.213699, .31706, .906257, .927215, -.198428, .288444, .936881, .935625, -.181643, .258329, .96795, .944076, -.164386, .228488, .998216, .951229, -.146339, .199763, 1.02689, .958793, -.127709, .172153, 1.0535, .963219, -.107244, .144989, 1.07646, .967562, -.0857764, .11685, 1.09675, .974866, -.0645377, .0880571, 1.11576, .983353, -.0431732, .0587352, 1.13227, .992503, -.0218356, .0294181, 1.1478, 1.00003, 605203e-9, -231013e-9, 1.16207, .482935, -101177e-10, .504695, 968142e-11, .477554, -251521e-9, .499071, 240676e-9, .477904, -.00100683, .499436, 96342e-8, .478368, -.00226636, .499899, .0021687, .477977, -.00402719, .499513, .00385384, .477993, -.00629226, .499525, .0060221, .478011, -.00906011, .499536, .00867289, .478051, -.0123305, .499566, .0118074, .478089, -.016102, .499587, .0154269, .478171, -.0203736, .499645, .0195341, .478254, -.025143, .499692, .0241318, .47839, -.0304071, .499779, .0292247, .478588, -.0361631, .499911, .0348196, .478812, -.0424023, .500046, .0409231, .479208, -.0490724, .500326, .047552, .479841, -.0560722, .500805, .0547377, .480392, -.0636125, .501152, .0624607, .481068, -.0716134, .501561, .0707473, .481898, -.0800062, .502054, .0796118, .483022, -.0886568, .502728, .0890974, .484332, -.0977553, .503479, .0992099, .486126, -.107173, .504546, .10999, .488066, -.11677, .50557, .121476, .490521, -.126725, .506849, .133672, .494232, -.136793, .50911, .146731, .498302, -.147116, .511345, .160577, .503565, -.157446, .514344, .175335, .510902, -.168121, .518824, .191207, .519263, -.178799, .523666, .208058, .528204, -.189407, .528296, .225875, .538854, -.200145, .533724, .244782, .551278, -.210701, .539833, .264753, .565222, -.221303, .546131, .285745, .579403, -.231688, .551496, .307592, .595469, -.241718, .556809, .330582, .610929, -.250992, .559641, .354995, .629433, -.259602, .562379, .382471, .648504, -.267038, .563676, .411126, .66756, -.273388, .562092, .440924, .689143, -.278788, .560807, .472118, .709056, -.282783, .555701, .503774, .729855, -.285836, .548698, .536364, .748954, -.287078, .538544, .56895, .768373, -.287133, .526711, .601991, .78827, -.285839, .512511, .635403, .807465, -.283238, .496323, .668797, .825194, -.27906, .477638, .702584, .842203, -.272286, .456253, .736393, .857749, -.263854, .432412, .77096, .874799, -.253943, .407806, .80489, .887497, -.24237, .38033, .83771, .89966, -.230278, .352446, .870376, .911753, -.21646, .323268, .902256, .923011, -.202071, .294314, .933306, .932375, -.185519, .264104, .965177, .940537, -.167604, .234035, .996303, .948904, -.149068, .20412, 1.0261, .955263, -.129539, .175431, 1.05304, .960303, -.109932, .148116, 1.07617, .965512, -.0880572, .119693, 1.09742, .973466, -.0660548, .0901619, 1.11721, .98284, -.0439228, .0599875, 1.13436, .992216, -.0219588, .0298975, 1.15006, .999946, 119402e-9, -208547e-10, 1.16471, .447827, -100414e-10, .491543, 914833e-11, .454778, -251257e-9, .499172, 22891e-8, .453519, -.00100342, .497787, 914184e-9, .45357, -.00225776, .497847, .00205701, .453578, -.00401371, .497855, .00365705, .45357, -.00627107, .497841, .00571453, .453598, -.00902968, .497864, .00823019, .453627, -.0122888, .497882, .0112049, .453684, -.0160475, .497923, .0146405, .453764, -.0203044, .49798, .0185394, .453866, -.0250576, .498049, .0229054, .453996, -.0303028, .49813, .0277424, .454196, -.0360379, .498267, .0330587, .454457, -.0422521, .498445, .0388613, .454926, -.0488393, .498812, .0451767, .455525, -.0558653, .499272, .0520153, .456074, -.0633772, .499625, .0593754, .456752, -.0713606, .500049, .0672751, .457648, -.07971, .500615, .0757447, .458849, -.0883032, .501399, .0848231, .46029, -.0974095, .502293, .0945135, .462, -.106729, .503301, .104848, .464121, -.116354, .504533, .115884, .466889, -.126214, .506172, .127652, .470744, -.136324, .508667, .14024, .47488, -.146595, .510995, .153673, .480845, -.157027, .514832, .168053, .488262, -.167658, .519506, .183508, .496547, -.178343, .524347, .199948, .506254, -.188916, .52983, .217503, .517961, -.199975, .536357, .236272, .531484, -.210624, .543641, .256096, .545496, -.221227, .550048, .277085, .559497, -.231568, .555076, .298615, .575752, -.241698, .560541, .321547, .591999, -.251172, .564156, .345602, .610654, -.260178, .567607, .371851, .630484, -.268094, .56923, .40076, .651807, -.274661, .569779, .430801, .67239, -.280331, .566791, .461939, .693024, -.284501, .562007, .493854, .715473, -.287852, .555791, .526992, .736323, -.28929, .546345, .560102, .755771, -.289405, .534, .593543, .775424, -.2881, .519114, .627256, .795447, -.285562, .502543, .661464, .815319, -.281416, .484773, .695206, .831769, -.275523, .463445, .729044, .849464, -.267516, .440269, .764069, .866775, -.257584, .415049, .799089, .881252, -.245817, .388049, .831948, .894209, -.233127, .35889, .865526, .906922, -.219579, .329915, .89818, .919686, -.204491, .300441, .930013, .929044, -.188962, .269445, .962061, .938393, -.171079, .238402, .994214, .94661, -.15199, .208204, 1.02533, .953095, -.131953, .178653, 1.0529, .958644, -.111233, .150684, 1.0771, .963925, -.0903098, .122359, 1.09855, .971995, -.0680505, .0923342, 1.11874, .981658, -.0448512, .0614195, 1.13635, .991649, -.0221931, .0303582, 1.15238, .999985, 393403e-9, -111086e-9, 1.16772, .396806, -971563e-11, .457671, 842355e-11, .429186, -249421e-9, .495017, 21625e-8, .429324, -998052e-9, .495173, 865322e-9, .429175, -.00224487, .494999, .00194637, .429129, -.00399041, .494952, .00346004, .429153, -.00623476, .494974, .00540684, .429168, -.0089773, .494983, .00778714, .429207, -.0122175, .495012, .0106022, .429257, -.0159542, .495047, .0138535, .429338, -.0201864, .495106, .0175443, .429431, -.0249104, .495165, .0216774, .429587, -.0301252, .495279, .0262594, .429796, -.0358249, .495432, .0312968, .430065, -.0419972, .495621, .0367985, .430588, -.0485144, .496061, .042798, .43113, -.0555028, .496472, .0492914, .431743, -.0629852, .496904, .0562907, .432448, -.0709256, .497369, .0638056, .433414, -.0791942, .498032, .071885, .434638, -.0877346, .498854, .0805517, .43611, -.0968056, .499812, .0898047, .437859, -.106002, .500891, .0997142, .440017, -.115648, .502198, .110289, .443236, -.125427, .504389, .121644, .44697, -.135492, .506809, .133769, .451689, -.145746, .509858, .146787, .45811, -.156219, .514247, .160793, .465305, -.166834, .518816, .175791, .474085, -.177546, .524331, .191906, .484808, -.188262, .53104, .209199, .49732, -.199346, .538511, .227825, .509693, -.209951, .544554, .247269, .524367, -.220533, .551616, .267978, .539228, -.231082, .557368, .289672, .55644, -.241342, .563782, .31268, .574204, -.250964, .568851, .33651, .593388, -.260306, .57312, .362219, .613358, -.268667, .574916, .390322, .634512, -.275591, .575053, .420478, .65563, -.281328, .572404, .451614, .678265, -.285948, .568893, .484112, .70011, -.289408, .561878, .517348, .723005, -.291328, .55359, .551355, .743744, -.291418, .541099, .585109, .763949, -.290252, .526489, .619487, .784186, -.287648, .509496, .65404, .804304, -.283782, .491484, .688649, .823629, -.278067, .470517, .723133, .84094, -.270588, .44705, .757163, .857852, -.261188, .421252, .792816, .874934, -.249313, .394191, .827248, .888709, -.236492, .365359, .861074, .902589, -.222185, .336016, .894417, .914201, -.207314, .30527, .926825, .925978, -.191146, .274532, .9595, .93512, -.174135, .243393, .991583, .943656, -.155231, .212414, 1.02356, .951719, -.134403, .182005, 1.05239, .957164, -.113023, .153043, 1.07754, .962656, -.0914493, .124186, 1.09984, .970695, -.0694179, .0941654, 1.12, .980749, -.0466199, .0629671, 1.13849, .991205, -.0227032, .0311146, 1.15494, .999884, 632388e-9, -254483e-9, 1.1706, .379821, -957289e-11, .460637, 789337e-11, .405188, -247483e-9, .491396, 204064e-9, .404796, -989434e-9, .490914, 815853e-9, .40483, -.00222607, .490949, .00183559, .40473, -.00395723, .49084, .00326332, .404731, -.00618287, .490836, .00509945, .404768, -.00890258, .490871, .00734463, .404791, -.0121156, .490883, .00999992, .404857, -.0158214, .490938, .0130676, .404943, -.0200178, .491004, .0165503, .405059, -.0247027, .491093, .0204521, .405213, -.0298729, .491205, .0247788, .405399, -.0355226, .491333, .0295373, .405731, -.0416352, .491604, .034741, .406303, -.0480807, .492116, .0404255, .406814, -.0550458, .492506, .0465732, .407404, -.0624652, .492926, .0532058, .408149, -.0702958, .493442, .0603442, .409128, -.0784623, .494136, .0680297, .410408, -.087007, .495054, .0762786, .411813, -.0959639, .495962, .0851046, .413735, -.105075, .497257, .0945878, .416137, -.114646, .498882, .104725, .41934, -.124394, .501132, .11563, .423326, -.134328, .503883, .127325, .428419, -.14458, .50747, .139911, .43484, -.154979, .511964, .153481, .442641, -.165628, .517328, .168114, .452511, -.176365, .524258, .183995, .463473, -.187298, .531248, .200953, .475564, -.198244, .538367, .219176, .488664, -.208938, .545175, .238514, .504073, -.219599, .553227, .259129, .520832, -.230378, .560653, .280997, .538455, -.240703, .567523, .303821, .55709, -.250548, .573287, .327948, .576646, -.259964, .577795, .353362, .596705, -.268721, .580077, .380336, .618053, -.276054, .58018, .4101, .640303, -.282176, .578747, .44161, .662365, -.286931, .574294, .474106, .684542, -.290521, .567035, .507549, .707984, -.292672, .558687, .541853, .730913, -.293189, .547606, .576581, .752948, -.292199, .533471, .61172, .773452, -.289508, .516395, .646339, .794715, -.285716, .497873, .682131, .814251, -.280051, .476845, .716396, .833057, -.272873, .453449, .751503, .84959, -.263982, .427857, .786085, .867022, -.252745, .400335, .821355, .882277, -.239655, .371304, .85646, .895375, -.225386, .340397, .890828, .909347, -.209587, .310005, .923532, .921885, -.193433, .2796, .956419, .932127, -.176135, .247276, .989445, .941869, -.157872, .216186, 1.02221, .949735, -.137577, .185602, 1.05195, .956617, -.115285, .155767, 1.07822, .961974, -.0928418, .126103, 1.10149, .96972, -.0700592, .0956758, 1.12207, .98012, -.0474671, .0643269, 1.1408, .990825, -.0238113, .0320863, 1.1577, .999876, 381574e-9, -812203e-10, 1.17403, .367636, -961342e-11, .469176, 753287e-11, .380377, -244772e-9, .485434, 191797e-9, .380416, -978857e-9, .485475, 767015e-9, .380376, -.00220165, .485435, .00172522, .380419, -.00391408, .485487, .00306734, .380438, -.00611549, .485505, .00479332, .380462, -.00880558, .485525, .00690391, .380496, -.0119837, .485551, .00940039, .38056, -.0156487, .485605, .0122848, .38064, -.0197988, .485666, .0155601, .380767, -.0244324, .48577, .0192313, .380909, -.0295444, .485871, .0233032, .381142, -.0351321, .48606, .0277861, .381472, -.0411535, .486336, .0326939, .382015, -.0475408, .486833, .0380565, .382523, -.0544395, .487231, .0438615, .383129, -.061784, .487683, .0501332, .383952, -.0695085, .488313, .0568996, .38498, -.0775819, .489077, .0641952, .386331, -.0860443, .490113, .0720324, .387788, -.0948406, .491099, .0804379, .389808, -.103899, .492566, .0894899, .39252, -.113313, .494601, .0992098, .395493, -.123007, .496619, .109641, .399826, -.132859, .499912, .120919, .405341, -.143077, .504061, .133107, .411932, -.153465, .508905, .146263, .420591, -.164108, .515482, .160544, .43101, -.174893, .523191, .176123, .441881, -.185839, .53026, .192757, .453919, -.196633, .537295, .210535, .468715, -.207611, .546156, .229886, .485182, -.218517, .555173, .250543, .501926, -.229249, .562728, .27221, .51785, -.239481, .567494, .294892, .536947, -.249395, .573889, .318987, .557115, -.259, .578831, .344348, .577966, -.268075, .582055, .371223, .599489, -.276115, .583307, .399834, .62479, -.282523, .583902, .431415, .647504, -.287663, .57953, .464301, .670601, -.291538, .573103, .498123, .693539, -.293842, .563731, .532662, .717385, -.294681, .553169, .567925, .741533, -.293717, .539908, .603502, .762142, -.291156, .521902, .639074, .783014, -.28719, .502815, .674439, .805158, -.281773, .482598, .710497, .823646, -.274682, .458949, .7456, .841879, -.266184, .433129, .781085, .859515, -.255682, .406064, .816, .875335, -.242849, .376509, .851074, .890147, -.228329, .345502, .886473, .903144, -.212491, .31428, .920751, .916618, -.195695, .282994, .954606, .927953, -.178267, .251091, .988402, .937414, -.159549, .219107, 1.02141, .946823, -.140022, .18896, 1.05167, .954651, -.118154, .158667, 1.07819, .959955, -.0946636, .128808, 1.1025, .96858, -.0711792, .0973787, 1.12391, .97938, -.0475046, .0650965, 1.14322, .990498, -.024059, .0326267, 1.16077, .999844, -512408e-10, 112444e-9, 1.17727, .316912, -934977e-11, .425996, 695559e-11, .356423, -241372e-9, .479108, 179562e-9, .356272, -965292e-9, .478897, 71811e-8, .356262, -.00217182, .478894, .00161574, .356265, -.00386092, .478895, .00287261, .356278, -.0060324, .478905, .00448907, .356293, -.00868565, .478914, .00646572, .356346, -.0118207, .478965, .00880438, .356395, -.0154355, .479001, .0115066, .356484, -.019529, .479075, .0145762, .356609, -.0240991, .47918, .018018, .356766, -.0291413, .479305, .0218379, .357009, -.0346498, .479512, .0260454, .357424, -.0405462, .479909, .0306657, .357899, -.0468825, .480337, .0357054, .358424, -.0536887, .480771, .0411728, .359041, -.0609416, .481242, .0470841, .359903, -.0685239, .481943, .0534831, .360932, -.0764883, .482741, .0603795, .362196, -.0848364, .483688, .0678028, .363847, -.0935002, .484947, .0758086, .365972, -.102471, .486588, .0844173, .368741, -.111751, .488787, .0937199, .372146, -.121334, .491405, .103732, .377114, -.131147, .495604, .114608, .38226, -.141213, .499436, .126345, .389609, -.151632, .505334, .139116, .397925, -.162073, .51168, .152995, .407824, -.172819, .518876, .168071, .420014, -.183929, .527639, .184495, .434266, -.195032, .537588, .20232, .447352, -.205792, .544379, .221189, .463726, -.216704, .553422, .241616, .481406, -.227531, .562074, .263298, .498707, -.238017, .568227, .286116, .518039, -.247936, .574473, .3101, .538277, -.257437, .579191, .335401, .561166, -.266829, .584807, .362246, .583189, -.275329, .586476, .390609, .606024, -.28234, .585578, .420998, .632419, -.287924, .584496, .454357, .656128, -.291972, .577766, .488233, .679953, -.29456, .56875, .523248, .704654, -.295816, .558388, .559168, .729016, -.295157, .544826, .595326, .752062, -.292779, .528273, .631864, .773138, -.288681, .508482, .667793, .794869, -.283358, .487341, .704035, .815101, -.27608, .46354, .739925, .834212, -.26767, .438672, .775539, .852368, -.257397, .411239, .810895, .870207, -.245689, .3829, .846472, .884063, -.231452, .351496, .881788, .898284, -.215561, .31895, .917438, .912964, -.198208, .287367, .952422, .924666, -.180426, .254487, .987551, .934429, -.161525, .222226, 1.02142, .943485, -.141197, .191143, 1.05218, .9521, -.120085, .161112, 1.07937, .957876, -.0975881, .130982, 1.10403, .966943, -.0726842, .0990553, 1.12616, .978313, -.0483705, .0662818, 1.14619, .990048, -.0239072, .0329243, 1.16413, .999984, 461885e-9, -772859e-10, 1.18099, .321287, -935049e-11, .455413, 659662e-11, .332595, -237513e-9, .471437, 167562e-9, .332729, -949964e-9, .471618, 670192e-9, .332305, -.00213618, .471028, .00150712, .332326, -.00379765, .471055, .00267959, .332344, -.00593353, .471072, .00418751, .332356, -.00854349, .471077, .00603172, .332403, -.0116268, .471121, .00821362, .332461, -.0151824, .47117, .0107357, .332552, -.0192088, .471251, .0136014, .332657, -.0237024, .47133, .0168152, .332835, -.0286615, .471487, .0203853, .333083, -.0340765, .471708, .0243212, .333547, -.0398563, .47219, .0286518, .333989, -.0460916, .472587, .0333763, .334532, -.0527897, .473054, .0385084, .335167, -.0599284, .473568, .0440638, .33608, -.0673514, .474362, .0500962, .337146, -.0752237, .475231, .0566022, .338462, -.083418, .476282, .0636272, .34014, -.0919382, .477615, .0712153, .342341, -.100741, .479404, .079417, .345088, -.109905, .481618, .0882631, .349049, -.119369, .485081, .0978851, .353939, -.129033, .489317, .108336, .359893, -.139038, .494309, .119698, .366945, -.149411, .499983, .132024, .375814, -.159843, .507185, .145558, .387112, -.170664, .516392, .160433, .40023, -.181897, .526519, .176648, .412555, -.192785, .53423, .193922, .427023, -.203663, .542741, .212662, .443685, -.214695, .552066, .232944, .461499, -.225561, .560762, .254495, .480975, -.236257, .569421, .277531, .501, -.24639, .576101, .301724, .521691, -.256101, .581493, .327112, .543478, -.265289, .585221, .353917, .566094, -.273938, .587614, .381941, .589578, -.281679, .587991, .41172, .614583, -.287655, .585928, .444148, .641813, -.292228, .582092, .478617, .666189, -.295172, .57398, .51397, .690475, -.29648, .561676, .550118, .715543, -.296203, .548758, .586933, .740405, -.293999, .532792, .62384, .762183, -.28998, .512735, .660723, .786069, -.28478, .492402, .69807, .806812, -.277568, .469058, .734422, .826987, -.268951, .443017, .770946, .844588, -.259049, .415501, .80699, .863725, -.2471, .387328, .842107, .879137, -.234157, .356108, .878078, .894634, -.218719, .324315, .914058, .909162, -.201293, .291813, .949922, .92072, -.18267, .258474, .985337, .93158, -.163212, .225593, 1.0205, .941238, -.142771, .193986, 1.05273, .949293, -.120956, .163392, 1.08075, .956226, -.0985743, .132934, 1.10559, .96546, -.075118, .101255, 1.12823, .977403, -.0497921, .0675441, 1.149, .989648, -.0241574, .0334681, 1.16765, 1.00001, 5762e-7, -184807e-9, 1.18519, .303474, -916603e-11, .4542, 61243e-10, .308894, -232869e-9, .462306, 155592e-9, .309426, -931661e-9, .463093, 622499e-9, .308643, -.0020949, .461933, .00139979, .308651, -.0037242, .461941, .00248874, .308662, -.00581873, .46195, .00388933, .308687, -.00837818, .461974, .00560247, .308728, -.0114016, .462011, .00762948, .308789, -.0148884, .462067, .00997326, .308882, -.0188369, .462151, .0126375, .309007, -.0232436, .462263, .0156271, .30918, -.0281054, .462417, .0189498, .309442, -.0334065, .462667, .0226167, .309901, -.0390589, .463162, .0266614, .310331, -.0452042, .463555, .0310715, .310858, -.0517735, .464019, .0358698, .311576, -.0587359, .464669, .0410848, .312436, -.0660383, .465406, .0467453, .313526, -.0737266, .466339, .0528718, .314903, -.0817574, .467504, .0595039, .316814, -.090167, .469226, .0666888, .318965, -.0987555, .470981, .0744658, .322077, -.107792, .473814, .082912, .325947, -.117098, .477241, .0920846, .331008, -.126602, .48184, .102137, .337893, -.136619, .488334, .113135, .345106, -.146838, .494415, .12511, .355111, -.157357, .503275, .138356, .365095, -.167955, .510966, .152686, .378344, -.179157, .521508, .16856, .391599, -.190143, .530455, .18561, .407786, -.20123, .541275, .204308, .425294, -.212456, .551784, .224623, .444021, -.223568, .561493, .246172, .463418, -.234154, .569886, .268979, .484077, -.244546, .577116, .293411, .505513, -.254301, .582914, .318936, .527672, -.263564, .587208, .345856, .550565, -.272332, .589277, .374054, .573656, -.280011, .588426, .403276, .59827, -.286924, .587504, .43474, .624731, -.291994, .583401, .468767, .652396, -.295159, .576997, .504411, .67732, -.296954, .565863, .54114, .703147, -.296877, .552316, .57816, .728715, -.295147, .536773, .616124, .752448, -.291275, .51771, .653885, .775169, -.285905, .496087, .691537, .799307, -.279064, .474232, .729251, .819482, -.270294, .447676, .766267, .837659, -.260032, .419656, .802616, .856903, -.248497, .391328, .838583, .873325, -.235252, .360285, .874711, .889788, -.221126, .329215, .91077, .904486, -.204304, .296392, .94653, .917711, -.185562, .262159, .983828, .928969, -.165635, .229142, 1.01955, .939707, -.14442, .19673, 1.05317, .948167, -.122147, .165095, 1.0823, .955222, -.099098, .13451, 1.10791, .964401, -.0755332, .102476, 1.1312, .976605, -.0513817, .0689667, 1.15218, .989085, -.0258499, .034506, 1.17129, .999908, 617773e-9, -271268e-9, 1.18961, .285803, -905752e-11, .452348, 572272e-11, .284689, -22732e-8, .450581, 143626e-9, .285263, -910214e-9, .451482, 575099e-9, .285302, -.00204784, .451553, .00129395, .285318, -.00364057, .451574, .0023006, .28533, -.00568813, .451585, .00359547, .285361, -.00819001, .451618, .00517934, .285397, -.0111458, .45165, .007054, .285447, -.0145536, .451688, .00922167, .285527, -.0184127, .451758, .0116869, .285688, -.0227207, .451929, .0144555, .28584, -.0274712, .452055, .0175341, .286136, -.0326278, .452369, .0209406, .286574, -.0381792, .452853, .0246965, .287012, -.0441879, .453272, .0287996, .287542, -.0506096, .453752, .033268, .288299, -.0573634, .454488, .0381504, .289186, -.0645458, .455294, .0434447, .290302, -.0720405, .456301, .0491973, .291776, -.0799046, .457648, .0554453, .29372, -.088117, .459483, .0622311, .296052, -.0965328, .461571, .0695992, .299563, -.105409, .465085, .077658, .30335, -.114553, .468506, .0864176, .309167, -.123917, .474423, .0961078, .31529, -.13381, .47995, .106643, .324163, -.144021, .488592, .118322, .333272, -.154382, .496461, .131133, .344224, -.165015, .50562, .145208, .357733, -.176168, .516719, .16073, .373046, -.187468, .528513, .177807, .38788, -.198488, .537713, .196072, .405133, -.209545, .547999, .21605, .423845, -.220724, .55759, .237484, .443777, -.231518, .566246, .26039, .464824, -.242035, .574326, .284835, .486635, -.251898, .58037, .310518, .51012, -.261304, .58568, .337678, .535301, -.270384, .590197, .366242, .559193, -.27841, .590569, .395873, .583544, -.285325, .588161, .426857, .608834, -.291113, .584249, .459477, .635753, -.294882, .57763, .494734, .664367, -.297088, .569479, .532023, .689688, -.297364, .555064, .569629, .715732, -.295949, .539522, .608124, .741307, -.292259, .521613, .646231, .764949, -.287063, .49969, .684938, .788599, -.28012, .476747, .723548, .81048, -.27153, .45116, .761135, .831372, -.261289, .424101, .798916, .850092, -.249559, .39443, .835952, .867777, -.236348, .363849, .871606, .884632, -.221569, .332477, .907843, .90047, -.20618, .300667, .944187, .914524, -.188771, .266552, .981371, .926892, -.168362, .232349, 1.01841, .937951, -.146761, .199359, 1.05308, .947236, -.123813, .1675, 1.0839, .954367, -.099984, .136166, 1.11047, .963907, -.0759278, .103808, 1.13414, .976218, -.0511367, .0697061, 1.15575, .988772, -.0267415, .0352529, 1.17531, .999888, -520778e-9, 289926e-9, 1.19389, .263546, -883274e-11, .441896, 526783e-11, .262352, -221849e-9, .439889, 132311e-9, .262325, -886683e-9, .439848, 528824e-9, .26228, -.00199476, .439765, .00118975, .262372, -.00354671, .439922, .00211568, .26239, -.00554141, .439941, .00330652, .262412, -.00797888, .439961, .00476346, .262453, -.0108584, .440002, .00648818, .262528, -.0141788, .440085, .0084835, .262615, -.017938, .440166, .0107533, .262744, -.0221346, .440291, .0133044, .262939, -.026762, .440493, .0161445, .263277, -.0317573, .440889, .0192974, .26368, -.0371832, .441338, .0227699, .264106, -.0430371, .441753, .0265698, .264624, -.0493035, .442227, .0307178, .265378, -.0558669, .442985, .0352616, .266253, -.0628718, .443795, .0401968, .267478, -.0701569, .445008, .04559, .269062, -.077845, .446599, .0514539, .270926, -.0857941, .448349, .0578382, .273693, -.0940773, .451221, .0648363, .276746, -.102704, .454097, .0724389, .281693, -.111735, .459517, .0808744, .287335, -.121004, .46531, .0901551, .29448, -.130734, .472605, .100371, .30257, -.140777, .480251, .111644, .312465, -.15111, .489444, .124111, .324856, -.16189, .500919, .137979, .33774, -.172946, .511317, .153163, .35255, -.184152, .522684, .169817, .367786, -.19522, .53248, .187886, .385474, -.20632, .543326, .207634, .404976, -.217744, .554109, .229165, .425203, -.228691, .563395, .252068, .446704, -.239299, .571565, .276471, .468951, -.249348, .577935, .302323, .493487, -.258933, .584309, .329882, .517861, -.268009, .58773, .358525, .543309, -.276238, .589612, .388585, .569704, -.28356, .589294, .419787, .594871, -.289497, .585137, .452114, .622555, -.294452, .580356, .486466, .651167, -.296918, .57185, .523079, .677332, -.297647, .558428, .5611, .703718, -.296321, .542232, .599592, .730262, -.293339, .524541, .639138, .754304, -.288036, .502691, .677978, .778051, -.281018, .479212, .716537, .801557, -.272414, .454071, .75586, .822559, -.262419, .425952, .794477, .843051, -.250702, .397313, .832664, .86232, -.237264, .366534, .869876, .879044, -.222716, .334816, .906973, .896362, -.206827, .303143, .943558, .910342, -.189659, .269699, .979759, .924119, -.171108, .236411, 1.01718, .935374, -.149579, .202224, 1.05289, .944295, -.126295, .16989, 1.08496, .952227, -.101511, .138089, 1.11256, .962041, -.0766392, .105053, 1.1375, .97528, -.0511967, .070329, 1.15983, .988476, -.025463, .0351268, 1.17987, .999962, 286808e-10, 145564e-10, 1.19901, .227089, -841413e-11, .404216, 472707e-11, .239725, -215083e-9, .426708, 120833e-9, .239904, -860718e-9, .427028, 483555e-9, .239911, -.00193661, .427039, .00108806, .239914, -.00344276, .42704, .00193457, .239933, -.00537907, .427064, .00302363, .239944, -.00774482, .427065, .00435604, .239993, -.01054, .427122, .00593398, .240052, -.0137626, .427179, .00775987, .240148, -.0174115, .427279, .00983854, .240278, -.021484, .42741, .0121763, .240472, -.0259729, .427618, .0147827, .240839, -.0308131, .428086, .0176837, .241201, -.0360893, .428482, .0208775, .241626, -.0417723, .428907, .0243821, .242207, -.0478337, .42952, .0282228, .24298, -.0542199, .430332, .0324333, .243881, -.0610015, .431222, .0370252, .245123, -.0680874, .432512, .0420535, .24667, -.0755482, .434088, .0475414, .248779, -.0832873, .436323, .0535542, .251665, -.0913546, .439509, .0601716, .255305, -.0998489, .443478, .0674282, .260049, -.108576, .448713, .0754673, .266192, -.117754, .455524, .084339, .273158, -.127294, .4627, .0941683, .282131, -.137311, .472068, .10515, .293332, -.147736, .483565, .117402, .304667, -.158357, .493702, .130824, .317785, -.169274, .504708, .145724, .333245, -.180595, .517107, .16215, .349843, -.191892, .528849, .180149, .367944, -.203168, .540301, .199746, .387579, -.214443, .551514, .221047, .408247, -.225624, .560906, .243981, .43014, -.236422, .56959, .268513, .452669, -.24654, .576098, .294409, .476196, -.256157, .580925, .322002, .501157, -.265289, .584839, .351052, .527632, -.273671, .587614, .3812, .555754, -.281254, .589119, .412994, .581682, -.287448, .585204, .445498, .608196, -.292614, .579006, .479505, .635661, -.296068, .571297, .514643, .664999, -.297395, .560855, .552213, .691039, -.296645, .544525, .591365, .7179, -.293785, .526535, .630883, .744059, -.289089, .50545, .670932, .76863, -.282239, .482514, .710904, .793273, -.273688, .457246, .750259, .814731, -.26328, .428872, .78948, .835603, -.251526, .399384, .828597, .85489, -.238339, .368811, .866892, .872828, -.223607, .336617, .90563, .889462, -.207538, .303997, .943538, .904929, -.190297, .270812, .980591, .919101, -.172034, .237453, 1.01935, .930536, -.152058, .204431, 1.05498, .941223, -.129515, .172495, 1.08717, .94982, -.104263, .140175, 1.11551, .960592, -.0781944, .106465, 1.14098, .974629, -.051688, .0711592, 1.16418, .98811, -.0253929, .0354432, 1.18465, 1.00004, 804378e-9, -330876e-9, 1.20462, .214668, -821282e-11, .406619, 433582e-11, .218053, -208144e-9, .413025, 109887e-9, .217987, -832212e-9, .412901, 439362e-9, .217971, -.00187246, .412876, 988623e-9, .217968, -.00332855, .41286, .00175772, .217985, -.00520055, .412882, .00274729, .218014, -.00748814, .412916, .00395842, .218054, -.0101901, .412957, .00539274, .218106, -.0133057, .413005, .00705348, .218217, -.0168342, .413139, .00894581, .218338, -.0207707, .413258, .0110754, .21855, -.0251001, .413509, .0134551, .218913, -.0297861, .413992, .0161081, .219265, -.0348956, .414383, .0190307, .219696, -.0403909, .414839, .0222458, .220329, -.0462003, .415567, .025792, .220989, -.0524208, .41621, .0296637, .222027, -.058948, .417385, .0339323, .223301, -.0658208, .418779, .0386055, .224988, -.0730347, .420665, .0437355, .227211, -.0805274, .423198, .0493844, .230131, -.088395, .426566, .0556135, .233908, -.0966208, .43091, .0624829, .239092, -.105223, .437148, .0701636, .245315, -.11424, .444302, .0786949, .253166, -.12368, .453262, .0882382, .262374, -.133569, .463211, .0988682, .273145, -.143836, .474271, .110727, .285512, -.154577, .4863, .123945, .299512, -.165501, .498817, .138581, .314287, -.176698, .510341, .154676, .331083, -.188066, .522583, .172459, .349615, -.199597, .534879, .191979, .369318, -.210843, .546083, .21309, .390377, -.222068, .5562, .235998, .412411, -.233059, .564704, .260518, .435715, -.24357, .572314, .286795, .461196, -.253356, .579395, .314559, .485587, -.262362, .581985, .343581, .511908, -.270895, .584347, .374367, .539798, -.278452, .58505, .406015, .567974, -.284877, .583344, .439168, .594303, -.290124, .577348, .473005, .622951, -.294183, .570751, .508534, .652404, -.296389, .561541, .544764, .679291, -.296605, .546426, .582927, .706437, -.294095, .528599, .622681, .734485, -.28978, .508676, .663567, .758841, -.283363, .484768, .704092, .78537, -.275015, .460434, .745101, .807315, -.264689, .432166, .784712, .8271, -.252597, .401807, .824241, .849191, -.239154, .371458, .863803, .867046, -.224451, .338873, .903063, .8852, -.208342, .306175, .942763, .901771, -.190684, .272759, .981559, .915958, -.172105, .239306, 1.02048, .928046, -.152214, .206071, 1.05765, .939961, -.130247, .17367, 1.08999, .948711, -.10672, .142201, 1.11829, .959305, -.0808688, .108454, 1.14467, .973009, -.0539145, .0728109, 1.16839, .987631, -.0262947, .0360625, 1.19004, .999978, .00132758, -559424e-9, 1.21058, .193925, -793421e-11, .391974, 392537e-11, .196746, -200315e-9, .397675, 991033e-10, .19667, -801099e-9, .397521, 396342e-9, .196633, -.00180246, .397445, 891829e-9, .196654, -.00320443, .397482, .00158582, .196659, -.00500647, .39748, .00247867, .196683, -.0072086, .397506, .00357167, .196728, -.00981001, .397562, .00486675, .196792, -.0128096, .397633, .00636707, .19689, -.0162055, .397746, .00807752, .197017, -.0199943, .397884, .0100052, .19729, -.024139, .39827, .0121691, .197583, -.0286671, .398639, .0145755, .197927, -.0335858, .399034, .0172355, .198383, -.0388806, .399554, .0201718, .199002, -.0444736, .400289, .0234194, .199739, -.0504583, .401111, .026984, .200784, -.056729, .402349, .0309217, .202075, -.0633643, .403841, .0352496, .203898, -.0703247, .406076, .0400313, .206199, -.0775565, .408841, .0453282, .209252, -.085184, .41259, .0511794, .213638, -.0931994, .418288, .0577459, .21881, -.101617, .424681, .0650508, .225642, -.11052, .433429, .0732759, .233717, -.119772, .442897, .0824683, .242823, -.129505, .452888, .0927484, .254772, -.139906, .466407, .104417, .266603, -.150402, .477413, .117211, .28073, -.161395, .490519, .131598, .295399, -.172465, .50201, .147407, .312705, -.183982, .515311, .165031, .331335, -.195532, .52786, .184336, .351037, -.206971, .5392, .205361, .372175, -.218117, .54941, .228043, .394548, -.229327, .558642, .25267, .419598, -.240052, .567861, .279071, .443922, -.249937, .573332, .306882, .471495, -.259407, .58013, .33661, .496769, -.267749, .580564, .367328, .524951, -.275524, .581696, .399753, .55318, -.282148, .579885, .433134, .581577, -.287533, .575471, .467534, .609231, -.291612, .567445, .502943, .637478, -.293911, .557657, .53871, .667795, -.295096, .546535, .576568, .694272, -.294073, .529561, .614929, .722937, -.290386, .510561, .655909, .749682, -.284481, .487846, .697663, .774754, -.276188, .462487, .738515, .799301, -.266215, .43481, .779802, .820762, -.254116, .404879, .820045, .843231, -.240393, .374559, .860294, .861857, -.225503, .341582, .900965, .880815, -.209382, .308778, .941727, .89766, -.19155, .275232, .980916, .912926, -.172346, .240938, 1.02162, .926391, -.151799, .207223, 1.0597, .938429, -.129968, .17484, 1.09291, .947834, -.10651, .142984, 1.12248, .958432, -.0824098, .109902, 1.149, .972402, -.0565242, .0744454, 1.1733, .987191, -.028427, .0373794, 1.19538, .999975, 385685e-10, -4203e-8, 1.21676, .178114, -766075e-11, .385418, 354027e-11, .176074, -191966e-9, .381002, 887135e-10, .17601, -767549e-9, .380861, 354715e-9, .17598, -.00172696, .380798, 798168e-9, .175994, -.00307012, .380824, .00141928, .176017, -.00479684, .380858, .00221859, .176019, -.00690648, .380839, .00319714, .176072, -.00939888, .380913, .0043572, .176131, -.0122726, .380979, .005702, .176239, -.0155264, .38112, .00723689, .176371, -.0191551, .381272, .00896907, .176638, -.023117, .381669, .0109194, .176912, -.0274633, .382015, .0130903, .177279, -.032173, .382476, .0154949, .17774, -.0372219, .383041, .0181669, .178344, -.0426132, .38378, .0211209, .179153, -.0483309, .384773, .0243899, .180197, -.0543447, .386076, .0280062, .181581, -.0607122, .387809, .032004, .18344, -.0673855, .390205, .036453, .186139, -.0743989, .393944, .0414162, .189432, -.0817731, .39832, .0469394, .193795, -.0895464, .404188, .0531442, .199641, -.0978264, .4121, .0601374, .206679, -.106499, .421425, .0680078, .214865, -.115654, .431504, .076919, .224406, -.125268, .442526, .0868835, .235876, -.135475, .455465, .0981875, .248335, -.146023, .4681, .110759, .262868, -.157016, .482069, .124885, .278962, -.168245, .496182, .140645, .295082, -.17958, .507401, .157838, .313738, -.191227, .520252, .17695, .333573, -.202718, .531708, .197817, .356433, -.214424, .544509, .220785, .378853, -.225492, .55373, .245306, .402717, -.236236, .561348, .271593, .428375, -.246568, .568538, .299776, .454724, -.255941, .573462, .329433, .482291, -.264511, .576356, .360598, .509706, -.272129, .576446, .393204, .538805, -.278979, .575298, .427227, .568919, -.284528, .572154, .462157, .596804, -.288801, .564691, .497997, .625987, -.291334, .555134, .534467, .656414, -.292722, .545051, .571736, .683916, -.292185, .528813, .610158, .711809, -.290043, .51106, .649061, .739547, -.285246, .490103, .690081, .766914, -.277647, .465523, .732554, .791375, -.267603, .437718, .773982, .814772, -.256109, .40882, .81609, .836691, -.242281, .377823, .856849, .856984, -.227155, .34496, .898363, .876332, -.210395, .311335, .939471, .894988, -.192612, .277703, .980799, .911113, -.173236, .243019, 1.02215, .924092, -.152258, .209037, 1.06139, .936828, -.129575, .175909, 1.09635, .946869, -.10594, .143852, 1.12707, .958284, -.081318, .110289, 1.15419, .972325, -.0556133, .0747232, 1.17909, .986878, -.0297899, .0383149, 1.20163, .999936, -.00197169, 912402e-9, 1.22338, .151174, -720365e-11, .351531, 309789e-11, .155594, -18279e-8, .361806, 78608e-9, .156099, -731569e-9, .362982, 314615e-9, .156053, -.00164578, .362869, 707845e-9, .156093, -.0029261, .362961, .00125884, .156099, -.00457155, .362959, .00196783, .15612, -.00658224, .362982, .00283622, .156168, -.00895774, .363048, .00386625, .156221, -.0116962, .363101, .00506109, .156324, -.0147973, .363241, .00642675, .156476, -.0182503, .363448, .00797175, .156731, -.0220266, .36384, .00971484, .156994, -.026176, .364179, .0116575, .157341, -.0306701, .36462, .0138207, .157867, -.0354591, .365364, .0162356, .15846, -.0406141, .366111, .0189092, .159308, -.0460519, .367248, .021885, .160426, -.0518096, .368767, .0252004, .161877, -.0578906, .370745, .0288825, .163995, -.0642812, .373831, .0330139, .16655, -.0710067, .377366, .0376283, .170237, -.0781522, .382799, .0428493, .175096, -.0857172, .389915, .0487324, .181069, -.0938025, .398487, .0554214, .188487, -.102363, .408799, .0630189, .197029, -.111343, .419991, .071634, .206684, -.120812, .431455, .0812797, .218698, -.131033, .445746, .0923651, .230726, -.141373, .457471, .104545, .245516, -.152387, .472388, .118449, .261551, -.163628, .486671, .133923, .277437, -.174814, .49762, .150849, .296662, -.186713, .51162, .169924, .31795, -.198513, .525435, .190848, .339422, -.210119, .536267, .213504, .362143, -.221354, .545982, .237947, .387198, -.23224, .555364, .264427, .412349, -.24257, .561489, .292519, .439274, -.252284, .566903, .322561, .466779, -.261023, .569614, .353952, .496011, -.26899, .571589, .387278, .524964, -.275498, .570325, .421356, .556518, -.281449, .568792, .457314, .584363, -.285526, .560268, .493199, .614214, -.28844, .55205, .530276, .645684, -.289777, .541906, .56855, .673446, -.289722, .526464, .606927, .701924, -.287792, .509872, .645945, .73037, -.284315, .490649, .685564, .757405, -.278804, .467964, .726511, .784025, -.269543, .441468, .768601, .808255, -.258117, .41216, .811321, .830739, -.244728, .380606, .853496, .851914, -.229428, .348111, .895374, .872586, -.212508, .314732, .937674, .891581, -.194025, .280338, .979869, .907641, -.174711, .245203, 1.02253, .922233, -.153509, .21077, 1.06371, .935878, -.130418, .177399, 1.09972, .946338, -.105558, .144507, 1.13124, .957265, -.080059, .110508, 1.15973, .971668, -.0539766, .0742311, 1.18515, .9866, -.0277101, .0375224, 1.20858, 1.00021, -515531e-9, 135226e-9, 1.23135, .137468, -686011e-11, .345041, 273315e-11, .13703, -173378e-9, .343936, 690761e-10, .136986, -693048e-9, .34383, 276126e-9, .136964, -.00155931, .343761, 621337e-9, .137003, -.00277211, .343863, .00110494, .137012, -.00433103, .343868, .00172744, .137043, -.00623606, .343916, .00249022, .13709, -.0084868, .343986, .00339559, .137145, -.0110814, .344045, .00444687, .137242, -.0140187, .344177, .00565007, .137431, -.0172713, .344491, .00701868, .137644, -.0208605, .344805, .00856042, .13791, -.024792, .345172, .0102863, .138295, -.0290461, .345734, .0122185, .138764, -.0335957, .346371, .0143771, .139415, -.038467, .347298, .0167894, .140272, -.0436176, .348527, .0194895, .141457, -.0491016, .350276, .0225043, .14303, -.0548764, .352646, .0258962, .145289, -.0610096, .356206, .0297168, .148502, -.0674777, .361488, .0340562, .152188, -.074345, .367103, .0389534, .157359, -.0817442, .375247, .0445541, .16379, -.0896334, .385064, .0509535, .171376, -.098005, .396082, .0582611, .179901, -.106817, .407418, .06654, .189892, -.116239, .420031, .075994, .201838, -.12627, .434321, .0867239, .214311, -.136701, .447631, .0987517, .228902, -.147616, .462046, .112353, .245107, -.158871, .476942, .127605, .262292, -.170261, .490285, .144469, .281215, -.182017, .503783, .163282, .301058, -.193729, .515505, .183873, .322752, -.205512, .52682, .206466, .347547, -.217214, .539473, .231194, .370969, -.227966, .546625, .257288, .397533, -.238555, .55472, .285789, .42398, -.248278, .559468, .315746, .452928, -.257422, .564095, .347724, .482121, -.265306, .565426, .380922, .510438, -.272043, .563205, .415639, .541188, -.277614, .561087, .451702, .571667, -.281927, .554922, .48845, .602432, -.285015, .546838, .526442, .634126, -.286512, .537415, .564896, .662816, -.286388, .522906, .604037, .692411, -.284734, .507003, .643795, .720946, -.281297, .488398, .68298, .748293, -.276262, .466353, .723466, .776931, -.269978, .443573, .764565, .801065, -.260305, .415279, .805838, .825843, -.247426, .384773, .849985, .84807, -.232437, .352555, .893174, .869122, -.215806, .318642, .936564, .888963, -.197307, .28381, .980253, .905547, -.177203, .247888, 1.02463, .918554, -.155542, .212904, 1.06714, .931395, -.131948, .1787, 1.10451, .941749, -.106723, .145902, 1.13694, .954551, -.0804939, .111193, 1.1666, .970279, -.0534239, .0744697, 1.19249, .986117, -.0257452, .0368788, 1.21665, .999938, .00190634, -.0010291, 1.23981, .118493, -647439e-11, .32272, 23772e-10, .118765, -163023e-9, .323456, 598573e-10, .118772, -65212e-8, .323477, 239447e-9, .118843, -.00146741, .323657, 538881e-9, .118804, -.00260846, .323553, 95826e-8, .118826, -.00407576, .323595, .00149845, .118846, -.00586826, .323617, .00216047, .118886, -.00798578, .32367, .00294679, .118947, -.0104273, .323753, .00386124, .119055, -.0131909, .323922, .00490999, .119241, -.0162444, .324251, .00610804, .11944, -.0196339, .324544, .00745805, .119739, -.0233378, .325026, .00897805, .12011, -.0273179, .325586, .0106895, .120571, -.0316143, .326231, .0126073, .12124, -.0361939, .327264, .0147654, .122162, -.0410511, .328733, .0172001, .123378, -.0462233, .330659, .0199375, .125183, -.0517109, .333754, .0230498, .127832, -.0575652, .338507, .026597, .130909, -.0637441, .343666, .0306345, .135221, -.0704302, .351063, .035273, .14082, -.0776364, .360604, .0406137, .146781, -.0852293, .369638, .0466788, .155121, -.0935351, .3827, .0537628, .16398, -.102234, .39522, .0617985, .173926, -.111465, .40793, .07097, .185137, -.121296, .42105, .0813426, .19826, -.13169, .435735, .0931596, .212938, -.142614, .450932, .106547, .229046, -.153884, .465726, .121575, .246246, -.165382, .479461, .138286, .264637, -.176806, .492106, .15666, .284959, -.188793, .504774, .17728, .308157, -.200763, .518805, .19988, .330951, -.21239, .528231, .224293, .3549, -.223521, .536376, .250541, .381502, -.234169, .544846, .278902, .409529, -.244077, .551717, .309227, .437523, -.253363, .55517, .341426, .467624, -.261659, .557772, .37518, .497268, -.268498, .556442, .41007, .528294, -.274018, .553915, .446445, .559053, -.278169, .549153, .483779, .589329, -.281229, .539878, .522249, .622503, -.282902, .53162, .561754, .652382, -.282815, .518119, .601544, .681847, -.281247, .502187, .641574, .712285, -.277986, .484824, .682633, .740094, -.273017, .463483, .723426, .768478, -.266692, .441299, .763747, .794556, -.258358, .415238, .805565, .819408, -.248807, .386912, .847254, .843411, -.236214, .356165, .891091, .862397, -.219794, .320562, .936174, .883113, -.201768, .285322, .982562, .90023, -.181672, .249713, 1.02862, .915192, -.159279, .214546, 1.07163, .928458, -.134725, .180285, 1.10995, .94069, -.10913, .147119, 1.14354, .953409, -.0821315, .112492, 1.17372, .969537, -.0542677, .0752014, 1.20043, .985612, -.0259096, .0370361, 1.22528, .999835, .00298198, -.00151801, 1.24959, .10097, -602574e-11, .300277, 202619e-11, .101577, -152164e-9, .302077, 511662e-10, .101572, -608889e-9, .302066, 204751e-9, .101566, -.00136997, .302047, 460753e-9, .101592, -.00243557, .302114, 819497e-9, .101608, -.0038053, .30214, .00128154, .101627, -.00547906, .30216, .0018483, .101669, -.00745647, .302224, .00252223, .101732, -.00973615, .302318, .00330716, .101844, -.0123097, .302513, .00421061, .102025, -.0151681, .30285, .00524481, .102224, -.0183334, .303166, .0064154, .102515, -.0217819, .303654, .00774063, .102886, -.0255067, .304243, .0092398, .103395, -.029514, .305089, .0109339, .104109, -.0337912, .306301, .0128561, .105074, -.0383565, .30798, .0150338, .10654, -.0432132, .310726, .0175228, .108478, -.0484244, .314351, .0203648, .111015, -.0539339, .319032, .0236325, .114682, -.0598885, .32605, .0274188, .11911, -.0663375, .334109, .0317905, .124736, -.0733011, .344013, .0368502, .131479, -.0807744, .355358, .0427104, .139283, -.0888204, .367614, .0494788, .148054, -.0973394, .380072, .0572367, .159037, -.10665, .395678, .0662704, .169794, -.116221, .40795, .0763192, .18314, -.126632, .423546, .087956, .197515, -.137383, .438213, .101042, .213514, -.148641, .453248, .115827, .23065, -.160117, .46688, .132283, .249148, -.171807, .479962, .150644, .270219, -.183695, .494618, .171073, .292338, -.195574, .506937, .193378, .314999, -.207205, .516463, .217585, .340991, -.218955, .528123, .24428, .367982, -.229917, .537025, .272784, .39432, -.239737, .541627, .302742, .423364, -.249048, .546466, .335112, .453751, -.257329, .549466, .369032, .48416, -.264623, .549503, .404577, .515262, -.270411, .547008, .441337, .547036, -.274581, .542249, .479162, .576614, -.277266, .533015, .517904, .611143, -.279144, .525512, .558508, .640989, -.279001, .51154, .598995, .671182, -.277324, .495641, .639935, .700848, -.273908, .477526, .681017, .729862, -.269063, .457955, .722764, .758273, -.262282, .434846, .764349, .784121, -.254281, .409203, .806206, .809798, -.24505, .382694, .848617, .834953, -.233861, .354034, .892445, .856817, -.221308, .321764, .936263, .877609, -.205996, .288118, .982401, .897489, -.186702, .253277, 1.02975, .913792, -.164618, .217963, 1.07488, .92785, -.140023, .183221, 1.11487, .940378, -.11328, .149385, 1.14947, .95273, -.0853958, .114152, 1.1807, .969059, -.0568698, .0769845, 1.20912, .985574, -.0276502, .0381186, 1.23498, .999943, .00239052, -.00126861, 1.25987, .0852715, -560067e-11, .279021, 171162e-11, .0854143, -140871e-9, .279483, 430516e-10, .0854191, -563385e-9, .2795, 172184e-9, .0854188, -.00126753, .279493, 387464e-9, .0854229, -.00225337, .279501, 68918e-8, .0854443, -.00352086, .279549, .00107803, .0854697, -.00506962, .279591, .00155536, .0855093, -.00689873, .279652, .00212354, .0855724, -.00900821, .279752, .00278703, .0856991, -.0113799, .280011, .0035551, .085855, -.0140314, .280297, .00443449, .0860682, -.016963, .280682, .00543636, .086344, -.0201438, .281159, .0065788, .0867426, -.0235999, .281886, .00787977, .087239, -.0273069, .282745, .0093606, .0879815, -.031269, .284139, .011056, .0891258, -.035531, .28647, .0130065, .0906909, -.0400947, .289708, .0152495, .0927624, -.0449638, .293904, .0178454, .0958376, -.0502427, .300471, .0208915, .0995827, -.0559514, .30806, .0244247, .104526, -.0622152, .317874, .0285721, .110532, -.0690046, .329332, .0334227, .117385, -.0763068, .341217, .0390466, .12522, -.084184, .353968, .0455786, .134037, -.0925248, .366797, .0530773, .144014, -.101487, .380209, .0617424, .156013, -.111273, .395956, .071777, .168872, -.121431, .41053, .0830905, .183089, -.132105, .425073, .0959341, .198763, -.143286, .439833, .110448, .216159, -.154841, .454507, .126769, .234859, -.166588, .468368, .14495, .255879, -.178626, .482846, .165233, .27677, -.190218, .493489, .187217, .301184, -.202227, .506549, .211659, .325852, -.213764, .5158, .237922, .352824, -.22487, .525442, .26632, .380882, -.235246, .532487, .296691, .410137, -.244847, .537703, .329179, .439787, -.253122, .540361, .363135, .472291, -.260517, .542734, .399222, .501856, -.266519, .538826, .436352, .534816, -.270905, .535152, .474505, .565069, -.273826, .525979, .513988, .597154, -.275333, .516394, .554852, .630473, -.275314, .506206, .596592, .660574, -.273323, .489769, .638117, .692015, -.270008, .472578, .680457, .720647, -.265001, .452134, .723008, .750528, -.258311, .430344, .765954, .777568, -.250046, .405624, .809012, .80387, -.240114, .378339, .852425, .828439, -.228737, .349877, .895346, .851472, -.216632, .318968, .940695, .873906, -.202782, .287489, .987235, .89467, -.187059, .254394, 1.03348, .912281, -.168818, .221294, 1.07812, .927358, -.146494, .18675, 1.11928, .940385, -.120009, .152322, 1.15609, .952672, -.0917183, .117514, 1.18875, .968496, -.0620321, .0797405, 1.21821, .985236, -.0314945, .0402383, 1.24523, .99998, -575153e-9, 110644e-9, 1.27133, .0702429, -512222e-11, .255273, 140947e-11, .0702981, -128826e-9, .255469, 354488e-10, .0703691, -515562e-9, .255727, 141874e-9, .0703805, -.00116, .255754, 31929e-8, .0703961, -.00206224, .255813, 567999e-9, .0704102, -.00322223, .255839, 88871e-8, .0704298, -.00463928, .255863, .00128272, .0704759, -.00631375, .255953, .00175283, .0705434, -.00824317, .256079, .00230342, .0706693, -.010412, .25636, .0029443, .0708189, -.0128439, .256647, .00368031, .0710364, -.0155177, .257084, .00452614, .0713223, -.0184374, .257637, .00549706, .0717182, -.0216002, .258416, .00661246, .072321, -.0249966, .259699, .00790147, .0731446, -.0286566, .261475, .0093884, .0743352, -.0325888, .264132, .0111186, .0760676, -.036843, .26815, .013145, .078454, -.0414292, .273636, .0155251, .0818618, -.0464634, .281653, .0183525, .0857382, -.0519478, .289992, .0216642, .0908131, -.0579836, .30066, .0255956, .0967512, -.0645124, .312204, .0301954, .103717, -.0716505, .325001, .0356017, .111596, -.0793232, .338129, .041896, .120933, -.087645, .352853, .0492447, .130787, -.096492, .366192, .0576749, .142311, -.105973, .380864, .0673969, .155344, -.116182, .396575, .0785899, .169535, -.126815, .411443, .0912377, .185173, -.138015, .426256, .105607, .201755, -.149325, .439607, .121551, .221334, -.161207, .455467, .139608, .241461, -.173162, .469096, .159591, .26294, -.18504, .481014, .18156, .286776, -.196881, .493291, .205781, .311596, -.208311, .503556, .231819, .338667, -.219671, .513268, .260274, .366021, -.230451, .519414, .290862, .395875, -.240131, .526766, .323196, .425564, -.248566, .52905, .357071, .457094, -.256195, .530796, .393262, .488286, -.262331, .528703, .430797, .522291, -.267141, .52727, .470231, .554172, -.270411, .519848, .510477, .586427, -.271986, .510307, .551594, .619638, -.27192, .499158, .593849, .650656, -.269817, .483852, .636314, .68284, -.266267, .467515, .679679, .714356, -.26113, .44931, .723884, .742717, -.254067, .425789, .767245, .770894, -.245652, .401144, .811819, .797358, -.235554, .374224, .856315, .823377, -.223896, .346167, .901077, .847456, -.210865, .316056, .946502, .870697, -.196574, .284503, .993711, .891068, -.180814, .251628, 1.04134, .909267, -.163314, .219065, 1.08609, .925653, -.143304, .186446, 1.12702, .940017, -.121322, .153416, 1.16371, .952398, -.0973872, .120334, 1.19712, .967568, -.0698785, .08352, 1.22791, .984772, -.0390031, .0439209, 1.25672, 1.00026, -.0070087, .00315668, 1.28428, .0556653, -459654e-11, .227325, 112556e-11, .0565238, -116382e-9, .230826, 284985e-10, .0565717, -465666e-9, .231026, 114036e-9, .0565859, -.00104773, .231079, 256656e-9, .0565761, -.00186255, .231025, 45663e-8, .0565913, -.00291002, .231058, 714664e-9, .0566108, -.00418998, .231085, .00103224, .0566532, -.00570206, .231169, .00141202, .0567473, -.00743666, .231417, .00186018, .0568567, -.00940298, .231661, .00238264, .0569859, -.0115991, .231895, .00298699, .0572221, -.0140096, .232456, .00368957, .057519, -.0166508, .233096, .00450303, .0579534, -.01951, .234094, .00544945, .0585922, -.0225991, .235629, .00655564, .0595647, -.0259416, .238106, .00785724, .0609109, -.0295661, .241557, .00939127, .0628751, -.0335126, .246652, .0112198, .0656908, -.0378604, .254091, .0134168, .0691347, -.0426543, .262666, .0160374, .0732165, -.0478967, .272029, .0191514, .0782863, -.0536716, .283007, .0228597, .0843973, -.0600683, .295732, .0272829, .0913598, -.0670095, .308779, .032484, .0994407, -.0745516, .322886, .0385886, .108189, -.082712, .336408, .0457133, .118574, -.0914927, .351692, .0539832, .129989, -.100854, .366502, .0635162, .142722, -.110837, .381675, .0744386, .156654, -.121353, .3963, .0868483, .172151, -.132414, .411477, .100963, .188712, -.143809, .42508, .116795, .208093, -.155765, .441328, .134715, .227936, -.167608, .454328, .154396, .249495, -.179579, .467235, .176179, .27362, -.191488, .480248, .200193, .296371, -.202618, .487886, .225775, .324234, -.214133, .499632, .25441, .353049, -.225212, .509532, .285077, .381785, -.234875, .514265, .317047, .414038, -.244205, .521282, .351874, .445251, -.252145, .522931, .388279, .476819, -.258433, .520947, .425825, .509209, -.263411, .517669, .465104, .542759, -.266732, .512841, .505741, .574822, -.268263, .503317, .547611, .609324, -.268489, .493035, .590953, .641772, -.266941, .478816, .63488, .674049, -.263297, .462863, .679072, .705071, -.257618, .442931, .723487, .734709, -.250625, .421299, .768708, .763704, -.24179, .397085, .814375, .791818, -.231115, .370577, .859907, .817439, -.21922, .34232, .906715, .843202, -.205658, .312627, .953943, .866639, -.190563, .280933, 1.00185, .888129, -.173978, .248393, 1.05105, .907239, -.155485, .216007, 1.09704, .923893, -.134782, .183233, 1.13857, .938882, -.11249, .150376, 1.17539, .952464, -.0890706, .117177, 1.20924, .968529, -.0646523, .0813095, 1.24055, .984763, -.038606, .0439378, 1.27018, 1.00053, -.01238, .00598668, 1.29873, .0437928, -409594e-11, .204012, 8.79224e-7, .0440166, -103395e-9, .205049, 221946e-10, .0440529, -413633e-9, .205225, 887981e-10, .0440493, -930594e-9, .2052, 199858e-9, .0439884, -.00165352, .204901, 355495e-9, .0440716, -.0025849, .205255, 556983e-9, .0440968, -.00372222, .205311, 805326e-9, .0441359, -.00506478, .205391, .00110333, .0442231, -.00660384, .205638, .00145768, .0443254, -.00835246, .205877, .00187275, .0444832, -.0102992, .20627, .00235938, .0447001, -.0124449, .206796, .0029299, .0450168, -.0147935, .207593, .0036005, .0454816, -.017336, .208819, .00439246, .0462446, -.0201156, .211036, .00533864, .0473694, -.0231568, .214388, .00646984, .0490191, -.0264941, .219357, .00783856, .0512776, -.030184, .226061, .00950182, .0541279, -.0342661, .234094, .0115156, .0578989, -.0388539, .244297, .0139687, .0620835, -.0438735, .254457, .0169015, .0673497, -.04951, .266706, .0204554, .0731759, -.0556263, .278753, .0246606, .0803937, -.0624585, .29309, .0297126, .0879287, -.0697556, .305856, .0355868, .0970669, -.0778795, .321059, .0425768, .106508, -.0863541, .333873, .05056, .11776, -.0955935, .349008, .0598972, .130081, -.105438, .363776, .0706314, .144454, -.115899, .380112, .0828822, .1596, -.126827, .394843, .0967611, .176097, -.138161, .409033, .112381, .194726, -.149904, .424257, .129952, .213944, -.161675, .436945, .149333, .235516, -.173659, .450176, .170892, .260564, -.185963, .466305, .194984, .285183, -.197582, .477328, .220805, .311095, -.208697, .486566, .248694, .338924, -.219519, .494811, .279015, .369757, -.229766, .504065, .311725, .3996, -.238879, .507909, .345844, .430484, -.246802, .509805, .381749, .46413, -.253924, .511436, .420251, .497077, -.259319, .508787, .459957, .530434, -.263297, .50394, .501356, .565725, -.265619, .49804, .544252, .599254, -.265842, .487346, .587856, .631251, -.263978, .472975, .631969, .663972, -.26043, .457135, .677471, .697724, -.255358, .439844, .723744, .727725, -.248308, .417872, .770653, .756417, -.239181, .39273, .817357, .785419, -.22814, .367839, .864221, .81266, -.215681, .339449, .912701, .839391, -.201623, .309279, .962419, .86366, -.185624, .278029, 1.0122, .885028, -.16797, .245294, 1.06186, .904639, -.148336, .212689, 1.10934, .922048, -.12637, .179616, 1.15063, .936952, -.102928, .146749, 1.18885, .951895, -.0785268, .112733, 1.22352, .967198, -.0530153, .0760056, 1.25681, .984405, -.02649, .0383183, 1.28762, 1.00021, 70019e-8, -20039e-8, 1.31656, .0325964, -355447e-11, .176706, 6.55682e-7, .0329333, -899174e-10, .178527, 165869e-10, .0329181, -359637e-9, .178453, 663498e-10, .0329085, -808991e-9, .178383, 149332e-9, .0329181, -.00143826, .178394, 265873e-9, .0329425, -.00224678, .178517, 416597e-9, .0329511, -.00323575, .17849, 603299e-9, .033011, -.00439875, .178695, 829422e-9, .0330733, -.00574059, .178843, .00109908, .0331857, -.00725896, .179176, .00141933, .0333445, -.00895289, .179618, .0017999, .0335674, -.0108219, .180238, .00225316, .033939, -.0128687, .181417, .00279765, .0345239, -.015114, .183395, .0034564, .0354458, -.017596, .186616, .00425864, .0368313, -.0203524, .191547, .00524936, .0386115, -.0234105, .197508, .00647033, .0410303, -.0268509, .205395, .00798121, .0442245, -.0307481, .215365, .0098557, .0478659, -.0350863, .225595, .0121417, .0522416, -.0399506, .236946, .0149385, .0574513, -.045357, .249442, .0183189, .0631208, -.0512863, .261222, .0223644, .0701124, -.0579273, .275418, .0272418, .0777331, -.0650652, .288989, .0329458, .0862709, -.0728813, .302546, .0396819, .096103, -.081363, .317164, .04757, .106976, -.0904463, .331733, .0567012, .119175, -.100105, .34661, .067202, .132919, -.110375, .362249, .0792588, .147727, -.121115, .376978, .0928672, .163618, -.132299, .390681, .108228, .182234, -.143887, .406571, .125502, .201809, -.155827, .42042, .144836, .225041, -.168357, .438411, .166706, .247621, -.18004, .450368, .189909, .27097, -.191536, .460083, .215251, .296658, -.203024, .469765, .243164, .325892, -.214056, .481837, .273388, .35406, -.224104, .487474, .305344, .384372, -.233489, .492773, .339741, .41749, -.241874, .498451, .376287, .45013, -.248834, .499632, .414195, .481285, -.254658, .495233, .454077, .519183, -.259367, .496401, .496352, .551544, -.261818, .487686, .538798, .587349, -.262964, .479453, .583626, .621679, -.262128, .467709, .629451, .654991, -.258998, .452123, .67566, .686873, -.254119, .433495, .723248, .719801, -.246946, .413657, .771156, .750355, -.237709, .390366, .81989, .780033, -.226549, .364947, .868601, .809254, -.214186, .337256, .920034, .836576, -.199639, .307395, .971706, .861774, -.183169, .275431, 1.02479, .885707, -.165111, .243431, 1.07837, .904742, -.144363, .210921, 1.12783, .915604, -.121305, .17647, 1.17254, .930959, -.0962119, .143106, 1.21012, .948404, -.069969, .108112, 1.24474, .967012, -.0427586, .0708478, 1.27718, .984183, -.0147043, .032335, 1.3083, .999577, .0142165, -.00726867, 1.3382, .0229227, -299799e-11, .148623, 4.62391e-7, .0232194, -758796e-10, .15054, 117033e-10, .0232315, -303636e-9, .15063, 468397e-10, .0232354, -683189e-9, .150624, 105472e-9, .0232092, -.0012136, .150445, 187744e-9, .0232523, -.00189765, .150679, 294847e-9, .0232828, -.00273247, .150789, 428013e-9, .0233371, -.00371287, .150995, 591134e-9, .0234015, -.00484794, .15118, 787642e-9, .023514, -.00612877, .151562, .00102547, .023679, -.00756125, .152116, .00131351, .0239559, -.00914651, .153162, .00166594, .0244334, -.010904, .155133, .00210182, .025139, -.0128615, .158035, .00264406, .0262598, -.0150628, .162751, .00332923, .0277875, -.0175532, .168944, .00419773, .0298472, -.0203981, .176835, .00530034, .0325444, -.023655, .186686, .00669777, .0355581, -.0272982, .196248, .00842661, .0392841, -.0314457, .207352, .0105854, .0436815, -.0361157, .219279, .0132458, .0485272, -.0412932, .230728, .0164736, .0541574, -.0470337, .242994, .0203715, .0609479, -.0535002, .257042, .0250953, .0685228, -.0605409, .27102, .0306856, .0768042, -.0680553, .28406, .037193, .0864844, -.0765011, .299186, .0449795, .0969415, -.0852674, .3132, .0538316, .108478, -.0947333, .327138, .0641149, .121705, -.10481, .342345, .0759185, .136743, -.115474, .358472, .0894116, .152986, -.126536, .374067, .104562, .170397, -.138061, .388267, .121632, .191392, -.150203, .406467, .140996, .211566, -.161751, .418641, .161696, .233567, -.173407, .430418, .184557, .257769, -.185397, .44277, .210092, .28531, -.197048, .457191, .237827, .311726, -.20784, .464712, .267253, .340537, -.218345, .472539, .299332, .372921, -.228306, .482331, .333988, .402924, -.236665, .484378, .369722, .434475, -.244097, .484717, .407836, .469736, -.250547, .487093, .448465, .505045, -.25511, .485575, .490263, .540262, -.258444, .481225, .534495, .576347, -.259903, .473481, .579451, .608656, -.259572, .4603, .625604, .646679, -.257908, .450341, .674511, .679902, -.253663, .431561, .723269, .714159, -.247419, .412684, .773263, .745345, -.239122, .389388, .824182, .778248, -.228837, .365361, .876634, .807208, -.216197, .337667, .92945, .835019, -.201772, .307197, .985261, .860261, -.185291, .274205, 1.04299, .877601, -.165809, .240178, 1.09816, .898211, -.143897, .207571, 1.14694, .915789, -.119513, .174904, 1.19008, .931831, -.0932919, .141423, 1.2297, .949244, -.0656528, .105603, 1.26553, .967527, -.0370262, .0679551, 1.29986, .984139, -.00730117, .0283133, 1.33252, .999713, .0234648, -.0121785, 1.36397, .0152135, -245447e-11, .122795, 3.04092e-7, .0151652, -615778e-10, .122399, 76292e-10, .0151181, -245948e-9, .122023, 304802e-10, .0151203, -553394e-9, .12203, 686634e-10, .015125, -983841e-9, .122037, 122463e-9, .0151427, -.00153774, .12214, 192706e-9, .0151708, -.0022103, .122237, 281219e-9, .0152115, -.00300741, .12238, 390804e-9, .0152877, -.00392494, .1227, 526317e-9, .015412, -.00496597, .123244, 69443e-8, .0156201, -.00613314, .124228, 90547e-8, .0159658, -.00744113, .125945, .0011732, .0165674, -.00892546, .129098, .00151888, .017487, -.010627, .133865, .00197007, .018839, -.0126043, .140682, .0025637, .020554, -.0148814, .148534, .00333637, .0226727, -.0175123, .157381, .00433738, .0251879, -.0205266, .166685, .00561664, .0283635, -.0240319, .177796, .00725563, .0318694, -.0279432, .188251, .00928811, .0361044, -.0324313, .200038, .011835, .0406656, -.0373527, .210685, .0149146, .0463846, -.0430132, .224182, .0187254, .0525696, -.0491013, .23634, .0232283, .0598083, -.0559175, .250013, .0286521, .0679437, -.0633657, .263981, .0350634, .0771181, -.0714602, .278072, .0425882, .0881273, -.0803502, .29511, .0514487, .0996628, -.0896903, .309976, .0615766, .112702, -.099644, .325611, .0732139, .126488, -.109829, .339321, .0862324, .142625, -.120859, .35574, .101275, .15953, -.131956, .369845, .117892, .176991, -.143145, .38146, .136205, .199715, -.155292, .40052, .157252, .220787, -.167066, .412055, .179966, .243697, -.178396, .423133, .204418, .272106, -.190433, .439524, .232141, .297637, -.201265, .447041, .261109, .325273, -.211834, .454488, .292627, .357219, -.221889, .465004, .326669, .387362, -.230729, .468527, .362426, .423131, -.23924, .475836, .401533, .45543, -.246067, .475017, .441902, .493393, -.251557, .478017, .484239, .526253, -.255571, .4709, .528586, .560554, -.257752, .463167, .574346, .599306, -.258076, .456452, .621655, .634541, -.256471, .443725, .670492, .668907, -.253283, .428719, .721943, .705619, -.247562, .411348, .772477, .739034, -.240626, .388939, .8264, .771408, -.231493, .36425, .881702, .803312, -.220125, .337321, .9385, .828457, -.206645, .305364, .997437, .854819, -.190664, .273715, 1.05693, .878666, -.171429, .242218, 1.11251, .898404, -.149235, .209556, 1.16398, .917416, -.12435, .176863, 1.21014, .933133, -.0972703, .142775, 1.25178, .95066, -.0683607, .106735, 1.29028, .968589, -.0378724, .0681609, 1.32703, .984776, -.00605712, .0273966, 1.36158, .99994, .0263276, -.0138124, 1.3943, .00867437, -186005e-11, .0928979, 1.73682e-7, .00864003, -466389e-10, .0925237, 435505e-11, .00864593, -186594e-9, .0925806, 174322e-10, .00864095, -419639e-9, .0924903, 392862e-10, .00863851, -746272e-9, .0924589, 702598e-10, .00868531, -.00116456, .0929, 111188e-9, .00869667, -.00167711, .0928529, 163867e-9, .00874332, -.00228051, .0930914, 23104e-8, .00882709, -.00297864, .0935679, 31741e-8, .00898874, -.00377557, .0946165, 430186e-9, .00929346, -.00469247, .0967406, 580383e-9, .00978271, -.00575491, .100084, 783529e-9, .0105746, -.00701514, .105447, .00106304, .0116949, -.00851797, .112494, .00144685, .0130419, -.0102757, .119876, .00196439, .0148375, -.012381, .129034, .00266433, .0168725, -.01482, .137812, .00358364, .0193689, -.0176563, .147696, .00478132, .0222691, -.0209211, .157795, .00631721, .0256891, -.0246655, .168431, .00826346, .0294686, -.0288597, .178587, .0106714, .0340412, -.0336441, .190251, .0136629, .0393918, -.039033, .202999, .0173272, .0453947, -.0450087, .215655, .0217448, .0521936, -.0515461, .228686, .0269941, .0600279, -.058817, .242838, .033272, .0692398, -.0667228, .258145, .0406457, .0793832, -.0752401, .273565, .0492239, .0902297, -.0841851, .287735, .0590105, .102014, -.0936479, .301161, .0702021, .116054, -.103967, .317438, .0832001, .13191, -.114622, .334166, .0977951, .148239, -.125452, .348192, .113985, .165809, -.136453, .361094, .131928, .184616, -.147648, .373534, .151811, .207491, -.159607, .39101, .174476, .230106, -.171119, .402504, .198798, .257036, -.182906, .418032, .225796, .281172, -.193605, .425468, .254027, .312034, -.204771, .440379, .285713, .340402, -.214988, .445406, .319196, .370231, -.224711, .44968, .35537, .407105, -.233516, .460747, .393838, .439037, -.240801, .460624, .433747, .47781, -.24762, .465957, .477234, .510655, -.251823, .460054, .52044, .550584, -.255552, .459172, .567853, .585872, -.257036, .450311, .615943, .620466, -.257535, .437763, .667693, .660496, -.255248, .426639, .718988, .695578, -.251141, .409185, .772503, .732176, -.244718, .39015, .827023, .760782, -.236782, .362594, .885651, .79422, -.225923, .33711, .943756, .824521, -.213855, .308272, 1.00874, .854964, -.197723, .278529, 1.06764, .878065, -.179209, .246208, 1.12836, .899834, -.157569, .21329, 1.18318, .918815, -.133206, .181038, 1.23161, .934934, -.106545, .146993, 1.27644, .952115, -.0780574, .111175, 1.31842, .96906, -.0478279, .0728553, 1.35839, .985178, -.0160014, .032579, 1.39697, 1.00039, .0173126, -.0095256, 1.43312, .00384146, -124311e-11, .0613583, 7.78271e-8, .00390023, -314043e-10, .0622919, 196626e-11, .00389971, -125622e-9, .0622632, 787379e-11, .00389491, -282352e-9, .0620659, 1778e-8, .00391618, -502512e-9, .0624687, 320918e-10, .00392662, -784458e-9, .0625113, 515573e-10, .00396053, -.00112907, .0628175, 778668e-10, .00401911, -.00153821, .0633286, 113811e-9, .00414994, -.0020208, .0646443, 16445e-8, .00441223, -.00260007, .0673886, 237734e-9, .00484427, -.0033097, .0716528, 345929e-9, .00549109, -.00418966, .0774998, 505987e-9, .00636293, -.00527331, .0844758, 739208e-9, .00746566, -.00660428, .0921325, .00107347, .00876625, -.00818826, .0997067, .00153691, .0103125, -.0100811, .107433, .00217153, .0123309, -.0123643, .117088, .00303427, .0146274, -.0150007, .126438, .00416018, .0172295, -.0180531, .135672, .00561513, .0204248, -.0215962, .146244, .007478, .0241597, -.0256234, .157481, .00981046, .0284693, -.0302209, .169125, .0127148, .033445, -.0353333, .181659, .0162453, .0391251, -.0410845, .1944, .0205417, .0454721, -.0473451, .207082, .0256333, .0530983, -.0542858, .221656, .0317036, .0615356, -.0618384, .236036, .0388319, .0703363, -.0697631, .248398, .046974, .0810391, -.0784757, .263611, .0565246, .0920144, -.0873488, .275857, .0671724, .105584, -.0973652, .292555, .0798105, .119506, -.107271, .306333, .0935945, .134434, -.117608, .318888, .109106, .153399, -.128938, .337552, .127074, .171258, -.139944, .349955, .14643, .191059, -.151288, .361545, .168, .215069, -.163018, .378421, .192082, .237838, -.174226, .38879, .217838, .266965, -.186063, .405857, .246931, .292827, -.196909, .414146, .277505, .324352, -.207473, .426955, .310711, .354427, -.217713, .433429, .346794, .389854, -.227183, .443966, .385237, .420749, -.235131, .44471, .424955, .459597, -.242786, .451729, .468446, .495316, -.248767, .45072, .513422, .534903, -.253351, .450924, .560618, .572369, -.256277, .445266, .609677, .612383, -.2576, .438798, .660995, .644037, -.256931, .421693, .713807, .686749, -.254036, .4109, .767616, .719814, -.249785, .390151, .82533, .754719, -.244283, .367847, .888311, .792022, -.235076, .345013, .948177, .822404, -.225061, .316193, 1.01661, .853084, -.211113, .287013, 1.08075, .879871, -.19449, .255424, 1.14501, .901655, -.174023, .222879, 1.20203, .919957, -.1509, .18989, 1.25698, .938412, -.124923, .15606, 1.30588, .953471, -.0968139, .120512, 1.3529, .970451, -.066734, .0828515, 1.3986, .985522, -.034734, .0424458, 1.44148, 1.00099, -.00102222, 678929e-9, 1.48398, 965494e-9, -6.27338e-7, .0306409, 1.97672e-8, 99168e-8, -158573e-10, .0314638, 4.99803e-7, 991068e-9, -634012e-10, .031363, 200682e-11, 974567e-9, -14144e-8, .03036, 457312e-11, 998079e-9, -252812e-9, .031496, 860131e-11, .00102243, -396506e-9, .0319955, 148288e-10, .00107877, -577593e-9, .0331376, 249141e-10, .00121622, -816816e-9, .0359396, 423011e-10, .0014455, -.00113761, .0399652, 724613e-10, .00178791, -.00156959, .0450556, 123929e-9, .00225668, -.00214064, .0508025, 208531e-9, .00285627, -.00287655, .0568443, 341969e-9, .0035991, -.00380271, .0630892, 544158e-9, .00455524, -.00496264, .0702204, 842423e-9, .00569143, -.0063793, .0773426, .00126704, .00716928, -.00813531, .0860839, .00186642, .00885307, -.0101946, .0944079, .00267014, .0109316, -.0126386, .103951, .00374033, .0133704, -.0154876, .113786, .0051304, .0161525, -.0187317, .123477, .00688858, .0194267, -.0224652, .133986, .00910557, .0230967, -.0265976, .143979, .0118074, .0273627, -.0312848, .154645, .0151266, .0323898, -.0365949, .166765, .0191791, .0379225, -.0422914, .177932, .0239236, .0447501, -.0487469, .19167, .0296568, .0519391, -.0556398, .203224, .0362924, .0599464, -.0631646, .215652, .0440585, .0702427, -.0714308, .232089, .0531619, .0806902, -.0800605, .245258, .0634564, .0923194, -.0892815, .258609, .0752481, .106938, -.09931, .276654, .0888914, .121238, -.109575, .289847, .104055, .138817, -.120461, .307566, .121266, .15595, -.131209, .320117, .139944, .178418, -.143049, .339677, .161591, .197875, -.154074, .349886, .184303, .224368, -.166307, .369352, .210669, .252213, -.178051, .386242, .238895, .277321, -.189335, .395294, .269182, .310332, -.200683, .412148, .302508, .338809, -.210856, .418266, .337264, .372678, -.220655, .428723, .374881, .405632, -.230053, .433887, .415656, .442293, -.237993, .439911, .457982, .477256, -.244897, .440175, .502831, .515592, -.250657, .441079, .550277, .550969, -.255459, .435219, .601102, .592883, -.257696, .432882, .651785, .629092, -.259894, .421054, .708961, .672033, -.258592, .41177, .763806, .709147, -.256525, .395267, .824249, .745367, -.254677, .375013, .8951, .784715, -.247892, .353906, .959317, .818107, -.240162, .327801, 1.03153, .847895, -.229741, .298821, 1.10601, .879603, -.213084, .269115, 1.164, .902605, -.195242, .236606, 1.22854, .922788, -.174505, .203442, 1.29017, .944831, -.150169, .169594, 1.34157, .959656, -.124099, .135909, 1.3956, .972399, -.0960626, .0990563, 1.45128, .986549, -.0657097, .0602348, 1.50312, 1.00013, -.0333558, .0186694, 1.55364, 619747e-11, -1e-7, .00778326, 796756e-16, 2.37499e-8, -9.99999e-8, 282592e-10, 114596e-15, 100292e-11, -166369e-11, 250354e-9, 6.77492e-9, 350752e-11, -637769e-11, 357289e-9, 6.31655e-8, 826445e-11, -174689e-10, 516179e-9, 3.1851e-7, 242481e-10, -450868e-10, .0010223, 130577e-11, 455631e-10, -89044e-9, .00144302, 374587e-11, 971222e-10, -178311e-9, .00241912, 102584e-10, 171403e-9, -313976e-9, .00354938, 236481e-10, 292747e-9, -520026e-9, .00513765, 496014e-10, 789827e-9, -.00118187, .0238621, 139056e-9, .00114093, -.00171827, .0286691, 244093e-9, .00176119, -.00249667, .0368565, 420623e-9, .0022233, -.00333742, .0400469, 65673e-8, .00343382, -.00481976, .0535751, .00109323, .00427602, -.00600755, .057099, .00155268, .00461435, -.00737637, .0551084, .00215031, .00695698, -.00971401, .0715767, .00316529, .00867619, -.0120943, .0793314, .00436995, .0106694, -.0148202, .0869391, .0058959, .0140351, -.0183501, .101572, .00798757, .0168939, -.022006, .11018, .0104233, .020197, -.0261568, .119041, .0134167, .0254702, -.0312778, .135404, .0173009, .0298384, -.0362469, .1437, .0215428, .035159, -.042237, .15512, .0268882, .0427685, -.0488711, .17128, .033235, .0494848, -.0557997, .181813, .0404443, .0592394, -.0635578, .198745, .0490043, .0681463, -.071838, .210497, .0588239, .0804753, -.0809297, .228864, .0702835, .0942205, -.0906488, .247008, .0834012, .106777, -.100216, .258812, .0975952, .124471, -.110827, .278617, .114162, .138389, -.121193, .287049, .131983, .159543, -.13253, .307151, .152541, .176432, -.143611, .31564, .174673, .201723, -.15548, .33538, .199842, .229721, -.167166, .355256, .227097, .250206, -.178238, .360047, .256014, .282118, -.189905, .378761, .28855, .312821, -.201033, .39181, .323348, .341482, -.211584, .397716, .360564, .377368, -.221314, .410141, .400004, .418229, -.230474, .423485, .442371, .444881, -.239443, .418874, .488796, .488899, -.245987, .427545, .535012, .520317, -.253948, .422147, .589678, .568566, -.256616, .42719, .637683, .599607, -.26376, .415114, .703363, .64222, -.268687, .408715, .771363, .685698, -.2694, .399722, .83574, .732327, -.266642, .388651, .897764, .769873, -.267712, .369198, .983312, .806733, -.263479, .346802, 1.06222, .843466, -.254575, .321368, 1.13477, .873008, -.242749, .29211, 1.20712, .908438, -.22725, .262143, 1.27465, .936321, -.207621, .228876, 1.33203, .950353, -.187932, .19484, 1.40439, .96442, -.165154, .163178, 1.4732, .979856, -.139302, .127531, 1.53574, .982561, -.11134, .0903457, 1.59982, .996389, -.0808124, .0489007, 1.6577 ]; const LTC_MAT_2 = [ 1, 0, 0, 0, 1, 791421e-36, 0, 0, 1, 104392e-29, 0, 0, 1, 349405e-26, 0, 0, 1, 109923e-23, 0, 0, 1, 947414e-22, 0, 0, 1, 359627e-20, 0, 0, 1, 772053e-19, 0, 0, 1, 108799e-17, 0, 0, 1, 110655e-16, 0, 0, 1, 865818e-16, 0, 0, .999998, 545037e-15, 0, 0, .999994, 2.85095e-9, 0, 0, .999989, 1.26931e-8, 0, 0, .999973, 4.89938e-8, 0, 0, .999947, 1.66347e-7, 0, 0, .999894, 5.02694e-7, 0, 0, .999798, 136532e-11, 0, 0, .999617, 335898e-11, 0, 0, .999234, 752126e-11, 0, 0, .998258, 152586e-10, 0, 0, .99504, 266207e-10, 0, 0, .980816, 236802e-10, 0, 0, .967553, 207684e-11, 0, 0, .966877, 403733e-11, 0, 0, .965752, 741174e-11, 0, 0, .96382, 127746e-10, 0, 0, .960306, 202792e-10, 0, 0, .953619, 280232e-10, 0, 0, .941103, 278816e-10, 0, 0, .926619, 160221e-10, 0, 0, .920983, 235164e-10, 0, 0, .912293, 311924e-10, 0, .0158731, .899277, 348118e-10, 0, .0476191, .880884, 26041e-9, 0, .0793651, .870399, 338726e-10, 0, .111111, .856138, 392906e-10, 0, .142857, .837436, 372874e-10, 0, .174603, .820973, 392558e-10, 0, .206349, .803583, 434658e-10, 0, .238095, .782168, 40256e-9, 0, .269841, .764107, 448159e-10, 0, .301587, .743092, 457627e-10, 0, .333333, .721626, 455314e-10, 0, .365079, .700375, 477335e-10, 0, .396825, .677334, 461072e-10, 0, .428571, .655702, 484393e-10, 0, .460317, .632059, 464583e-10, 0, .492064, .610125, 483923e-10, 0, .52381, .58653, 464342e-10, 0, .555556, .564508, 477033e-10, 0, .587302, .541405, 459263e-10, 0, .619048, .519556, 46412e-9, 0, .650794, .497292, 448913e-10, 0, .68254, .475898, 445789e-10, 0, .714286, .454722, 433496e-10, 0, .746032, .434042, 423054e-10, 0, .777778, .414126, 413737e-10, 0, .809524, .394387, 397265e-10, 0, .84127, .375841, 390709e-10, 0, .873016, .357219, 369938e-10, 0, .904762, .340084, 365618e-10, 0, .936508, .322714, 342533e-10, 0, .968254, .306974, 339596e-10, 0, 1, 1, 101524e-23, 0, 0, 1, 10292e-22, 0, 0, 1, 130908e-23, 0, 0, 1, 473331e-23, 0, 0, 1, 625319e-22, 0, 0, 1, 107932e-20, 0, 0, 1, 163779e-19, 0, 0, 1, 203198e-18, 0, 0, 1, 204717e-17, 0, 0, .999999, 168995e-16, 0, 0, .999998, 115855e-15, 0, 0, .999996, 66947e-14, 0, 0, .999991, 3.30863e-9, 0, 0, .999983, 1.41737e-8, 0, 0, .999968, 5.32626e-8, 0, 0, .99994, 1.77431e-7, 0, 0, .999891, 5.28835e-7, 0, 0, .999797, 142169e-11, 0, 0, .999617, 347057e-11, 0, 0, .999227, 77231e-10, 0, 0, .998239, 155753e-10, 0, 0, .994937, 268495e-10, 0, 0, .980225, 213742e-10, 0, 0, .967549, 21631e-10, 0, 0, .966865, 417989e-11, 0, 0, .965739, 763341e-11, 0, 0, .963794, 130892e-10, 0, 0, .960244, 206456e-10, 0, 0, .953495, 282016e-10, 0, 148105e-9, .940876, 271581e-10, 0, .002454, .926569, 164159e-10, 0, .00867491, .920905, 239521e-10, 0, .01956, .912169, 315127e-10, 0, .035433, .899095, 346626e-10, 0, .056294, .882209, 290223e-10, 0, .0818191, .870272, 342992e-10, 0, .111259, .855977, 394164e-10, 0, .142857, .837431, 372343e-10, 0, .174603, .820826, 396691e-10, 0, .206349, .803408, 435395e-10, 0, .238095, .782838, 419579e-10, 0, .269841, .763941, 450953e-10, 0, .301587, .742904, 455847e-10, 0, .333333, .721463, 458833e-10, 0, .365079, .700197, 477159e-10, 0, .396825, .677501, 470641e-10, 0, .428571, .655527, 484732e-10, 0, .460317, .6324, 476834e-10, 0, .492064, .609964, 484213e-10, 0, .52381, .586839, 475541e-10, 0, .555556, .564353, 476951e-10, 0, .587302, .541589, 467611e-10, 0, .619048, .519413, 463493e-10, 0, .650794, .497337, 453994e-10, 0, .68254, .475797, 445308e-10, 0, .714286, .454659, 435787e-10, 0, .746032, .434065, 424839e-10, 0, .777778, .414018, 41436e-9, 0, .809524, .39455, 401902e-10, 0, .84127, .375742, 390813e-10, 0, .873016, .357501, 377116e-10, 0, .904762, .339996, 36535e-9, 0, .936508, .323069, 351265e-10, 0, .968254, .306897, 339112e-10, 0, 1, 1, 10396e-19, 0, 0, 1, 104326e-20, 0, 0, 1, 110153e-20, 0, 0, 1, 144668e-20, 0, 0, 1, 34528e-19, 0, 0, 1, 175958e-19, 0, 0, 1, 12627e-17, 0, 0, 1, 936074e-18, 0, 0, 1, 645742e-17, 0, 0, .999998, 401228e-16, 0, 0, .999997, 222338e-15, 0, 0, .999995, 1.0967e-9, 0, 0, .999991, 4.82132e-9, 0, 0, .999981, 1.89434e-8, 0, 0, .999967, 6.67716e-8, 0, 0, .999938, 2.12066e-7, 0, 0, .999886, 6.0977e-7, 0, 0, .999792, 159504e-11, 0, 0, .999608, 381191e-11, 0, 0, .999209, 833727e-11, 0, 0, .998179, 165288e-10, 0, 0, .994605, 274387e-10, 0, 0, .979468, 167316e-10, 0, 0, .967529, 242877e-11, 0, 0, .966836, 461696e-11, 0, 0, .96569, 830977e-11, 0, 0, .963706, 140427e-10, 0, 244659e-11, .960063, 217353e-10, 0, 760774e-9, .953113, 286606e-10, 0, .00367261, .940192, 247691e-10, 0, .00940263, .927731, 195814e-10, 0, .018333, .920669, 252531e-10, 0, .0306825, .911799, 324277e-10, 0, .0465556, .89857, 340982e-10, 0, .0659521, .883283, 319622e-10, 0, .0887677, .86989, 35548e-9, 0, .114784, .855483, 397143e-10, 0, .143618, .837987, 391665e-10, 0, .174606, .820546, 411306e-10, 0, .206349, .802878, 436753e-10, 0, .238095, .783402, 444e-7, 0, .269841, .763439, 458726e-10, 0, .301587, .742925, 467097e-10, 0, .333333, .721633, 478887e-10, 0, .365079, .69985, 481251e-10, 0, .396825, .67783, 491811e-10, 0, .428571, .655126, 488199e-10, 0, .460318, .632697, 496025e-10, 0, .492064, .609613, 48829e-9, 0, .52381, .587098, 492754e-10, 0, .555556, .564119, 482625e-10, 0, .587302, .541813, 482807e-10, 0, .619048, .519342, 471552e-10, 0, .650794, .497514, 466765e-10, 0, .68254, .475879, 455582e-10, 0, .714286, .454789, 446007e-10, 0, .746032, .434217, 435382e-10, 0, .777778, .414086, 421753e-10, 0, .809524, .394744, 412093e-10, 0, .84127, .375782, 396634e-10, 0, .873016, .357707, 386419e-10, 0, .904762, .340038, 370345e-10, 0, .936508, .323284, 359725e-10, 0, .968254, .306954, 3436e-8, 0, 1, 1, 599567e-19, 0, 0, 1, 600497e-19, 0, 0, 1, 614839e-19, 0, 0, 1, 686641e-19, 0, 0, 1, 972658e-19, 0, 0, 1, 221271e-18, 0, 0, 1, 833195e-18, 0, 0, 1, 403601e-17, 0, 0, .999999, 206001e-16, 0, 0, .999998, 101739e-15, 0, 0, .999997, 470132e-15, 0, 0, .999993, 2.00436e-9, 0, 0, .999988, 7.83682e-9, 0, 0, .999979, 2.80338e-8, 0, 0, .999962, 9.17033e-8, 0, 0, .999933, 2.74514e-7, 0, 0, .999881, 7.53201e-7, 0, 0, .999783, 189826e-11, 0, 0, .999594, 440279e-11, 0, 0, .999178, 93898e-10, 0, 0, .998073, 181265e-10, 0, 0, .993993, 280487e-10, 0, 0, .979982, 149422e-10, 0, 0, .968145, 378481e-11, 0, 0, .966786, 53771e-10, 0, 0, .965611, 947508e-11, 0, 388934e-10, .963557, 156616e-10, 0, 9693e-7, .959752, 235144e-10, 0, .00370329, .952461, 291568e-10, 0, .00868428, .940193, 240102e-10, 0, .0161889, .929042, 231235e-10, 0, .0263948, .920266, 273968e-10, 0, .0394088, .911178, 337915e-10, 0, .0552818, .897873, 333629e-10, 0, .0740138, .884053, 351405e-10, 0, .0955539, .869455, 378034e-10, 0, .119795, .854655, 399378e-10, 0, .14656, .838347, 419108e-10, 0, .175573, .820693, 440831e-10, 0, .206388, .802277, 445599e-10, 0, .238095, .783634, 472691e-10, 0, .269841, .763159, 476984e-10, 0, .301587, .742914, 491487e-10, 0, .333333, .721662, 502312e-10, 0, .365079, .699668, 502817e-10, 0, .396825, .677839, 51406e-9, 0, .428571, .655091, 511095e-10, 0, .460317, .632665, 516067e-10, 0, .492064, .609734, 512255e-10, 0, .52381, .587043, 510263e-10, 0, .555556, .564298, 50565e-9, 0, .587302, .541769, 497951e-10, 0, .619048, .519529, 492698e-10, 0, .650794, .497574, 482066e-10, 0, .68254, .476028, 473689e-10, 0, .714286, .454961, 461941e-10, 0, .746032, .434341, 450618e-10, 0, .777778, .414364, 438355e-10, 0, .809524, .394832, 424196e-10, 0, .84127, .376109, 412563e-10, 0, .873016, .35779, 396226e-10, 0, .904762, .340379, 384886e-10, 0, .936508, .323385, 368214e-10, 0, .968254, .307295, 356636e-10, 0, 1, 1, 106465e-17, 0, 0, 1, 106555e-17, 0, 0, 1, 107966e-17, 0, 0, 1, 114601e-17, 0, 0, 1, 137123e-17, 0, 0, 1, 21243e-16, 0, 0, .999999, 489653e-17, 0, 0, .999999, 160283e-16, 0, 0, .999998, 62269e-15, 0, 0, .999997, 251859e-15, 0, 0, .999996, 996192e-15, 0, 0, .999992, 3.74531e-9, 0, 0, .999986, 1.32022e-8, 0, 0, .999975, 4.33315e-8, 0, 0, .999959, 1.31956e-7, 0, 0, .999927, 3.72249e-7, 0, 0, .999871, 9.72461e-7, 0, 0, .999771, 235343e-11, 0, 0, .999572, 52768e-10, 0, 0, .999133, 109237e-10, 0, 0, .997912, 203675e-10, 0, 0, .993008, 279396e-10, 0, 0, .980645, 139604e-10, 0, 0, .970057, 646596e-11, 0, 0, .966717, 65089e-10, 0, 474145e-10, .965497, 111863e-10, 0, 89544e-8, .96334, 179857e-10, 0, .0032647, .959294, 259045e-10, 0, .0075144, .951519, 292327e-10, 0, .0138734, .940517, 249769e-10, 0, .0224952, .93014, 26803e-9, 0, .0334828, .91972, 303656e-10, 0, .0468973, .910294, 353323e-10, 0, .0627703, .897701, 351002e-10, 0, .0811019, .884522, 388104e-10, 0, .10186, .869489, 412932e-10, 0, .124985, .853983, 415781e-10, 0, .150372, .838425, 454066e-10, 0, .177868, .820656, 471624e-10, 0, .207245, .801875, 475243e-10, 0, .238143, .783521, 505621e-10, 0, .269841, .763131, 50721e-9, 0, .301587, .74261, 523293e-10, 0, .333333, .72148, 528699e-10, 0, .365079, .699696, 538677e-10, 0, .396825, .677592, 539255e-10, 0, .428571, .65525, 546367e-10, 0, .460317, .632452, 541348e-10, 0, .492064, .609903, 544976e-10, 0, .52381, .586928, 536201e-10, 0, .555556, .564464, 535185e-10, 0, .587302, .541801, 524949e-10, 0, .619048, .519681, 51812e-9, 0, .650794, .497685, 507687e-10, 0, .68254, .47622, 496243e-10, 0, .714286, .455135, 485714e-10, 0, .746032, .4346, 471847e-10, 0, .777778, .414564, 459294e-10, 0, .809524, .395165, 444705e-10, 0, .84127, .376333, 430772e-10, 0, .873016, .358197, 416229e-10, 0, .904762, .34064, 401019e-10, 0, .936508, .323816, 386623e-10, 0, .968254, .307581, 370933e-10, 0, 1, 1, 991541e-17, 0, 0, 1, 992077e-17, 0, 0, 1, 100041e-16, 0, 0, 1, 10385e-15, 0, 0, 1, 115777e-16, 0, 0, 1, 150215e-16, 0, 0, .999999, 254738e-16, 0, 0, .999999, 598822e-16, 0, 0, .999998, 179597e-15, 0, 0, .999997, 602367e-15, 0, 0, .999994, 2.06835e-9, 0, 0, .99999, 6.94952e-9, 0, 0, .999984, 2.23363e-8, 0, 0, .999972, 6.78578e-8, 0, 0, .999952, 1.93571e-7, 0, 0, .999919, 5.16594e-7, 0, 0, .99986, 128739e-11, 0, 0, .999753, 299298e-11, 0, 0, .999546, 648258e-11, 0, 0, .999074, 129985e-10, 0, 0, .997671, 232176e-10, 0, 0, .991504, 256701e-10, 0, 0, .981148, 131141e-10, 0, 0, .971965, 869048e-11, 0, 280182e-10, .966624, 808301e-11, 0, 695475e-9, .965344, 135235e-10, 0, .00265522, .963048, 210592e-10, 0, .00622975, .958673, 287473e-10, 0, .0116234, .950262, 281379e-10, 0, .018976, .940836, 271089e-10, 0, .0283844, .930996, 30926e-9, 0, .0399151, .919848, 348359e-10, 0, .0536063, .909136, 366092e-10, 0, .0694793, .897554, 384162e-10, 0, .0875342, .884691, 430971e-10, 0, .107749, .869414, 447803e-10, 0, .130087, .853462, 452858e-10, 0, .154481, .838187, 495769e-10, 0, .180833, .820381, 502709e-10, 0, .209005, .801844, 522713e-10, 0, .238791, .783061, 541505e-10, 0, .269869, .763205, 553712e-10, 0, .301587, .742362, 564909e-10, 0, .333333, .721393, 572646e-10, 0, .365079, .699676, 581012e-10, 0, .396825, .677395, 58096e-9, 0, .428571, .655208, 585766e-10, 0, .460317, .632451, 583602e-10, 0, .492064, .609839, 580234e-10, 0, .52381, .587093, 577161e-10, 0, .555556, .564467, 568447e-10, 0, .587302, .542043, 563166e-10, 0, .619048, .519826, 55156e-9, 0, .650794, .497952, 541682e-10, 0, .68254, .476477, 528971e-10, 0, .714286, .455412, 514952e-10, 0, .746032, .434926, 502222e-10, 0, .777778, .4149, 485779e-10, 0, .809524, .395552, 472242e-10, 0, .84127, .376712, 454891e-10, 0, .873016, .358622, 440924e-10, 0, .904762, .341048, 422984e-10, 0, .936508, .324262, 408582e-10, 0, .968254, .308013, 390839e-10, 0, 1, 1, 613913e-16, 0, 0, 1, 614145e-16, 0, 0, 1, 617708e-16, 0, 0, 1, 633717e-16, 0, 0, 1, 681648e-16, 0, 0, 1, 808291e-16, 0, 0, 1, 114608e-15, 0, 0, .999998, 210507e-15, 0, 0, .999997, 499595e-15, 0, 0, .999995, 1.39897e-9, 0, 0, .999994, 4.19818e-9, 0, 0, .999988, 1.27042e-8, 0, 0, .999979, 3.75153e-8, 0, 0, .999965, 1.06206e-7, 0, 0, .999945, 2.85381e-7, 0, 0, .999908, 7.23611e-7, 0, 0, .999846, 17255e-10, 0, 0, .999733, 386104e-11, 0, 0, .999511, 808493e-11, 0, 0, .998993, 156884e-10, 0, 0, .997326, 265538e-10, 0, 0, .989706, 206466e-10, 0, 0, .981713, 130756e-10, 0, 70005e-10, .973636, 106473e-10, 0, 464797e-9, .966509, 10194e-9, 0, .00201743, .965149, 165881e-10, 0, .00497549, .962669, 249147e-10, 0, .00953262, .95786, 317449e-10, 0, .0158211, .949334, 281045e-10, 0, .0239343, .941041, 303263e-10, 0, .0339372, .931575, 356754e-10, 0, .0458738, .920102, 397075e-10, 0, .059772, .908002, 384886e-10, 0, .075645, .897269, 43027e-9, 0, .0934929, .884559, 479925e-10, 0, .113302, .869161, 48246e-9, 0, .135045, .853342, 509505e-10, 0, .158678, .837633, 542846e-10, 0, .184136, .820252, 554139e-10, 0, .211325, .801872, 581412e-10, 0, .240113, .782418, 585535e-10, 0, .270306, .7631, 610923e-10, 0, .301594, .742183, 613678e-10, 0, .333333, .721098, 627275e-10, 0, .365079, .699512, 629413e-10, 0, .396825, .677372, 636351e-10, 0, .428571, .655059, 633555e-10, 0, .460317, .632567, 636513e-10, 0, .492064, .609784, 628965e-10, 0, .52381, .587237, 625546e-10, 0, .555556, .564525, 615825e-10, 0, .587302, .542181, 605048e-10, 0, .619048, .520017, 596329e-10, 0, .650794, .498204, 581516e-10, 0, .68254, .476742, 569186e-10, 0, .714286, .455803, 553833e-10, 0, .746032, .435251, 537807e-10, 0, .777778, .415374, 522025e-10, 0, .809524, .395921, 503421e-10, 0, .84127, .377253, 488211e-10, 0, .873016, .359021, 468234e-10, 0, .904762, .341637, 453269e-10, 0, .936508, .3247, 433014e-10, 0, .968254, .308625, 418007e-10, 0, 1, 1, 286798e-15, 0, 0, 1, 286877e-15, 0, 0, 1, 288094e-15, 0, 0, 1, 293506e-15, 0, 0, 1, 309262e-15, 0, 0, .999999, 348593e-15, 0, 0, .999999, 444582e-15, 0, 0, .999998, 688591e-15, 0, 0, .999996, 1.34391e-9, 0, 0, .999993, 3.17438e-9, 0, 0, .999989, 8.35609e-9, 0, 0, .999983, 2.28677e-8, 0, 0, .999974, 6.23361e-8, 0, 0, .999959, 1.65225e-7, 0, 0, .999936, 4.19983e-7, 0, 0, .999896, 101546e-11, 0, 0, .99983, 232376e-11, 0, 0, .999709, 50156e-10, 0, 0, .999469, 10167e-9, 0, 0, .998886, 190775e-10, 0, 0, .996819, 300511e-10, 0, 0, .988837, 185092e-10, 0, 1.68222e-7, .982178, 134622e-10, 0, 259622e-9, .975017, 125961e-10, 0, .00142595, .967101, 13507e-9, 0, .00382273, .964905, 205003e-10, 0, .00764164, .96218, 29546e-9, 0, .0130121, .956821, 343738e-10, 0, .0200253, .948829, 305063e-10, 0, .0287452, .941092, 346487e-10, 0, .039218, .931883, 412061e-10, 0, .0514748, .920211, 444651e-10, 0, .0655351, .907307, 431252e-10, 0, .0814082, .89684, 490382e-10, 0, .0990939, .884119, 53334e-9, 0, .118583, .869148, 54114e-9, 0, .139856, .853377, 578536e-10, 0, .162882, .836753, 592285e-10, 0, .187615, .820063, 622787e-10, 0, .213991, .801694, 645492e-10, 0, .241918, .782116, 65353e-9, 0, .271267, .762673, 674344e-10, 0, .301847, .742133, 682788e-10, 0, .333333, .720779, 691959e-10, 0, .365079, .699386, 696817e-10, 0, .396826, .67732, 699583e-10, 0, .428572, .654888, 698447e-10, 0, .460318, .632499, 694063e-10, 0, .492064, .609825, 691612e-10, 0, .52381, .587287, 681576e-10, 0, .555556, .564743, 674138e-10, 0, .587302, .542409, 661617e-10, 0, .619048, .520282, 647785e-10, 0, .650794, .498506, 633836e-10, 0, .68254, .477102, 615905e-10, 0, .714286, .456167, 601013e-10, 0, .746032, .435728, 581457e-10, 0, .777778, .415809, 564215e-10, 0, .809524, .396517, 544997e-10, 0, .84127, .377737, 525061e-10, 0, .873016, .359698, 506831e-10, 0, .904762, .342164, 48568e-9, 0, .936508, .325417, 467826e-10, 0, .968254, .309186, 446736e-10, 0, 1, 1, 1.09018e-9, 0, 0, 1, 1.0904e-9, 0, 0, 1, 1.09393e-9, 0, 0, 1, 1.1095e-9, 0, 0, 1, 1.154e-9, 0, 0, 1, 1.26089e-9, 0, 0, .999999, 1.5059e-9, 0, 0, .999997, 2.07899e-9, 0, 0, .999994, 3.48164e-9, 0, 0, .999993, 7.05728e-9, 0, 0, .999987, 1.63692e-8, 0, 0, .999981, 4.06033e-8, 0, 0, .999969, 1.0245e-7, 0, 0, .999953, 2.55023e-7, 0, 0, .999925, 6.1511e-7, 0, 0, .999881, 142218e-11, 0, 0, .99981, 313086e-11, 0, 0, .99968, 653119e-11, 0, 0, .999418, 12832e-9, 0, 0, .998748, 232497e-10, 0, 0, .996066, 329522e-10, 0, 0, .988379, 179613e-10, 0, 108799e-9, .982567, 143715e-10, 0, 921302e-9, .976097, 148096e-10, 0, .00280738, .968475, 178905e-10, 0, .00596622, .964606, 253921e-10, 0, .0105284, .961564, 348623e-10, 0, .0165848, .955517, 357612e-10, 0, .0242, .948381, 343493e-10, 0, .03342, .941095, 405849e-10, 0, .0442777, .931923, 475394e-10, 0, .0567958, .91996, 484328e-10, 0, .0709879, .907419, 502146e-10, 0, .086861, .89618, 561654e-10, 0, .104415, .88337, 587612e-10, 0, .123643, .869046, 618057e-10, 0, .144531, .853278, 657392e-10, 0, .167057, .836091, 66303e-9, 0, .191188, .819644, 704445e-10, 0, .216878, .801246, 714071e-10, 0, .244062, .782031, 740093e-10, 0, .272649, .762066, 74685e-9, 0, .302509, .741964, 766647e-10, 0, .333442, .720554, 766328e-10, 0, .365079, .699098, 777857e-10, 0, .396826, .677189, 774633e-10, 0, .428572, .65484, 776235e-10, 0, .460318, .632496, 770316e-10, 0, .492064, .609908, 762669e-10, 0, .52381, .587312, 753972e-10, 0, .555556, .564938, 739994e-10, 0, .587302, .542577, 728382e-10, 0, .619048, .52062, 71112e-9, 0, .650794, .498819, 694004e-10, 0, .68254, .477555, 675575e-10, 0, .714286, .456568, 653449e-10, 0, .746032, .436278, 636068e-10, 0, .777778, .41637, 613466e-10, 0, .809524, .397144, 594177e-10, 0, .84127, .378412, 570987e-10, 0, .873016, .360376, 550419e-10, 0, .904762, .342906, 527422e-10, 0, .936508, .326136, 506544e-10, 0, .968254, .30997, 484307e-10, 0, 1, 1, 3.54014e-9, 0, 0, 1, 3.54073e-9, 0, 0, 1, 3.54972e-9, 0, 0, 1, 3.58929e-9, 0, 0, 1, 3.70093e-9, 0, 0, .999999, 3.96194e-9, 0, 0, .999998, 4.53352e-9, 0, 0, .999997, 5.78828e-9, 0, 0, .999994, 8.63812e-9, 0, 0, .999991, 1.53622e-8, 0, 0, .999985, 3.16356e-8, 0, 0, .999977, 7.12781e-8, 0, 0, .999964, 1.66725e-7, 0, 0, .999945, 3.90501e-7, 0, 0, .999912, 8.95622e-7, 0, 0, .999866, 198428e-11, 0, 0, .999786, 421038e-11, 0, 0, .999647, 850239e-11, 0, 0, .999356, 162059e-10, 0, 0, .998563, 282652e-10, 0, 0, .994928, 336309e-10, 0, 244244e-10, .987999, 178458e-10, 0, 523891e-9, .982893, 159162e-10, 0, .00194729, .977044, 178056e-10, 0, .00451099, .969972, 230624e-10, 0, .00835132, .964237, 313922e-10, 0, .013561, .960791, 406145e-10, 0, .0202056, .954292, 372796e-10, 0, .0283321, .948052, 403199e-10, 0, .0379739, .940938, 479537e-10, 0, .0491551, .931689, 545292e-10, 0, .0618918, .91987, 54038e-9, 0, .0761941, .907665, 589909e-10, 0, .0920672, .895281, 642651e-10, 0, .109511, .882621, 659707e-10, 0, .12852, .86873, 709973e-10, 0, .149085, .853008, 742221e-10, 0, .171189, .835944, 761754e-10, 0, .194809, .818949, 797052e-10, 0, .21991, .800951, 812434e-10, 0, .246447, .781847, 838075e-10, 0, .274352, .761649, 84501e-9, 0, .303535, .74152, 860258e-10, 0, .333857, .720495, 866233e-10, 0, .365104, .698742, 868326e-10, 0, .396826, .677096, 87133e-9, 0, .428572, .654782, 863497e-10, 0, .460318, .632335, 860206e-10, 0, .492064, .610031, 849337e-10, 0, .52381, .587457, 838279e-10, 0, .555556, .56513, 82309e-9, 0, .587302, .542877, 803542e-10, 0, .619048, .5209, 786928e-10, 0, .650794, .499291, 765171e-10, 0, .68254, .477971, 744753e-10, 0, .714286, .457221, 72209e-9, 0, .746032, .436803, 697448e-10, 0, .777778, .417083, 675333e-10, 0, .809524, .397749, 648058e-10, 0, .84127, .379177, 625759e-10, 0, .873016, .361061, 598584e-10, 0, .904762, .343713, 575797e-10, 0, .936508, .326894, 549999e-10, 0, .968254, .310816, 527482e-10, 0, 1, 1, 1.0153e-8, 0, 0, 1, 1.01544e-8, 0, 0, 1, 1.01751e-8, 0, 0, 1, 1.02662e-8, 0, 0, 1, 1.0521e-8, 0, 0, .999999, 1.11049e-8, 0, 0, .999999, 1.23408e-8, 0, 0, .999996, 1.4924e-8, 0, 0, .999992, 2.04471e-8, 0, 0, .999989, 3.26539e-8, 0, 0, .99998, 6.03559e-8, 0, 0, .999971, 1.23936e-7, 0, 0, .999955, 2.69058e-7, 0, 0, .999933, 5.93604e-7, 0, 0, .999901, 129633e-11, 0, 0, .999847, 275621e-11, 0, 0, .999761, 564494e-11, 0, 0, .999607, 110485e-10, 0, 0, .999282, 204388e-10, 0, 0, .99831, 341084e-10, 0, 2.2038e-7, .993288, 294949e-10, 0, 242388e-9, .987855, 192736e-10, 0, .0012503, .983167, 182383e-10, 0, .0032745, .977908, 218633e-10, 0, .00646321, .971194, 290662e-10, 0, .0109133, .963867, 386401e-10, 0, .0166927, .95982, 462827e-10, 0, .0238494, .953497, 420705e-10, 0, .0324178, .947621, 477743e-10, 0, .0424225, .940611, 568258e-10, 0, .0538808, .931174, 618061e-10, 0, .0668047, .919919, 627098e-10, 0, .0812014, .907856, 694714e-10, 0, .0970745, .894509, 735008e-10, 0, .114424, .881954, 763369e-10, 0, .133246, .868309, 821896e-10, 0, .153534, .852511, 83769e-9, 0, .175275, .835821, 881615e-10, 0, .198453, .817981, 896368e-10, 0, .223042, .800504, 930906e-10, 0, .249009, .78141, 945056e-10, 0, .276304, .761427, 963605e-10, 0, .304862, .74094, 968088e-10, 0, .334584, .720233, 981481e-10, 0, .365322, .698592, 979122e-10, 0, .396826, .676763, 981057e-10, 0, .428571, .654808, 973956e-10, 0, .460318, .632326, 962619e-10, 0, .492064, .610049, 952996e-10, 0, .52381, .58763, 933334e-10, 0, .555556, .565261, 917573e-10, 0, .587302, .543244, 896636e-10, 0, .619048, .521273, 873304e-10, 0, .650794, .499818, 852648e-10, 0, .68254, .478536, 823961e-10, 0, .714286, .457826, 79939e-9, 0, .746032, .437549, 77126e-9, 0, .777778, .41776, 743043e-10, 0, .809524, .39863, 716426e-10, 0, .84127, .379954, 686456e-10, 0, .873016, .362025, 660514e-10, 0, .904762, .344581, 630755e-10, 0, .936508, .327909, 605439e-10, 0, .968254, .311736, 576345e-10, 0, 1, 1, 2.63344e-8, 0, 0, 1, 2.63373e-8, 0, 0, 1, 2.63815e-8, 0, 0, 1, 2.65753e-8, 0, 0, 1, 2.71132e-8, 0, 0, .999999, 2.83279e-8, 0, 0, .999997, 3.0833e-8, 0, 0, .999995, 3.58711e-8, 0, 0, .999992, 4.61266e-8, 0, 0, .999985, 6.7574e-8, 0, 0, .999977, 1.1358e-7, 0, 0, .999966, 2.13657e-7, 0, 0, .999948, 4.31151e-7, 0, 0, .999923, 8.96656e-7, 0, 0, .999884, 186603e-11, 0, 0, .999826, 381115e-11, 0, 0, .999732, 754184e-11, 0, 0, .999561, 143192e-10, 0, 0, .999191, 257061e-10, 0, 0, .997955, 405724e-10, 0, 744132e-10, .992228, 276537e-10, 0, 716477e-9, .987638, 208885e-10, 0, .0022524, .983395, 215226e-10, 0, .00484816, .978614, 270795e-10, 0, .00860962, .972389, 365282e-10, 0, .0136083, .964392, 474747e-10, 0, .0198941, .95861, 509141e-10, 0, .0275023, .952806, 48963e-9, 0, .0364584, .94712, 571119e-10, 0, .04678, .940104, 671704e-10, 0, .0584799, .930398, 687586e-10, 0, .0715665, .919866, 738161e-10, 0, .086045, .907853, 813235e-10, 0, .101918, .894078, 834582e-10, 0, .119186, .881177, 892093e-10, 0, .137845, .867575, 944548e-10, 0, .157891, .852107, 969607e-10, 0, .179316, .835502, 101456e-9, 0, .202106, .81756, 103256e-9, 0, .226243, .79984, 106954e-9, 0, .251704, .780998, 108066e-9, 0, .278451, .761132, 110111e-9, 0, .306436, .740429, 110459e-9, 0, .335586, .719836, 111219e-9, 0, .365796, .698467, 11145e-8, 0, .3969, .676446, 110393e-9, 0, .428571, .654635, 110035e-9, 0, .460318, .632411, 108548e-9, 0, .492064, .609986, 106963e-9, 0, .52381, .587872, 105238e-9, 0, .555556, .565528, 102665e-9, 0, .587302, .543563, 100543e-9, 0, .619048, .52176, 976182e-10, 0, .650794, .500188, 947099e-10, 0, .68254, .479204, 919929e-10, 0, .714286, .458413, 886139e-10, 0, .746032, .438314, 857839e-10, 0, .777778, .418573, 82411e-9, 0, .809524, .39947, 792211e-10, 0, .84127, .380892, 759546e-10, 0, .873016, .362953, 727571e-10, 0, .904762, .345601, 695738e-10, 0, .936508, .328895, 664907e-10, 0, .968254, .312808, 634277e-10, 0, 1, 1, 6.28647e-8, 0, 0, 1, 6.28705e-8, 0, 0, 1, 6.29587e-8, 0, 0, 1, 6.33441e-8, 0, 0, .999999, 6.44087e-8, 0, 0, .999998, 6.67856e-8, 0, 0, .999997, 7.15889e-8, 0, 0, .999995, 8.09577e-8, 0, 0, .999989, 9.92764e-8, 0, 0, .999983, 1.35834e-7, 0, 0, .999974, 2.10482e-7, 0, 0, .999959, 3.65215e-7, 0, 0, .999939, 6.86693e-7, 0, 0, .999911, 13472e-10, 0, 0, .999868, 26731e-10, 0, 0, .999804, 524756e-11, 0, 0, .9997, 100403e-10, 0, 0, .99951, 185019e-10, 0, 0, .999078, 322036e-10, 0, 620676e-11, .997428, 470002e-10, 0, 341552e-9, .99162, 287123e-10, 0, .00143727, .987479, 234706e-10, 0, .00349201, .983582, 260083e-10, 0, .0066242, .979186, 337927e-10, 0, .0109113, .97325, 454689e-10, 0, .0164064, .965221, 573759e-10, 0, .0231463, .957262, 544114e-10, 0, .0311571, .952211, 587006e-10, 0, .0404572, .946631, 692256e-10, 0, .0510592, .939391, 787819e-10, 0, .0629723, .929795, 792368e-10, 0, .0762025, .91965, 875075e-10, 0, .090753, .907737, 950903e-10, 0, .106626, .893899, 972963e-10, 0, .123822, .880239, 10459e-8, 0, .142337, .866562, 107689e-9, 0, .16217, .85164, 113081e-9, 0, .183314, .835021, 116636e-9, 0, .20576, .817311, 120074e-9, 0, .229496, .798845, 121921e-9, 0, .254502, .780479, 12475e-8, 0, .280753, .760694, 125255e-9, 0, .308212, .740142, 126719e-9, 0, .336825, .719248, 12636e-8, 0, .366517, .698209, 126712e-9, 0, .397167, .676398, 125769e-9, 0, .428578, .654378, 124432e-9, 0, .460318, .632484, 123272e-9, 0, .492064, .610113, 12085e-8, 0, .52381, .587931, 118411e-9, 0, .555556, .565872, 11569e-8, 0, .587302, .543814, 112521e-9, 0, .619048, .522265, 109737e-9, 0, .650794, .500835, 106228e-9, 0, .68254, .479818, 102591e-9, 0, .714286, .459258, 991288e-10, 0, .746032, .439061, 952325e-10, 0, .777778, .419552, 91895e-9, 0, .809524, .400399, 879051e-10, 0, .84127, .381976, 844775e-10, 0, .873016, .364009, 806316e-10, 0, .904762, .346761, 771848e-10, 0, .936508, .330049, 735429e-10, 0, .968254, .314018, 702103e-10, 0, 1, 1, 1.39968e-7, 0, 0, 1, 1.39979e-7, 0, 0, 1, 1.40145e-7, 0, 0, 1, 1.4087e-7, 0, 0, .999999, 1.42865e-7, 0, 0, .999998, 1.47279e-7, 0, 0, .999997, 1.56057e-7, 0, 0, .999992, 1.7276e-7, 0, 0, .999989, 2.04352e-7, 0, 0, .99998, 2.6494e-7, 0, 0, .999969, 3.83435e-7, 0, 0, .999953, 6.18641e-7, 0, 0, .999929, 108755e-11, 0, 0, .999898, 201497e-11, 0, 0, .999849, 381346e-11, 0, 0, .999778, 719815e-11, 0, 0, .999661, 133215e-10, 0, 0, .999451, 238313e-10, 0, 0, .998936, 401343e-10, 0, 113724e-9, .99662, 517346e-10, 0, 820171e-9, .991094, 304323e-10, 0, .00238143, .987487, 281757e-10, 0, .00493527, .983731, 320048e-10, 0, .00856859, .979647, 423905e-10, 0, .0133393, .973837, 562935e-10, 0, .0192863, .96584, 677442e-10, 0, .0264369, .956309, 623073e-10, 0, .03481, .951523, 704131e-10, 0, .0444184, .946003, 836594e-10, 0, .0552713, .938454, 911736e-10, 0, .0673749, .929279, 938264e-10, 0, .0807329, .919239, 103754e-9, 0, .0953479, .907293, 109928e-9, 0, .111221, .893936, 115257e-9, 0, .128352, .879674, 122265e-9, 0, .14674, .865668, 125733e-9, 0, .166382, .850998, 132305e-9, 0, .187276, .834498, 134844e-9, 0, .209413, .816903, 139276e-9, 0, .232786, .798235, 140984e-9, 0, .257382, .779724, 14378e-8, 0, .283181, .760251, 144623e-9, 0, .310156, .739808, 145228e-9, 0, .338269, .718762, 14539e-8, 0, .367461, .697815, 144432e-9, 0, .397646, .67631, 143893e-9, 0, .428685, .654278, 141846e-9, 0, .460318, .632347, 13935e-8, 0, .492064, .610296, 137138e-9, 0, .52381, .588039, 133806e-9, 0, .555556, .566218, 130755e-9, 0, .587302, .544346, 127128e-9, 0, .619048, .522701, 123002e-9, 0, .650794, .501542, 119443e-9, 0, .68254, .480508, 115055e-9, 0, .714286, .460092, 111032e-9, 0, .746032, .440021, 106635e-9, 0, .777778, .420446, 102162e-9, 0, .809524, .401512, 98184e-9, 0, .84127, .38299, 936497e-10, 0, .873016, .365232, 89813e-9, 0, .904762, .347865, 853073e-10, 0, .936508, .331342, 817068e-10, 0, .968254, .315202, 773818e-10, 0, 1, 1, 2.9368e-7, 0, 0, 1, 2.937e-7, 0, 0, 1, 2.93998e-7, 0, 0, 1, 2.95298e-7, 0, 0, .999999, 2.98865e-7, 0, 0, .999998, 3.067e-7, 0, 0, .999995, 3.22082e-7, 0, 0, .999992, 3.50767e-7, 0, 0, .999986, 4.03538e-7, 0, 0, .999976, 5.01372e-7, 0, 0, .999964, 6.8562e-7, 0, 0, .999945, 10374e-10, 0, 0, .999919, 171269e-11, 0, 0, .999882, 300175e-11, 0, 0, .999829, 542144e-11, 0, 0, .999749, 984182e-11, 0, 0, .99962, 176213e-10, 0, 0, .999382, 305995e-10, 0, 138418e-10, .998751, 496686e-10, 0, 389844e-9, .995344, 510733e-10, 0, .00150343, .990768, 345829e-10, 0, .00352451, .987464, 342841e-10, 0, .00655379, .983846, 399072e-10, 0, .0106554, .980007, 533219e-10, 0, .0158723, .974494, 696992e-10, 0, .0222333, .96622, 776754e-10, 0, .029758, .956273, 747718e-10, 0, .0384596, .950952, 864611e-10, 0, .0483473, .945215, 100464e-9, 0, .0594266, .937287, 103729e-9, 0, .0717019, .928649, 111665e-9, 0, .0851752, .918791, 12353e-8, 0, .0998479, .906685, 127115e-9, 0, .115721, .893706, 13628e-8, 0, .132794, .879248, 142427e-9, 0, .151067, .864685, 148091e-9, 0, .170538, .850032, 153517e-9, 0, .191204, .833853, 157322e-9, 0, .213063, .816353, 161086e-9, 0, .236107, .797834, 164111e-9, 0, .260329, .778831, 165446e-9, 0, .285714, .759756, 167492e-9, 0, .312243, .739419, 166928e-9, 0, .339887, .718491, 167e-6, 0, .368604, .697392, 165674e-9, 0, .398329, .676102, 163815e-9, 0, .428961, .654243, 162003e-9, 0, .460331, .632176, 158831e-9, 0, .492064, .610407, 155463e-9, 0, .52381, .588394, 152062e-9, 0, .555556, .56645, 147665e-9, 0, .587302, .5449, 14375e-8, 0, .619048, .523276, 138905e-9, 0, .650794, .502179, 134189e-9, 0, .68254, .481359, 129392e-9, 0, .714286, .46092, 124556e-9, 0, .746032, .441084, 11957e-8, 0, .777778, .421517, 114652e-9, 0, .809524, .402721, 109688e-9, 0, .84127, .384222, 104667e-9, 0, .873016, .366534, 999633e-10, 0, .904762, .349205, 950177e-10, 0, .936508, .332702, 907301e-10, 0, .968254, .316599, 859769e-10, 0, 1, 1, 5.85473e-7, 0, 0, 1, 5.85507e-7, 0, 0, 1, 5.8602e-7, 0, 0, .999999, 5.88259e-7, 0, 0, .999999, 5.94381e-7, 0, 0, .999998, 6.07754e-7, 0, 0, .999995, 6.33729e-7, 0, 0, .99999, 6.8137e-7, 0, 0, .999984, 7.67003e-7, 0, 0, .999973, 9.21212e-7, 0, 0, .999959, 120218e-11, 0, 0, .999936, 172024e-11, 0, 0, .999907, 268088e-11, 0, 0, .999866, 445512e-11, 0, 0, .999806, 768481e-11, 0, 0, .999716, 1342e-8, 0, 0, .999576, 232473e-10, 0, 0, .9993, 391694e-10, 0, 129917e-9, .998498, 608429e-10, 0, 845035e-9, .994132, 489743e-10, 0, .00237616, .99031, 384644e-10, 0, .00484456, .987409, 421768e-10, 0, .00832472, .983981, 504854e-10, 0, .0128643, .980268, 671028e-10, 0, .0184947, .974875, 852749e-10, 0, .025237, .966063, 85531e-9, 0, .0331046, .956779, 900588e-10, 0, .0421067, .950259, 10577e-8, 0, .0522487, .944239, 119458e-9, 0, .0635343, .936341, 122164e-9, 0, .0759654, .928047, 134929e-9, 0, .0895434, .918065, 145544e-9, 0, .104269, .906267, 150531e-9, 0, .120142, .893419, 161652e-9, 0, .137163, .878758, 16593e-8, 0, .15533, .863699, 174014e-9, 0, .174645, .848876, 177877e-9, 0, .195106, .833032, 184049e-9, 0, .21671, .815557, 186088e-9, 0, .239454, .797323, 19054e-8, 0, .263332, .778124, 191765e-9, 0, .288336, .758929, 192535e-9, 0, .314451, .738979, 192688e-9, 0, .341658, .718213, 191522e-9, 0, .369924, .696947, 190491e-9, 0, .399202, .675807, 187913e-9, 0, .429416, .654147, 184451e-9, 0, .460447, .63229, 181442e-9, 0, .492064, .610499, 177139e-9, 0, .523809, .588747, 172596e-9, 0, .555555, .566783, 167457e-9, 0, .587301, .545359, 162518e-9, 0, .619048, .523984, 156818e-9, 0, .650794, .502917, 151884e-9, 0, .68254, .482294, 145514e-9, 0, .714286, .461945, 140199e-9, 0, .746032, .442133, 134101e-9, 0, .777778, .422705, 128374e-9, 0, .809524, .403916, 122996e-9, 0, .84127, .38554, 116808e-9, 0, .873016, .367909, 111973e-9, 0, .904762, .350651, 105938e-9, 0, .936508, .334208, 101355e-9, 0, .968254, .318123, 957629e-10, 0, 1, 1, 111633e-11, 0, 0, 1, 111639e-11, 0, 0, 1, 111725e-11, 0, 0, 1, 112096e-11, 0, 0, .999999, 11311e-10, 0, 0, .999997, 115315e-11, 0, 0, .999995, 11956e-10, 0, 0, .999989, 127239e-11, 0, 0, .999981, 140772e-11, 0, 0, .999969, 164541e-11, 0, 0, .999952, 206607e-11, 0, 0, .999928, 281783e-11, 0, 0, .999895, 416835e-11, 0, 0, .999848, 658728e-11, 0, 0, .999781, 108648e-10, 0, 0, .999682, 182579e-10, 0, 0, .999523, 306003e-10, 0, 159122e-10, .999205, 499862e-10, 0, 391184e-9, .998131, 73306e-9, 0, .00147534, .993334, 513229e-10, 0, .0034227, .99016, 467783e-10, 0, .00632232, .987321, 523413e-10, 0, .0102295, .984099, 64267e-9, 0, .0151794, .980432, 843042e-10, 0, .0211947, .974976, 102819e-9, 0, .0282899, .966429, 996234e-10, 0, .0364739, .957633, 111074e-9, 0, .0457522, .949422, 128644e-9, 0, .0561278, .943045, 140076e-9, 0, .0676023, .935448, 146349e-9, 0, .0801762, .927225, 161854e-9, 0, .0938499, .917033, 169135e-9, 0, .108623, .905762, 179987e-9, 0, .124496, .892879, 189832e-9, 0, .141469, .878435, 195881e-9, 0, .159541, .863114, 20466e-8, 0, .178713, .84776, 209473e-9, 0, .198985, .832084, 214861e-9, 0, .220355, .814915, 217695e-9, 0, .242823, .796711, 220313e-9, 0, .266385, .777603, 22313e-8, 0, .291036, .757991, 222471e-9, 0, .316767, .738371, 222869e-9, 0, .343563, .717872, 221243e-9, 0, .371402, .696619, 218089e-9, 0, .400248, .675379, 21562e-8, 0, .430047, .65411, 21169e-8, 0, .460709, .63241, 206947e-9, 0, .492079, .61046, 201709e-9, 0, .52381, .58903, 196753e-9, 0, .555556, .567267, 189637e-9, 0, .587302, .545886, 184735e-9, 0, .619048, .524714, 177257e-9, 0, .650794, .503789, 171424e-9, 0, .68254, .483204, 164688e-9, 0, .714286, .462976, 157172e-9, 0, .746032, .443294, 151341e-9, 0, .777778, .423988, 143737e-9, 0, .809524, .405325, 138098e-9, 0, .84127, .386981, 130698e-9, 0, .873016, .369436, 125276e-9, 0, .904762, .35219, 118349e-9, 0, .936508, .335804, 11312e-8, 0, .968254, .319749, 106687e-9, 0, 1, 1, 204685e-11, 0, 0, 1, 204694e-11, 0, 0, 1, 204831e-11, 0, 0, .999999, 205428e-11, 0, 0, .999999, 207056e-11, 0, 0, .999997, 210581e-11, 0, 0, .999993, 21732e-10, 0, 0, .999987, 229365e-11, 0, 0, .999979, 250243e-11, 0, 0, .999965, 286127e-11, 0, 0, .999947, 348028e-11, 0, 0, .999918, 455588e-11, 0, 0, .999881, 643303e-11, 0, 0, .999828, 970064e-11, 0, 0, .999753, 153233e-10, 0, 0, .999642, 24793e-9, 0, 0, .999464, 402032e-10, 0, 122947e-9, .999089, 635852e-10, 0, 807414e-9, .997567, 857026e-10, 0, .00227206, .992903, 594912e-10, 0, .00462812, .990011, 578515e-10, 0, .00794162, .987192, 65399e-9, 0, .0122534, .98418, 819675e-10, 0, .0175888, .980491, 105514e-9, 0, .0239635, .974779, 121532e-9, 0, .031387, .96675, 119144e-9, 0, .0398644, .958248, 136125e-9, 0, .0493982, .948884, 155408e-9, 0, .0599896, .941673, 162281e-9, 0, .0716382, .934521, 176754e-9, 0, .0843437, .926205, 192873e-9, 0, .0981056, .916089, 200038e-9, 0, .112923, .904963, 213624e-9, 0, .128796, .892089, 221834e-9, 0, .145725, .878028, 232619e-9, 0, .163709, .86249, 238632e-9, 0, .182749, .846587, 247002e-9, 0, .202847, .830988, 250702e-9, 0, .224001, .814165, 255562e-9, 0, .246214, .796135, 257505e-9, 0, .269482, .777052, 258625e-9, 0, .293805, .757201, 258398e-9, 0, .319176, .737655, 256714e-9, 0, .345587, .717477, 255187e-9, 0, .373021, .696433, 251792e-9, 0, .401454, .675084, 247223e-9, 0, .430844, .653907, 242213e-9, 0, .461125, .632561, 237397e-9, 0, .492187, .610658, 229313e-9, 0, .52381, .589322, 224402e-9, 0, .555556, .567857, 216116e-9, 0, .587302, .54652, 209124e-9, 0, .619048, .525433, 201601e-9, 0, .650794, .504679, 192957e-9, 0, .68254, .484203, 186052e-9, 0, .714286, .464203, 177672e-9, 0, .746032, .444549, 170005e-9, 0, .777778, .425346, 162401e-9, 0, .809524, .406706, 1544e-7, 0, .84127, .388576, 147437e-9, 0, .873016, .37094, 139493e-9, 0, .904762, .353996, 133219e-9, 0, .936508, .337391, 125573e-9, 0, .968254, .321648, 119867e-9, 0, 1, 1, 362511e-11, 0, 0, 1, 362525e-11, 0, 0, 1, 362739e-11, 0, 0, .999999, 363673e-11, 0, 0, .999998, 366214e-11, 0, 0, .999996, 371698e-11, 0, 0, .999992, 382116e-11, 0, 0, .999986, 400554e-11, 0, 0, .999976, 432058e-11, 0, 0, .999961, 485194e-11, 0, 0, .999938, 574808e-11, 0, 0, .999908, 726643e-11, 0, 0, .999865, 984707e-11, 0, 0, .999807, 142217e-10, 0, 0, .999723, 215581e-10, 0, 0, .999602, 336114e-10, 0, 119113e-10, .999398, 527353e-10, 0, 355813e-9, .998946, 805809e-10, 0, .00137768, .996647, 942908e-10, 0, .00322469, .992298, 668733e-10, 0, .00597897, .989802, 716564e-10, 0, .00968903, .987019, 821355e-10, 0, .0143845, .984219, 104555e-9, 0, .0200831, .980425, 131245e-9, 0, .0267948, .974241, 139613e-9, 0, .034525, .967006, 145931e-9, 0, .0432757, .95893, 167153e-9, 0, .0530471, .949157, 188146e-9, 0, .0638386, .94062, 194625e-9, 0, .0756487, .933509, 213721e-9, 0, .0884762, .925088, 229616e-9, 0, .10232, .915178, 239638e-9, 0, .117178, .904093, 254814e-9, 0, .133051, .891337, 263685e-9, 0, .149939, .877326, 274789e-9, 0, .167841, .861794, 280534e-9, 0, .18676, .845758, 289534e-9, 0, .206696, .829792, 294446e-9, 0, .22765, .813037, 296877e-9, 0, .249625, .795285, 300217e-9, 0, .27262, .776323, 299826e-9, 0, .296636, .756673, 299787e-9, 0, .321671, .736856, 297867e-9, 0, .347718, .716883, 294052e-9, 0, .374768, .696089, 289462e-9, 0, .402804, .67505, 285212e-9, 0, .431796, .653509, 27653e-8, 0, .461695, .63258, 271759e-9, 0, .49242, .61104, 262811e-9, 0, .523822, .589567, 255151e-9, 0, .555556, .568322, 246434e-9, 0, .587302, .547235, 237061e-9, 0, .619048, .52616, 228343e-9, 0, .650794, .505716, 219236e-9, 0, .68254, .485274, 209595e-9, 0, .714286, .465411, 201011e-9, 0, .746032, .445854, 19109e-8, 0, .777778, .426911, 182897e-9, 0, .809524, .408222, 173569e-9, 0, .84127, .390307, 165496e-9, 0, .873016, .372624, 156799e-9, 0, .904762, .355804, 14917e-8, 0, .936508, .33924, 140907e-9, 0, .968254, .323534, 134062e-9, 0, 1, 1, 622487e-11, 0, 0, 1, 62251e-10, 0, 0, 1, 622837e-11, 0, 0, .999999, 624259e-11, 0, 0, .999998, 628127e-11, 0, 0, .999996, 636451e-11, 0, 0, .999991, 65218e-10, 0, 0, .999984, 679782e-11, 0, 0, .999973, 726361e-11, 0, 0, .999955, 803644e-11, 0, 0, .999931, 931397e-11, 0, 0, .999896, 114299e-10, 0, 0, .999847, 149402e-10, 0, 0, .999784, 207461e-10, 0, 0, .999692, 302493e-10, 0, 0, .999554, 454957e-10, 0, 997275e-10, .999326, 690762e-10, 0, 724813e-9, .998757, 101605e-9, 0, .0020972, .995367, 958745e-10, 0, .00432324, .99209, 832808e-10, 0, .00746347, .989517, 887601e-10, 0, .0115534, .987008, 10564e-8, 0, .0166134, .98421, 133179e-9, 0, .0226552, .98021, 161746e-9, 0, .0296838, .973676, 161821e-9, 0, .0377016, .967052, 178635e-9, 0, .0467079, .959385, 206765e-9, 0, .0567013, .949461, 22476e-8, 0, .0676796, .939578, 23574e-8, 0, .0796403, .932416, 25893e-8, 0, .0925812, .923759, 271228e-9, 0, .106501, .914223, 289165e-9, 0, .121397, .902942, 301156e-9, 0, .13727, .890419, 313852e-9, 0, .15412, .876639, 324408e-9, 0, .171946, .861316, 33249e-8, 0, .190751, .84496, 338497e-9, 0, .210537, .828427, 345861e-9, 0, .231305, .811871, 347863e-9, 0, .253057, .794397, 350225e-9, 0, .275797, .775726, 349915e-9, 0, .299525, .75617, 347297e-9, 0, .324242, .736091, 344232e-9, 0, .349947, .716213, 340835e-9, 0, .376633, .695736, 332369e-9, 0, .404289, .674961, 327943e-9, 0, .432895, .653518, 318533e-9, 0, .462415, .632574, 310391e-9, 0, .492788, .61134, 300755e-9, 0, .523909, .590017, 290506e-9, 0, .555556, .568752, 280446e-9, 0, .587302, .548061, 269902e-9, 0, .619048, .52711, 258815e-9, 0, .650794, .506682, 248481e-9, 0, .68254, .486524, 237141e-9, 0, .714286, .466812, 226872e-9, 0, .746032, .44732, 216037e-9, 0, .777778, .428473, 205629e-9, 0, .809524, .409921, 195691e-9, 0, .84127, .392028, 185457e-9, 0, .873016, .374606, 176436e-9, 0, .904762, .357601, 166508e-9, 0, .936508, .341348, 158385e-9, 0, .968254, .32542, 149203e-9, 0, 1, 1, 103967e-10, 0, 0, 1, 10397e-9, 0, 0, 1, 104019e-10, 0, 0, .999999, 104231e-10, 0, 0, .999998, 104806e-10, 0, 0, .999995, 106042e-10, 0, 0, .999991, 108366e-10, 0, 0, .999982, 112415e-10, 0, 0, .999968, 119174e-10, 0, 0, .99995, 130227e-10, 0, 0, .999922, 148176e-10, 0, 0, .999884, 177303e-10, 0, 0, .99983, 224564e-10, 0, 0, .999758, 300966e-10, 0, 0, .999654, 423193e-10, 0, 549083e-11, .999503, 614848e-10, 0, 296087e-9, .999237, 903576e-10, 0, .00123144, .998491, 1271e-7, 0, .00295954, .994594, 107754e-9, 0, .00555829, .99178, 103025e-9, 0, .00907209, .989265, 11154e-8, 0, .0135257, .986998, 136296e-9, 0, .0189327, .984137, 169154e-9, 0, .0252993, .979798, 196671e-9, 0, .0326272, .97337, 196678e-9, 0, .0409157, .967239, 223121e-9, 0, .0501623, .959543, 253809e-9, 0, .0603638, .949466, 265972e-9, 0, .0715171, .939074, 288372e-9, 0, .0836187, .931118, 310983e-9, 0, .0966657, .922525, 325561e-9, 0, .110656, .912983, 345725e-9, 0, .125588, .901617, 3556e-7, 0, .141461, .889487, 374012e-9, 0, .158275, .875787, 383445e-9, 0, .176031, .860654, 393972e-9, 0, .19473, .844417, 400311e-9, 0, .214374, .82741, 405004e-9, 0, .234967, .810545, 407378e-9, 0, .256512, .793312, 407351e-9, 0, .279011, .774847, 406563e-9, 0, .302468, .755621, 404903e-9, 0, .326887, .735511, 397486e-9, 0, .352266, .715435, 39357e-8, 0, .378605, .695403, 384739e-9, 0, .405897, .674681, 376108e-9, 0, .43413, .65359, 365997e-9, 0, .463277, .632471, 354957e-9, 0, .493295, .61151, 343593e-9, 0, .524106, .59064, 331841e-9, 0, .555561, .569386, 318891e-9, 0, .587302, .548785, 3072e-7, 0, .619048, .528146, 29361e-8, 0, .650794, .507872, 281709e-9, 0, .68254, .487805, 268627e-9, 0, .714286, .468196, 255887e-9, 0, .746032, .448922, 243997e-9, 0, .777778, .430093, 231662e-9, 0, .809524, .411845, 220339e-9, 0, .84127, .393808, 208694e-9, 0, .873016, .376615, 198045e-9, 0, .904762, .359655, 187375e-9, 0, .936508, .343452, 177371e-9, 0, .968254, .32765, 167525e-9, 0, 1, 1, 169351e-10, 0, 0, 1, 169356e-10, 0, 0, 1, 169427e-10, 0, 0, .999999, 169736e-10, 0, 0, .999998, 170575e-10, 0, 0, .999995, 172372e-10, 0, 0, .99999, 175739e-10, 0, 0, .999979, 181568e-10, 0, 0, .999966, 191206e-10, 0, 0, .999944, 20677e-9, 0, 0, .999912, 231644e-10, 0, 0, .999869, 271268e-10, 0, 0, .999811, 334272e-10, 0, 0, .99973, 433979e-10, 0, 0, .999617, 590083e-10, 0, 680315e-10, .999445, 829497e-10, 0, 612796e-9, .999138, 118019e-9, 0, .00187408, .998095, 156712e-9, 0, .00395791, .993919, 125054e-9, 0, .00692144, .991333, 126091e-9, 0, .0107962, .989226, 144912e-9, 0, .0155986, .986954, 175737e-9, 0, .0213364, .983982, 213883e-9, 0, .0280114, .979128, 234526e-9, 0, .0356226, .973327, 243725e-9, 0, .0441668, .967416, 2773e-7, 0, .0536399, .959729, 308799e-9, 0, .0640376, .949758, 322447e-9, 0, .0753554, .939173, 350021e-9, 0, .0875893, .9296, 370089e-9, 0, .100736, .921181, 391365e-9, 0, .114793, .91164, 413636e-9, 0, .129759, .900435, 427068e-9, 0, .145632, .888183, 441046e-9, 0, .162412, .874772, 454968e-9, 0, .180101, .859566, 461882e-9, 0, .1987, .843579, 471556e-9, 0, .218213, .826453, 474335e-9, 0, .238641, .809164, 477078e-9, 0, .259989, .792179, 47755e-8, 0, .282262, .773866, 472573e-9, 0, .305464, .754944, 469765e-9, 0, .329599, .735133, 462371e-9, 0, .35467, .714858, 453674e-9, 0, .380678, .694829, 443888e-9, 0, .407622, .674453, 432052e-9, 0, .435493, .653685, 420315e-9, 0, .464275, .632666, 406829e-9, 0, .493938, .611676, 392234e-9, 0, .524422, .591193, 379208e-9, 0, .555624, .570145, 36319e-8, 0, .587302, .549566, 349111e-9, 0, .619048, .529278, 334166e-9, 0, .650794, .509026, 318456e-9, 0, .68254, .489186, 30449e-8, 0, .714286, .469662, 289051e-9, 0, .746032, .450691, 275494e-9, 0, .777778, .431841, 261437e-9, 0, .809524, .413752, 247846e-9, 0, .84127, .395951, 235085e-9, 0, .873016, .378633, 222245e-9, 0, .904762, .36194, 210533e-9, 0, .936508, .345599, 198494e-9, 0, .968254, .329999, 188133e-9, 0, 1, 1, 269663e-10, 0, 0, 1, 26967e-9, 0, 0, 1, 269772e-10, 0, 0, .999999, 270214e-10, 0, 0, .999998, 271415e-10, 0, 0, .999994, 27398e-9, 0, 0, .999988, 278771e-10, 0, 0, .999977, 287019e-10, 0, 0, .999961, 300544e-10, 0, 0, .999937, 322138e-10, 0, 0, .999904, 356163e-10, 0, 0, .999854, 409465e-10, 0, 0, .99979, 492651e-10, 0, 0, .999699, 621722e-10, 0, 8.8288e-7, .999572, 819715e-10, 0, 223369e-9, .999381, 111689e-9, 0, .00105414, .999016, 153862e-9, 0, .0026493, .997437, 187667e-9, 0, .00508608, .993545, 155672e-9, 0, .00840554, .991135, 161455e-9, 0, .012629, .989157, 188241e-9, 0, .0177661, .986874, 226229e-9, 0, .0238198, .983714, 268668e-9, 0, .0307887, .978301, 277109e-9, 0, .0386688, .973227, 303446e-9, 0, .0474554, .967317, 341851e-9, 0, .0571428, .959477, 370885e-9, 0, .0677256, .950012, 392753e-9, 0, .0791988, .939484, 42781e-8, 0, .0915576, .928135, 443866e-9, 0, .104798, .919819, 472959e-9, 0, .118918, .910049, 491551e-9, 0, .133915, .899181, 512616e-9, 0, .149788, .886881, 523563e-9, 0, .166537, .87359, 540183e-9, 0, .184164, .858613, 547386e-9, 0, .202669, .842809, 554809e-9, 0, .222056, .825727, 558316e-9, 0, .242329, .808086, 557824e-9, 0, .263492, .790728, 556346e-9, 0, .285551, .772987, 552672e-9, 0, .30851, .7541, 543738e-9, 0, .332376, .734669, 536107e-9, 0, .357153, .714411, 523342e-9, 0, .382845, .694196, 512238e-9, 0, .409454, .674252, 497465e-9, 0, .436977, .65357, 481096e-9, 0, .465404, .632999, 467054e-9, 0, .494713, .611994, 448771e-9, 0, .524864, .591604, 431889e-9, 0, .555779, .571134, 415238e-9, 0, .587302, .550528, 396369e-9, 0, .619048, .530292, 379477e-9, 0, .650794, .510364, 361488e-9, 0, .68254, .490749, 343787e-9, 0, .714286, .471266, 327822e-9, 0, .746032, .452462, 310626e-9, 0, .777778, .433907, 295352e-9, 0, .809524, .415659, 279179e-9, 0, .84127, .398138, 264685e-9, 0, .873016, .380833, 249905e-9, 0, .904762, .364247, 236282e-9, 0, .936508, .348041, 222905e-9, 0, .968254, .332389, 210522e-9, 0, 1, 1, 420604e-10, 0, 0, 1, 420614e-10, 0, 0, 1, 420757e-10, 0, 0, .999999, 42138e-9, 0, 0, .999997, 423067e-10, 0, 0, .999993, 426668e-10, 0, 0, .999986, 433372e-10, 0, 0, .999974, 444857e-10, 0, 0, .999956, 463554e-10, 0, 0, .99993, 493105e-10, 0, 0, .999892, 539077e-10, 0, 0, .999838, 610005e-10, 0, 0, .999767, 718822e-10, 0, 0, .999666, 884581e-10, 0, 365471e-10, .999525, 113398e-9, 0, 485623e-9, .999311, 150043e-9, 0, .00162096, .998865, 200063e-9, 0, .00355319, .996278, 211014e-9, 0, .00633818, .992956, 189672e-9, 0, .0100043, .991017, 210262e-9, 0, .0145648, .989055, 244292e-9, 0, .0200237, .986741, 290481e-9, 0, .0263798, .983288, 334303e-9, 0, .033629, .977784, 340307e-9, 0, .0417652, .973037, 377864e-9, 0, .0507821, .967181, 4239e-7, 0, .060673, .958971, 443854e-9, 0, .0714314, .950093, 483039e-9, 0, .0830518, .939552, 517934e-9, 0, .0955288, .927678, 539449e-9, 0, .108859, .918278, 568604e-9, 0, .123038, .908449, 588505e-9, 0, .138065, .897713, 612473e-9, 0, .153938, .885533, 625575e-9, 0, .170657, .872131, 63854e-8, 0, .188224, .857517, 647034e-9, 0, .20664, .841796, 65209e-8, 0, .225909, .824726, 6544e-7, 0, .246035, .807297, 655744e-9, 0, .267022, .789058, 646716e-9, 0, .288878, .77189, 643898e-9, 0, .311607, .753082, 629973e-9, 0, .335216, .7341, 621564e-9, 0, .359713, .714094, 605171e-9, 0, .385103, .693839, 588752e-9, 0, .41139, .673891, 573294e-9, 0, .438576, .653565, 552682e-9, 0, .466656, .633326, 533446e-9, 0, .495617, .612582, 514635e-9, 0, .525431, .59205, 49303e-8, 0, .556041, .571918, 471842e-9, 0, .587338, .551572, 451713e-9, 0, .619048, .531553, 430049e-9, 0, .650794, .51175, 410445e-9, 0, .68254, .49238, 390098e-9, 0, .714286, .473143, 370033e-9, 0, .746032, .45423, 351205e-9, 0, .777778, .435963, 332049e-9, 0, .809524, .41787, 315021e-9, 0, .84127, .400387, 297315e-9, 0, .873016, .383332, 281385e-9, 0, .904762, .366665, 265397e-9, 0, .936508, .350633, 250601e-9, 0, .968254, .334964, 23589e-8, 0, 1, 1, 643736e-10, 0, 0, 1, 64375e-9, 0, 0, 1, 643947e-10, 0, 0, .999999, 64481e-9, 0, 0, .999997, 647143e-10, 0, 0, .999994, 652119e-10, 0, 0, .999985, 661359e-10, 0, 0, .999972, 677116e-10, 0, 0, .999952, 702599e-10, 0, 0, .999922, 742517e-10, 0, 0, .99988, 803906e-10, 0, 0, .99982, 897315e-10, 0, 0, .999741, 103838e-9, 0, 0, .999629, 12496e-8, 0, 149024e-9, .999474, 156161e-9, 0, 861027e-9, .999229, 201034e-9, 0, .00231198, .998662, 259069e-9, 0, .00458147, .995299, 245439e-9, 0, .00770895, .992732, 24498e-8, 0, .0117126, .990847, 273211e-9, 0, .0165989, .988911, 316492e-9, 0, .0223674, .98654, 37161e-8, 0, .0290135, .982636, 410352e-9, 0, .0365309, .977346, 421756e-9, 0, .0449117, .972909, 475578e-9, 0, .0541481, .966821, 522482e-9, 0, .0642326, .958686, 545008e-9, 0, .075158, .949754, 589286e-9, 0, .0869181, .939184, 619995e-9, 0, .0995074, .927505, 654266e-9, 0, .112922, .916606, 682362e-9, 0, .127157, .906707, 704286e-9, 0, .142212, .895937, 725909e-9, 0, .158085, .883913, 743939e-9, 0, .174776, .870642, 755157e-9, 0, .192287, .856241, 764387e-9, 0, .210619, .84069, 771032e-9, 0, .229775, .823728, 765906e-9, 0, .249761, .806481, 767604e-9, 0, .270582, .787924, 754385e-9, 0, .292243, .770588, 749668e-9, 0, .314753, .751991, 731613e-9, 0, .338118, .733407, 717655e-9, 0, .362347, .713688, 700604e-9, 0, .387447, .693595, 678765e-9, 0, .413424, .673426, 657042e-9, 0, .440284, .65359, 635892e-9, 0, .468027, .633576, 611569e-9, 0, .496645, .613144, 586011e-9, 0, .526122, .592711, 563111e-9, 0, .556417, .572722, 537699e-9, 0, .587451, .552762, 512556e-9, 0, .619048, .532985, 489757e-9, 0, .650794, .513219, 464139e-9, 0, .68254, .493992, 442193e-9, 0, .714286, .47509, 418629e-9, 0, .746032, .456287, 397045e-9, 0, .777778, .438152, 375504e-9, 0, .809524, .420294, 35492e-8, 0, .84127, .402749, 335327e-9, 0, .873016, .385879, 316422e-9, 0, .904762, .369352, 298333e-9, 0, .936508, .353301, 281417e-9, 0, .968254, .337781, 265203e-9, 0, 1, 1, 968267e-10, 0, 0, 1, 968284e-10, 0, 0, 1, 968556e-10, 0, 0, .999999, 969733e-10, 0, 0, .999997, 972913e-10, 0, 0, .999993, 979688e-10, 0, 0, .999984, 992239e-10, 0, 0, .999969, 101356e-9, 0, 0, .999946, 104784e-9, 0, 0, .999913, 110111e-9, 0, 0, .999868, 118217e-9, 0, 0, .999801, 130396e-9, 0, 0, .999712, 148523e-9, 0, 124907e-10, .999589, 175233e-9, 0, 355405e-9, .999416, 213999e-9, 0, .0013528, .999136, 268529e-9, 0, .00312557, .998367, 333088e-9, 0, .00573045, .994701, 304757e-9, 0, .00919397, .992497, 318031e-9, 0, .0135261, .990608, 353863e-9, 0, .0187278, .988715, 409044e-9, 0, .0247947, .986241, 472967e-9, 0, .0317196, .981696, 495104e-9, 0, .039494, .977097, 532873e-9, 0, .0481087, .972583, 594447e-9, 0, .0575549, .966142, 636867e-9, 0, .0678242, .95823, 669899e-9, 0, .0789089, .949677, 719499e-9, 0, .0908023, .939226, 750584e-9, 0, .103499, .927501, 793183e-9, 0, .116993, .915199, 81995e-8, 0, .131282, .90498, 847654e-9, 0, .146364, .894243, 868929e-9, 0, .162237, .882154, 884278e-9, 0, .178902, .869161, 898108e-9, 0, .196358, .854751, 901254e-9, 0, .21461, .839368, 90679e-8, 0, .23366, .822874, 901541e-9, 0, .253512, .805514, 897297e-9, 0, .274174, .78716, 881856e-9, 0, .29565, .769061, 870032e-9, 0, .31795, .751, 851719e-9, 0, .341081, .732614, 830671e-9, 0, .365053, .713171, 806569e-9, 0, .389874, .693472, 78338e-8, 0, .415553, .673528, 756404e-9, 0, .442098, .653397, 726872e-9, 0, .469512, .633781, 700494e-9, 0, .497794, .613877, 67105e-8, 0, .526935, .593506, 640361e-9, 0, .556908, .573667, 613502e-9, 0, .587657, .553932, 583177e-9, 0, .61906, .534345, 554375e-9, 0, .650794, .515042, 527811e-9, 0, .68254, .495674, 499367e-9, 0, .714286, .477132, 47429e-8, 0, .746032, .458609, 447726e-9, 0, .777778, .440354, 424205e-9, 0, .809524, .422765, 399549e-9, 0, .84127, .405472, 378315e-9, 0, .873016, .388482, 355327e-9, 0, .904762, .372191, 336122e-9, 0, .936508, .356099, 315247e-9, 0, .968254, .340737, 29794e-8, 0, 1, 1, 143327e-9, 0, 0, 1, 14333e-8, 0, 0, 1, 143366e-9, 0, 0, .999999, 143524e-9, 0, 0, .999996, 143952e-9, 0, 0, .999991, 144862e-9, 0, 0, .999981, 146544e-9, 0, 0, .999966, 149391e-9, 0, 0, .999941, 153946e-9, 0, 0, .999905, 160971e-9, 0, 0, .999852, 171562e-9, 0, 0, .99978, 18729e-8, 0, 0, .999681, 210386e-9, 0, 826239e-10, .999546, 243906e-9, 0, 664807e-9, .999352, 291739e-9, 0, .00196192, .999027, 357419e-9, 0, .00405941, .997886, 422349e-9, 0, .00699664, .99419, 385008e-9, 0, .0107896, .99214, 409775e-9, 0, .0154415, .990274, 456418e-9, 0, .0209488, .988455, 527008e-9, 0, .0273037, .985804, 597685e-9, 0, .0344969, .98103, 613124e-9, 0, .0425183, .976674, 668321e-9, 0, .0513575, .972021, 736985e-9, 0, .0610046, .965274, 773789e-9, 0, .0714508, .958046, 830852e-9, 0, .0826877, .949333, 875766e-9, 0, .0947085, .939135, 917088e-9, 0, .107507, .927119, 952244e-9, 0, .121078, .91469, 990626e-9, 0, .135419, .903006, .00101304, 0, .150526, .892368, .00103834, 0, .166399, .880231, .00105002, 0, .183038, .867432, .00106331, 0, .200443, .853208, .00106783, 0, .218618, .837956, .00106458, 0, .237566, .821772, .00105945, 0, .257291, .804328, .00104685, 0, .2778, .786465, .00103178, 0, .2991, .768004, .00101077, 0, .321199, .74972, 985504e-9, 0, .344106, .731682, 962893e-9, 0, .36783, .712813, 932146e-9, 0, .392383, .693139, 89871e-8, 0, .417774, .673566, 869678e-9, 0, .444013, .653483, 835525e-9, 0, .471107, .633891, 799853e-9, 0, .49906, .614433, 766838e-9, 0, .527869, .594586, 732227e-9, 0, .557517, .574769, 696442e-9, 0, .587966, .555149, 663935e-9, 0, .61913, .535898, 629826e-9, 0, .650794, .516753, 596486e-9, 0, .68254, .497816, 567078e-9, 0, .714286, .479034, 534399e-9, 0, .746032, .460975, 507013e-9, 0, .777778, .442935, 477421e-9, 0, .809524, .425263, 451101e-9, 0, .84127, .408248, 424964e-9, 0, .873016, .391339, 39993e-8, 0, .904762, .37513, 377619e-9, 0, .936508, .359172, 354418e-9, 0, .968254, .343876, 334823e-9, 0, 1, 1, 209042e-9, 0, 0, 1, 209045e-9, 0, 0, 1, 209093e-9, 0, 0, .999999, 209304e-9, 0, 0, .999996, 209871e-9, 0, 0, .999991, 211078e-9, 0, 0, .999979, 213304e-9, 0, 0, .999963, 217061e-9, 0, 0, .999933, 223042e-9, 0, 0, .999894, 232206e-9, 0, 0, .999837, 245901e-9, 0, 0, .999756, 266023e-9, 0, 102927e-11, .999648, 295204e-9, 0, 233468e-9, .999499, 336958e-9, 0, .00108237, .999283, 395563e-9, 0, .00268832, .998896, 473785e-9, 0, .00511138, .997006, 520008e-9, 0, .00837705, .993819, 497261e-9, 0, .0124928, .991632, 523722e-9, 0, .0174561, .989875, 587258e-9, 0, .0232596, .988109, 676329e-9, 0, .0298932, .985155, 747701e-9, 0, .0373453, .980479, 768803e-9, 0, .0456045, .976271, 841054e-9, 0, .0546593, .971347, 911469e-9, 0, .0644994, .964528, 953057e-9, 0, .0751152, .957632, .00102221, 0, .0864981, .948681, .00106122, 0, .0986407, .938716, .00111857, 0, .111537, .926629, .00114762, 0, .125182, .914025, .00118995, 0, .139571, .901026, .00121228, 0, .154703, .890358, .00123946, 0, .170576, .878283, .0012527, 0, .18719, .865459, .00125536, 0, .204547, .851407, .00126134, 0, .222648, .836276, .00124759, 0, .241498, .820436, .00124443, 0, .261101, .803253, .00122071, 0, .281465, .785562, .00120107, 0, .302595, .76718, .00117762, 0, .324501, .748551, .00114289, 0, .347192, .730564, .00110872, 0, .370679, .712253, .00107636, 0, .394973, .692867, .00103646, 0, .420085, .673695, 996793e-9, 0, .446027, .653912, 95675e-8, 0, .47281, .634129, 916739e-9, 0, .500441, .615004, 874401e-9, 0, .528921, .595587, 833411e-9, 0, .558244, .575965, 794556e-9, 0, .588384, .5566, 75196e-8, 0, .619281, .537428, 716381e-9, 0, .650795, .518623, 676558e-9, 0, .68254, .499964, 64074e-8, 0, .714286, .481356, 605984e-9, 0, .746032, .463279, 570256e-9, 0, .777778, .445673, 540138e-9, 0, .809524, .428032, 507299e-9, 0, .84127, .411112, 479553e-9, 0, .873016, .394444, 450737e-9, 0, .904762, .378247, 424269e-9, 0, .936508, .362415, 399111e-9, 0, .968254, .347103, 375274e-9, 0, 1, 1, 300729e-9, 0, 0, 1, 300733e-9, 0, 0, 1, 300797e-9, 0, 0, .999998, 301072e-9, 0, 0, .999996, 301817e-9, 0, 0, .999989, 303398e-9, 0, 0, .999977, 306309e-9, 0, 0, .999958, 311209e-9, 0, 0, .999927, 318975e-9, 0, 0, .999884, 330804e-9, 0, 0, .99982, 34834e-8, 0, 0, .999733, 373854e-9, 0, 326995e-10, .999613, 410424e-9, 0, 477174e-9, .999447, 462047e-9, 0, .00161099, .999204, 533322e-9, 0, .00353153, .998725, 624964e-9, 0, .00627965, .995871, 631786e-9, 0, .0098693, .993194, 632017e-9, 0, .0143011, .991541, 68923e-8, 0, .019568, .989773, 766892e-9, 0, .0256593, .987647, 863668e-9, 0, .0325625, .984193, 922089e-9, 0, .0402647, .980016, 970749e-9, 0, .0487532, .975859, .00106027, 0, .058016, .970514, .00112239, 0, .0680419, .963625, .00117212, 0, .0788208, .956959, .00125211, 0, .0903439, .947956, .00129411, 0, .102604, .93809, .00135879, 0, .115594, .92659, .00139309, 0, .129309, .913829, .00143253, 0, .143745, .90005, .00145809, 0, .158901, .888129, .0014748, 0, .174774, .87607, .00148756, 0, .191365, .863461, .00148714, 0, .208674, .849594, .00148892, 0, .226705, .834531, .00146496, 0, .245461, .81903, .0014579, 0, .264947, .802122, .00143039, 0, .28517, .78445, .00139717, 0, .306137, .766434, .00136312, 0, .327857, .747816, .00132597, 0, .350341, .729519, .00128323, 0, .373598, .711454, .00123803, 0, .397642, .692699, .00119097, 0, .422485, .673723, .00114565, 0, .448139, .654386, .00109552, 0, .474619, .634673, .00104553, 0, .501933, .615554, 99985e-8, 0, .530089, .596462, 948207e-9, 0, .559087, .577385, 902299e-9, 0, .588913, .558257, 856448e-9, 0, .619525, .5392, 810395e-9, 0, .650826, .520543, 768558e-9, 0, .68254, .502206, 7239e-7, 0, .714286, .48402, 685794e-9, 0, .746032, .465779, 64471e-8, 0, .777778, .448455, 609583e-9, 0, .809524, .431091, 57227e-8, 0, .84127, .414147, 54042e-8, 0, .873016, .39765, 506545e-9, 0, .904762, .381576, 477635e-9, 0, .936508, .365881, 448446e-9, 0, .968254, .350582, 421424e-9, 0, 1, 1, 427144e-9, 0, 0, 1, 427151e-9, 0, 0, 1, 427232e-9, 0, 0, .999998, 42759e-8, 0, 0, .999995, 428555e-9, 0, 0, .999988, 430603e-9, 0, 0, .999976, 434368e-9, 0, 0, .999952, 440688e-9, 0, 0, .999919, 450667e-9, 0, 0, .999871, 46578e-8, 0, 0, .999801, 488024e-9, 0, 0, .999704, 520092e-9, 0, 129791e-9, .999572, 565553e-9, 0, 821056e-9, .999389, 628906e-9, 0, .00225241, .999114, 714911e-9, 0, .00449109, .998488, 819218e-9, 0, .00756249, .995234, 80415e-8, 0, .0114716, .993021, 830181e-9, 0, .0162131, .991407, 902645e-9, 0, .021776, .989625, 996934e-9, 0, .0281471, .987064, .00109707, 0, .0353118, .983265, .00114353, 0, .0432562, .979535, .0012272, 0, .0519665, .975224, .00132642, 0, .0614298, .969574, .00138092, 0, .0716348, .963021, .00145896, 0, .0825709, .956046, .00152834, 0, .094229, .947136, .00158217, 0, .106602, .937313, .0016347, 0, .119682, .926073, .00168383, 0, .133465, .913121, .00171627, 0, .147947, .899165, .00174229, 0, .163125, .885891, .00176137, 0, .178998, .873783, .00176406, 0, .195566, .861331, .00176156, 0, .21283, .847569, .00175346, 0, .230793, .832785, .00172753, 0, .249459, .817442, .00170204, 0, .268832, .800613, .00166576, 0, .28892, .783597, .00162909, 0, .30973, .76571, .0015826, 0, .331271, .747021, .00153106, 0, .353554, .728593, .00148036, 0, .37659, .710661, .00142808, 0, .400391, .692426, .00136906, 0, .424973, .673623, .00131066, 0, .450347, .65494, .00125569, 0, .476531, .635448, .00119517, 0, .503535, .616221, .00113828, 0, .531372, .597531, .0010816, 0, .560047, .578795, .00102673, 0, .589554, .559892, 970985e-9, 0, .619869, .541307, 919773e-9, 0, .650923, .522608, 868479e-9, 0, .68254, .504484, 82137e-8, 0, .714286, .486603, 772916e-9, 0, .746032, .468802, 730353e-9, 0, .777778, .451172, 684955e-9, 0, .809524, .434348, 647565e-9, 0, .84127, .417445, 605863e-9, 0, .873016, .401077, 571885e-9, 0, .904762, .385039, 536034e-9, 0, .936508, .369483, 504227e-9, 0, .968254, .354272, 473165e-9, 0, 1, 1, 599525e-9, 0, 0, 1, 599533e-9, 0, 0, 1, 599639e-9, 0, 0, .999998, 600097e-9, 0, 0, .999994, 601336e-9, 0, 0, .999987, 603958e-9, 0, 0, .999972, 608775e-9, 0, 0, .999949, 616842e-9, 0, 0, .999912, 629534e-9, 0, 0, .999857, 648658e-9, 0, 0, .999781, 676615e-9, 0, 538873e-11, .999674, 716574e-9, 0, 308602e-9, .999528, 772641e-9, 0, .00127003, .999326, 849806e-9, 0, .00300783, .999009, 952682e-9, 0, .00556637, .998112, .00106394, 0, .00895889, .994496, .00102228, 0, .0131827, .992806, .00108586, 0, .0182277, .991211, .0011759, 0, .0240795, .989415, .00128955, 0, .030723, .986499, .00139038, 0, .0381418, .982679, .00144539, 0, .046321, .978839, .00153954, 0, .0552459, .974295, .00164417, 0, .0649034, .968784, .00171517, 0, .0752814, .962324, .00180282, 0, .0863693, .954956, .00186387, 0, .0981578, .94624, .00193817, 0, .110639, .936517, .00198156, 0, .123806, .925186, .00203042, 0, .137655, .91252, .0020664, 0, .15218, .898441, .00207822, 0, .16738, .884394, .0020992, 0, .183253, .871273, .00208748, 0, .199799, .859057, .00208686, 0, .21702, .845243, .00205519, 0, .234918, .830723, .00202868, 0, .253496, .815801, .00199501, 0, .272761, .79914, .00194193, 0, .292719, .782372, .00188824, 0, .313377, .76482, .00183695, 0, .334745, .746586, .00177418, 0, .356833, .7281, .00170628, 0, .379654, .709842, .00164063, 0, .403221, .692019, .00157355, 0, .427548, .67364, .00150262, 0, .452651, .655277, .00143473, 0, .478545, .636438, .00136371, 0, .505246, .617364, .00129911, 0, .532768, .598603, .00123014, 0, .561122, .580195, .00116587, 0, .590309, .561786, .00110398, 0, .620318, .543377, .00104148, 0, .651102, .525093, 983984e-9, 0, .682545, .506791, 92667e-8, 0, .714286, .489291, 874326e-9, 0, .746032, .471811, 821734e-9, 0, .777778, .454435, 774698e-9, 0, .809524, .437493, 727302e-9, 0, .84127, .420977, 684039e-9, 0, .873016, .404729, 64373e-8, 0, .904762, .388756, 60285e-8, 0, .936508, .373344, 56765e-8, 0, .968254, .358191, 531929e-9, 0, 1, 1, 832169e-9, 0, 0, 1, 832178e-9, 0, 0, 1, 83231e-8, 0, 0, .999998, 832893e-9, 0, 0, .999995, 834465e-9, 0, 0, .999985, 837791e-9, 0, 0, .999969, 843893e-9, 0, 0, .999944, 854086e-9, 0, 0, .999903, 870071e-9, 0, 0, .999843, 894042e-9, 0, 0, .999759, 928865e-9, 0, 531805e-10, .999643, 978242e-9, 0, 579365e-9, .99948, .00104684, 0, .00182774, .999255, .00114012, 0, .00387804, .998885, .00126188, 0, .00675709, .997405, .00135888, 0, .010468, .99424, .00133626, 0, .0150018, .992458, .00140905, 0, .0203443, .990929, .00152305, 0, .0264786, .989116, .00165882, 0, .0333875, .985624, .00174128, 0, .0410536, .982003, .00182108, 0, .0494609, .978336, .00194498, 0, .0585941, .973184, .00202708, 0, .0684396, .9678, .00212166, 0, .0789851, .961348, .00221366, 0, .0902199, .953841, .00228219, 0, .102134, .94534, .00235662, 0, .114721, .935552, .00240572, 0, .127972, .924064, .00244405, 0, .141884, .911827, .00247557, 0, .156451, .897731, .00248374, 0, .171672, .883409, .00249863, 0, .187545, .868625, .00246688, 0, .20407, .856529, .00246523, 0, .221249, .842999, .00242368, 0, .239083, .828505, .00237354, 0, .257578, .813825, .00232588, 0, .276738, .797813, .00226731, 0, .296569, .781097, .00219704, 0, .31708, .764038, .00212394, 0, .338281, .746067, .00204786, 0, .360181, .727687, .00196728, 0, .382794, .709571, .00188779, 0, .406133, .691503, .00180532, 0, .430213, .673673, .00171849, 0, .45505, .655732, .00164147, 0, .480662, .637399, .00155858, 0, .507065, .618616, .00147641, 0, .534278, .60005, .00140125, 0, .562313, .581713, .00132441, 0, .59118, .563546, .00125014, 0, .620875, .545605, .00118249, 0, .651373, .527559, .0011116, 0, .682593, .509764, .00104979, 0, .714286, .49193, 985977e-9, 0, .746032, .475011, 928592e-9, 0, .777778, .457878, 873466e-9, 0, .809524, .440979, 819585e-9, 0, .84127, .424613, 772365e-9, 0, .873016, .408549, 722195e-9, 0, .904762, .392771, 680014e-9, 0, .936508, .377317, 636797e-9, 0, .968254, .362352, 598318e-9, 0, 1, 1, .00114313, 0, 0, 1, .00114314, 0, 0, .999999, .00114331, 0, 0, .999998, .00114404, 0, 0, .999994, .00114601, 0, 0, .999984, .00115019, 0, 0, .999967, .00115784, 0, 0, .999937, .0011706, 0, 0, .999894, .00119054, 0, 0, .999828, .00122031, 0, 0, .999735, .00126331, 0, 169263e-9, .999606, .00132382, 0, 949167e-9, .999426, .0014071, 0, .00249668, .999173, .00151895, 0, .00486392, .99873, .00166102, 0, .00806323, .996243, .0017023, 0, .0120895, .993779, .00172782, 0, .0169288, .9919, .0018108, 0, .0225633, .990524, .00196028, 0, .028974, .98868, .00212014, 0, .036142, .984663, .00217598, 0, .044049, .981457, .00230563, 0, .0526781, .977608, .00243966, 0, .0620137, .972215, .00251336, 0, .0720418, .966798, .0026285, 0, .0827499, .960241, .00271409, 0, .0941271, .952489, .00278381, 0, .106164, .944127, .00285399, 0, .118852, .934282, .00290994, 0, .132185, .923271, .00294558, 0, .146157, .910803, .00296269, 0, .160766, .896705, .00296803, 0, .176007, .88238, .00296637, 0, .19188, .867116, .00293163, 0, .208385, .853636, .00289418, 0, .225523, .840469, .00284663, 0, .243296, .82639, .00278594, 0, .261709, .811759, .00271618, 0, .280767, .796113, .00263187, 0, .300476, .779518, .00254589, 0, .320845, .763142, .00246003, 0, .341883, .745464, .00236529, 0, .363601, .727491, .00226536, 0, .386011, .709414, .00216375, 0, .409128, .691396, .00207127, 0, .432967, .67368, .00197106, 0, .457545, .656049, .00187022, 0, .482881, .638188, .00177605, 0, .508992, .620177, .00168482, 0, .535899, .601506, .00158909, 0, .563619, .58362, .00150583, 0, .592165, .565496, .00141791, 0, .621544, .54789, .00133693, 0, .651743, .530323, .00126038, 0, .682709, .512795, .00118556, 0, .714286, .495199, .00111527, 0, .746032, .478101, .0010489, 0, .777778, .461511, 984264e-9, 0, .809524, .444879, 92591e-8, 0, .84127, .428424, 866582e-9, 0, .873016, .412495, 814463e-9, 0, .904762, .396975, 764498e-9, 0, .936508, .381614, 715967e-9, 0, .968254, .366732, 672483e-9, 0, 1, 1, .00155501, 0, 0, 1, .00155503, 0, 0, 1, .00155524, 0, 0, .999998, .00155615, 0, 0, .999994, .0015586, 0, 0, .999983, .00156379, 0, 0, .999963, .0015733, 0, 0, .999932, .00158911, 0, 0, .999882, .00161376, 0, 0, .99981, .00165041, 0, 100875e-10, .999708, .00170304, 0, 367658e-9, .999565, .00177658, 0, .0014234, .999368, .00187688, 0, .00327939, .999081, .00200989, 0, .00596629, .99852, .00217177, 0, .0094852, .99549, .0021745, 0, .013824, .993252, .00222357, 0, .0189642, .991727, .00235022, 0, .0248856, .989951, .00250561, 0, .0315669, .988029, .00268829, 0, .0389882, .984029, .0027496, 0, .0471302, .980683, .00289793, 0, .0559754, .976554, .00303315, 0, .0655081, .97139, .00313257, 0, .0757138, .965544, .00323656, 0, .08658, .95912, .00333432, 0, .0980954, .951183, .0034039, 0, .110251, .942974, .00347515, 0, .123038, .932642, .00350381, 0, .13645, .922158, .00354519, 0, .150482, .909404, .00353851, 0, .165129, .896071, .0035435, 0, .18039, .881206, .00349936, 0, .196263, .866077, .00347256, 0, .212748, .85093, .003415, 0, .229847, .837703, .00333367, 0, .247561, .823878, .003249, 0, .265895, .809449, .00316347, 0, .284854, .794379, .00306351, 0, .304445, .778138, .0029499, 0, .324675, .761997, .00284099, 0, .345555, .744938, .00272104, 0, .367095, .727212, .00260715, 0, .389309, .709549, .00248855, 0, .41221, .691704, .00236783, 0, .435814, .673689, .00225178, 0, .460138, .656453, .00213765, 0, .485203, .639128, .00202178, 0, .511028, .621512, .00191443, 0, .537634, .603598, .00180977, 0, .565041, .58559, .00170456, 0, .593268, .567852, .00160927, 0, .622327, .5503, .00151395, 0, .652217, .533033, .00142499, 0, .682907, .515942, .00133955, 0, .714296, .498814, .0012602, 0, .746032, .481595, .00118188, 0, .777778, .465117, .00111171, 0, .809524, .448865, .00104091, 0, .84127, .432711, 976618e-9, 0, .873016, .416822, 91859e-8, 0, .904762, .401272, 857704e-9, 0, .936508, .386226, 807172e-9, 0, .968254, .371321, 75464e-8, 0, 1, 1, .00209596, 0, 0, 1, .00209598, 0, 0, 1, .00209624, 0, 0, .999997, .00209736, 0, 0, .999991, .00210039, 0, 0, .999979, .00210678, 0, 0, .999959, .00211847, 0, 0, .999925, .0021379, 0, 0, .99987, .00216809, 0, 0, .999791, .00221281, 0, 681487e-10, .999677, .00227669, 0, 658161e-9, .999521, .00236533, 0, .00200635, .999301, .00248514, 0, .0041779, .998977, .00264185, 0, .00718648, .998191, .00281695, 0, .0110239, .994801, .00278518, 0, .015672, .993091, .00288774, 0, .0211091, .991571, .00303931, 0, .0273123, .9897, .00321643, 0, .034259, .987023, .00337332, 0, .0419282, .983289, .00346146, 0, .0502998, .979892, .00363704, 0, .0593562, .975111, .00373601, 0, .069081, .970351, .0038842, 0, .0794598, .964131, .00397053, 0, .0904798, .957747, .00408078, 0, .10213, .949536, .00413533, 0, .1144, .941372, .00420305, 0, .127284, .931049, .00422815, 0, .140772, .920647, .00425048, 0, .154862, .908033, .0042281, 0, .169548, .895028, .00422026, 0, .184828, .879968, .00415042, 0, .200701, .864875, .00408821, 0, .217167, .84918, .00400909, 0, .234227, .834934, .00391178, 0, .251884, .821397, .00380066, 0, .270141, .807135, .00367974, 0, .289004, .792363, .00355172, 0, .308479, .776661, .003411, 0, .328575, .760705, .00328123, 0, .349301, .744408, .00314003, 0, .370668, .726994, .0029906, 0, .392689, .709598, .00285034, 0, .415379, .692112, .00271179, 0, .438754, .674435, .00257185, 0, .46283, .65676, .00243425, 0, .48763, .639982, .00230351, 0, .513173, .622983, .0021777, 0, .539482, .605471, .00204991, 0, .566579, .58796, .00193759, 0, .594488, .570463, .00181976, 0, .623226, .553058, .00171497, 0, .6528, .535894, .00161109, 0, .683198, .519089, .00151394, 0, .714354, .502454, .00142122, 0, .746032, .485681, .00133488, 0, .777778, .468935, .00124975, 0, .809524, .452951, .00117309, 0, .84127, .437139, .00110155, 0, .873016, .421446, .00103124, 0, .904762, .405951, 966387e-9, 0, .936508, .391003, 908119e-9, 0, .968254, .376198, 848057e-9, 0, 1, 1, .00280076, 0, 0, 1, .00280078, 0, 0, .999999, .00280109, 0, 0, .999997, .00280246, 0, 0, .999992, .00280616, 0, 0, .999979, .00281396, 0, 0, .999956, .00282822, 0, 0, .999916, .00285186, 0, 0, .999857, .0028885, 0, 0, .999768, .00294259, 0, 196026e-9, .999645, .00301946, 0, .00104842, .99947, .00312541, 0, .00270199, .999229, .00326733, 0, .00519449, .998852, .00344992, 0, .00852602, .997558, .00361052, 0, .0126804, .994417, .0035898, 0, .017635, .992824, .00372393, 0, .023365, .991344, .00390695, 0, .0298456, .989337, .00410392, 0, .0370529, .985811, .00420987, 0, .0449651, .982772, .00437488, 0, .0535615, .979001, .00455069, 0, .0628243, .974102, .00464462, 0, .0727368, .969197, .00480577, 0, .0832844, .962759, .00487818, 0, .0944545, .956207, .00498176, 0, .106236, .947909, .00503392, 0, .118619, .939596, .00507474, 0, .131595, .929642, .00509798, 0, .145159, .918807, .00508476, 0, .159305, .906921, .00505634, 0, .174028, .893312, .00498845, 0, .189327, .878933, .0049133, 0, .2052, .863986, .0048259, 0, .221647, .847936, .00470848, 0, .23867, .832253, .00456889, 0, .25627, .818619, .00442726, 0, .274453, .804788, .00427677, 0, .293222, .790241, .00411906, 0, .312585, .775162, .00394833, 0, .33255, .759463, .00377366, 0, .353126, .743598, .00361026, 0, .374324, .72697, .00343627, 0, .396158, .709646, .00326422, 0, .418641, .69277, .00309717, 0, .44179, .675371, .0029356, 0, .465624, .657863, .00277712, 0, .490163, .640772, .00261738, 0, .515429, .624441, .0024737, 0, .541445, .607497, .00233125, 0, .568236, .590438, .00218994, 0, .595828, .573224, .0020664, 0, .624242, .556168, .00193526, 0, .653496, .539232, .00182463, 0, .683588, .522352, .00170735, 0, .714482, .506172, .00160555, 0, .746032, .489842, .00150451, 0, .777778, .473463, .00140938, 0, .809524, .457266, .00132568, 0, .84127, .441609, .0012376, 0, .873016, .426348, .00116265, 0, .904762, .411002, .00108935, 0, .936508, .396045, .00101946, 0, .968254, .381448, 955665e-9, 0, 1, 1, .0037121, 0, 0, 1, .00371213, 0, 0, 1, .00371251, 0, 0, .999997, .00371417, 0, 0, .99999, .00371863, 0, 0, .999977, .00372807, 0, 0, .99995, .00374529, 0, 0, .999908, .0037738, 0, 0, .999843, .00381789, 0, 123596e-10, .999745, .00388273, 0, 407442e-9, .999608, .00397443, 0, .0015447, .999415, .00409998, 0, .00351385, .999143, .00426662, 0, .0063316, .9987, .00447625, 0, .00998679, .996363, .00455323, 0, .0144569, .994021, .00461052, 0, .0197151, .992372, .00476359, 0, .0257344, .991007, .00499101, 0, .0324882, .988767, .0051972, 0, .0399517, .984872, .00528407, 0, .0481022, .982004, .00548926, 0, .0569191, .977714, .00564385, 0, .0663839, .973076, .0057693, 0, .0764801, .967565, .0058924, 0, .0871928, .961384, .00599629, 0, .0985095, .954435, .00605998, 0, .110419, .946303, .0061133, 0, .122912, .937662, .00612028, 0, .13598, .927867, .00612209, 0, .149617, .916475, .00604813, 0, .163817, .90541, .00603088, 0, .178577, .891591, .00592218, 0, .193894, .877573, .00578854, 0, .209767, .862511, .00566648, 0, .226196, .846861, .00551481, 0, .243182, .83068, .00533754, 0, .260728, .815725, .00515487, 0, .278837, .802321, .0049655, 0, .297515, .787826, .00475421, 0, .316768, .773454, .00456002, 0, .336605, .758224, .00434727, 0, .357034, .74265, .00414444, 0, .378067, .726729, .00393738, 0, .399717, .710155, .00373575, 0, .421998, .693312, .00353736, 0, .444928, .67653, .00334368, 0, .468523, .659444, .00315981, 0, .492806, .642051, .00297809, 0, .517798, .625758, .00280592, 0, .543525, .609615, .00264254, 0, .570012, .592919, .00248459, 0, .597288, .576298, .00233327, 0, .625379, .559489, .00219519, 0, .654307, .542891, .00205441, 0, .684084, .526255, .00193385, 0, .714693, .509853, .00180745, 0, .746044, .494131, .00169817, 0, .777778, .478114, .0015913, 0, .809524, .462274, .00148981, 0, .84127, .446412, .00139537, 0, .873016, .431274, .00130984, 0, .904762, .41635, .00122403, 0, .936508, .401476, .00114809, 0, .968254, .386993, .00107563, 0, 1, 1, .00488216, 0, 0, 1, .0048822, 0, 0, 1, .00488265, 0, 0, .999997, .00488463, 0, 0, .999988, .00488999, 0, 0, .999974, .00490129, 0, 0, .999946, .00492191, 0, 0, .999897, .00495598, 0, 0, .999825, .00500855, 0, 744791e-10, .999718, .00508559, 0, 712744e-9, .999565, .005194, 0, .00215249, .999352, .00534147, 0, .00444576, .999046, .00553523, 0, .00759218, .998492, .00577016, 0, .0115714, .995564, .00578487, 0, .0163557, .993339, .00586414, 0, .021915, .991834, .00606002, 0, .0282201, .990496, .00633312, 0, .0352433, .987826, .00651941, 0, .042959, .98383, .00660842, 0, .0513439, .98109, .00685523, 0, .0603772, .976131, .00695778, 0, .0700402, .971922, .00714236, 0, .0803163, .965901, .00721437, 0, .0911908, .959606, .00732017, 0, .102651, .952504, .00735788, 0, .114686, .944365, .00738493, 0, .127286, .935652, .00737969, 0, .140443, .925813, .00733612, 0, .154151, .914397, .00723094, 0, .168405, .903257, .00714002, 0, .183201, .890015, .00700149, 0, .198536, .876014, .00682813, 0, .214409, .861436, .00665567, 0, .23082, .845752, .00644526, 0, .24777, .829169, .00621635, 0, .265263, .813435, .00597789, 0, .283301, .799701, .00575694, 0, .301889, .785726, .00549866, 0, .321035, .77152, .0052503, 0, .340746, .75683, .00499619, 0, .361032, .741951, .0047543, 0, .381904, .726367, .0045084, 0, .403374, .710537, .00426784, 0, .425457, .693965, .00403487, 0, .448169, .677724, .0038075, 0, .47153, .66117, .00359431, 0, .495561, .644274, .00338354, 0, .520284, .627449, .00318163, 0, .545725, .611645, .00299672, 0, .571911, .595614, .00281016, 0, .598873, .579426, .00264252, 0, .62664, .563016, .00247509, 0, .655239, .546728, .00232647, 0, .684692, .530539, .00217803, 0, .714999, .514164, .00204216, 0, .746106, .498344, .00191403, 0, .777778, .482957, .00179203, 0, .809524, .467336, .00167695, 0, .84127, .451994, .00157567, 0, .873016, .436514, .00147113, 0, .904762, .42178, .00138034, 0, .936508, .407271, .00129219, 0, .968254, .392822, .0012098, 0, 1, 1, .00637427, 0, 0, 1, .00637431, 0, 0, .999999, .00637485, 0, 0, .999996, .00637721, 0, 0, .999987, .00638357, 0, 0, .999971, .006397, 0, 0, .999939, .00642142, 0, 0, .999888, .00646177, 0, 0, .999807, .00652387, 0, 207916e-9, .999689, .00661454, 0, .00112051, .99952, .00674155, 0, .00287719, .999283, .00691313, 0, .00550145, .998936, .00713598, 0, .00897928, .998165, .00738501, 0, .0132829, .994847, .00734388, 0, .01838, .993182, .00749991, 0, .0242381, .991665, .0077246, 0, .030826, .989708, .00797579, 0, .0381152, .986663, .00813011, 0, .0460794, .983288, .00830365, 0, .0546951, .980104, .00853496, 0, .0639411, .974855, .00861045, 0, .0737988, .97045, .00879133, 0, .0842516, .964509, .00886377, 0, .0952848, .957594, .00890346, 0, .106886, .950546, .00893289, 0, .119044, .942225, .00890074, 0, .131749, .933365, .00886826, 0, .144994, .923202, .0087316, 0, .158772, .912605, .00863082, 0, .173078, .901099, .00847403, 0, .187908, .888177, .00825838, 0, .203261, .873955, .00801834, 0, .219134, .860091, .00779026, 0, .235527, .84434, .00752478, 0, .252443, .828517, .00724074, 0, .269883, .81239, .00693769, 0, .287851, .79721, .00664817, 0, .306352, .783489, .00634763, 0, .325393, .769514, .00604221, 0, .344981, .755419, .00573568, 0, .365126, .741083, .00544359, 0, .385839, .726059, .00515515, 0, .407132, .710809, .00487139, 0, .42902, .695052, .00459846, 0, .45152, .678886, .00433412, 0, .474651, .663042, .00407981, 0, .498433, .646634, .00384264, 0, .52289, .630117, .00360897, 0, .548048, .613804, .00338863, 0, .573936, .598338, .00318486, 0, .600584, .582687, .00298377, 0, .628027, .566809, .00280082, 0, .656295, .550817, .00262255, 0, .685417, .534937, .00245835, 0, .715406, .519151, .00230574, 0, .74624, .503118, .0021549, 0, .777778, .487723, .00202008, 0, .809524, .472725, .00189355, 0, .84127, .457599, .00177108, 0, .873016, .442558, .00165843, 0, .904762, .427624, .00155494, 0, .936508, .413171, .00145273, 0, .968254, .399122, .00136454, 0, 1, 1, .00826496, 0, 0, 1, .00826499, 0, 0, 1, .00826564, 0, 0, .999996, .00826842, 0, 0, .999987, .00827589, 0, 0, .999967, .00829167, 0, 0, .999933, .00832037, 0, 0, .999876, .00836768, 0, 109338e-10, .999786, .00844031, 0, 427145e-9, .999655, .00854603, 0, .0016384, .999468, .00869337, 0, .00372392, .999203, .008891, 0, .00668513, .998803, .00914387, 0, .0104968, .99748, .00935838, 0, .015125, .994446, .00933309, 0, .0205338, .99292, .00953084, 0, .0266884, .991414, .0097893, 0, .0335565, .989049, .0100228, 0, .0411086, .98582, .0101664, 0, .0493181, .982441, .0103582, 0, .0581613, .978595, .0105292, 0, .0676169, .973495, .0106274, 0, .0776661, .968405, .0107261, 0, .0882926, .962717, .0108234, 0, .0994817, .955478, .0108102, 0, .111221, .948275, .0107914, 0, .123499, .940006, .0107161, 0, .136308, .930831, .0106309, 0, .149639, .920648, .0104083, 0, .163485, .910205, .0102312, 0, .177843, .898445, .0100051, 0, .192707, .885986, .00971928, 0, .208077, .872204, .00940747, 0, .22395, .858436, .0091085, 0, .240326, .843454, .00876595, 0, .257208, .827437, .00839794, 0, .274596, .811488, .00803692, 0, .292496, .796039, .00767352, 0, .310911, .781083, .0073097, 0, .329849, .767642, .00694032, 0, .349316, .753901, .00657476, 0, .369323, .740131, .00622699, 0, .38988, .725845, .0058838, 0, .410999, .710991, .00555586, 0, .432696, .696002, .00523089, 0, .454987, .680461, .00492494, 0, .47789, .664875, .00463464, 0, .501426, .649273, .00435422, 0, .52562, .63302, .0040875, 0, .550498, .61705, .00384075, 0, .576089, .601154, .00359557, 0, .602427, .586008, .00337636, 0, .629544, .570699, .00316019, 0, .657479, .555166, .00296033, 0, .686264, .539645, .00277552, 0, .715924, .524159, .00259499, 0, .746459, .508682, .00243257, 0, .777789, .493163, .00227851, 0, .809524, .478004, .00213083, 0, .84127, .46347, .00199502, 0, .873016, .448778, .00186967, 0, .904762, .434105, .00174732, 0, .936508, .419576, .00163861, 0, .968254, .405541, .00153341, 0, 1, 1, .0106462, 0, 0, 1, .0106462, 0, 0, .999999, .010647, 0, 0, .999995, .0106502, 0, 0, .999985, .0106589, 0, 0, .999964, .0106773, 0, 0, .999925, .0107106, 0, 0, .999861, .0107655, 0, 712986e-10, .999763, .0108497, 0, 743959e-9, .999616, .0109716, 0, .00227361, .999408, .0111408, 0, .0046983, .999112, .0113659, 0, .00800158, .998637, .0116475, 0, .0121493, .996223, .0117231, 0, .0171023, .994006, .0118064, 0, .0228218, .992444, .0120254, 0, .0292711, .991028, .0123314, 0, .036417, .98803, .0124954, 0, .0442295, .984816, .0126538, 0, .0526815, .981399, .0128537, 0, .0617492, .977085, .0129694, 0, .0714114, .972154, .013091, 0, .0816495, .966617, .0131166, 0, .0924472, .960628, .0131583, 0, .10379, .953295, .0131094, 0, .115665, .94575, .0129966, 0, .128062, .937654, .0128796, 0, .140972, .927716, .0126477, 0, .154387, .917932, .0123889, 0, .168301, .907719, .012131, 0, .182709, .89584, .0118013, 0, .197608, .883526, .0114145, 0, .212994, .870301, .0110075, 0, .228867, .856272, .0106019, 0, .245227, .842251, .0101938, 0, .262074, .826466, .00973254, 0, .279412, .810859, .0092846, 0, .297244, .795051, .00883304, 0, .315575, .780053, .00840272, 0, .334412, .76575, .00796438, 0, .35376, .752298, .00752526, 0, .373631, .739153, .00711486, 0, .394034, .725514, .00670361, 0, .414983, .711473, .00632656, 0, .436491, .696936, .00595206, 0, .458575, .682126, .00559191, 0, .481253, .667027, .00525362, 0, .504547, .651875, .00493805, 0, .528481, .636463, .00462848, 0, .553081, .620641, .00433936, 0, .578377, .604931, .00407, 0, .604404, .589549, .00380864, 0, .631197, .574712, .00357049, 0, .658795, .559775, .00334466, 0, .687238, .544514, .00312505, 0, .716559, .529555, .00293199, 0, .746776, .514402, .00274204, 0, .777849, .499302, .00256647, 0, .809524, .484114, .00239901, 0, .84127, .469308, .00225148, 0, .873016, .455133, .00210178, 0, .904762, .440939, .0019727, 0, .936508, .426627, .00184382, 0, .968254, .412509, .00172548, 0, 1, 1, .013628, 0, 0, 1, .0136281, 0, 0, .999999, .0136289, 0, 0, .999995, .0136327, 0, 0, .999983, .0136427, 0, 0, .99996, .0136638, 0, 0, .999917, .0137022, 0, 0, .999846, .0137652, 0, 204597e-9, .999736, .0138615, 0, .00116837, .999573, .0140007, 0, .00303325, .99934, .0141927, 0, .00580613, .999004, .0144457, 0, .00945626, .998407, .0147489, 0, .0139421, .995464, .014731, 0, .0192202, .993328, .0148283, 0, .0252495, .991799, .0150797, 0, .0319921, .990397, .0154316, 0, .0394138, .986835, .0155005, 0, .0474843, .983938, .0157308, 0, .0561763, .980154, .0158753, 0, .0654661, .975659, .0159581, 0, .0753326, .970171, .0159832, 0, .0857571, .964803, .0160084, 0, .0967236, .958366, .0159484, 0, .108218, .950613, .0158001, 0, .120227, .942874, .0155845, 0, .132741, .935005, .0154292, 0, .145751, .924991, .0150742, 0, .159249, .914814, .0146757, 0, .17323, .904743, .0143097, 0, .187687, .893216, .0138695, 0, .202619, .880769, .0133706, 0, .218021, .868136, .0128606, 0, .233894, .85469, .0123403, 0, .250238, .840593, .0118091, 0, .267052, .825808, .011253, 0, .284341, .81009, .0107099, 0, .302106, .79504, .0101636, 0, .320354, .779757, .00964041, 0, .33909, .764697, .00911896, 0, .358322, .750913, .00859533, 0, .378059, .738175, .00811592, 0, .398311, .725242, .00764504, 0, .41909, .711864, .00718885, 0, .440412, .698009, .00675843, 0, .462292, .683841, .00634984, 0, .484748, .669391, .00595502, 0, .507802, .654731, .00558671, 0, .531477, .639805, .00523578, 0, .555802, .624789, .00490834, 0, .580805, .609325, .00459448, 0, .606522, .593975, .00430342, 0, .63299, .578983, .00403019, 0, .66025, .564442, .0037707, 0, .688346, .549835, .0035316, 0, .717319, .535039, .00330255, 0, .7472, .520403, .00308932, 0, .777982, .505687, .00289335, 0, .809524, .490939, .00270818, 0, .84127, .476233, .0025343, 0, .873016, .461624, .00237097, 0, .904762, .447833, .00222065, 0, .936508, .433992, .00207561, 0, .968254, .420147, .00194955, 0, 1, 1, .0173415, 0, 0, 1, .0173416, 0, 0, .999999, .0173426, 0, 0, .999995, .0173468, 0, 0, .999983, .0173582, 0, 0, .999954, .0173822, 0, 0, .999908, .0174258, 0, 669501e-11, .999828, .0174973, 0, 427399e-9, .999705, .0176063, 0, .00171019, .999524, .0177631, 0, .0039248, .999263, .0179781, 0, .00705382, .998878, .018258, 0, .0110552, .998012, .0185551, 0, .0158812, .994614, .0184264, 0, .0214852, .993132, .0186385, 0, .0278239, .991563, .0189067, 0, .0348585, .989298, .0191577, 0, .0425544, .986036, .0192522, 0, .050881, .982558, .0194063, 0, .059811, .978531, .019486, 0, .0693209, .974198, .0195847, 0, .0793895, .968148, .0194749, 0, .0899984, .962565, .0194277, 0, .101132, .956041, .0192991, 0, .112775, .947749, .0189893, 0, .124917, .94018, .018704, 0, .137547, .93165, .0183458, 0, .150655, .921798, .0178775, 0, .164236, .911573, .0173618, 0, .178281, .901569, .0168482, 0, .192788, .890341, .016265, 0, .207752, .877835, .0156199, 0, .223171, .865472, .0149516, 0, .239044, .852905, .0143274, 0, .255371, .838906, .0136643, 0, .272153, .824888, .0129903, 0, .289393, .809977, .0123218, 0, .307093, .794697, .0116572, 0, .325259, .780028, .0110307, 0, .343896, .765124, .0104236, 0, .363012, .750411, .0098219, 0, .382617, .737264, .00924397, 0, .402719, .724799, .00868719, 0, .423332, .712253, .00816476, 0, .444469, .699267, .00767262, 0, .466146, .685618, .00719746, 0, .488383, .671736, .00673916, 0, .511199, .657777, .00631937, 0, .534618, .643497, .00592411, 0, .558668, .62889, .00553928, 0, .58338, .614299, .0051934, 0, .608787, .599197, .00485985, 0, .634929, .584175, .00454357, 0, .661849, .569541, .00425787, 0, .689594, .555193, .00397905, 0, .718211, .540947, .00372364, 0, .747742, .526593, .00348599, 0, .778205, .512335, .00326103, 0, .80953, .498017, .00305137, 0, .84127, .483609, .00285485, 0, .873016, .469368, .00267472, 0, .904762, .455037, .00249945, 0, .936508, .441493, .00234792, 0, .968254, .428147, .00219936, 0, 1, 1, .0219422, 0, 0, 1, .0219423, 0, 0, .999998, .0219434, 0, 0, .999993, .0219481, 0, 0, .999981, .021961, 0, 0, .999949, .0219879, 0, 0, .999896, .0220367, 0, 593194e-10, .999808, .0221167, 0, 75364e-8, .99967, .0222383, 0, .00237884, .999466, .0224125, 0, .00495612, .999174, .0226495, 0, .00844887, .998725, .0229525, 0, .0128058, .996979, .0231123, 0, .0179742, .994317, .0230742, 0, .0239047, .992781, .0232895, 0, .0305526, .991191, .0235734, 0, .0378786, .987787, .0236152, 0, .0458475, .985092, .0237994, 0, .0544287, .981121, .0238553, 0, .0635952, .976924, .0238706, 0, .0733233, .97218, .0238704, 0, .0835922, .965956, .0236598, 0, .0943839, .959998, .0234735, 0, .105682, .953245, .0232277, 0, .117474, .944445, .0226973, 0, .129747, .937087, .0223527, 0, .142491, .928341, .0218144, 0, .155697, .9184, .0211516, 0, .169358, .907959, .0204553, 0, .183469, .89808, .0197673, 0, .198024, .887047, .0189915, 0, .21302, .875221, .0182082, 0, .228455, .86269, .0173584, 0, .244329, .850735, .0165718, 0, .260639, .837545, .0157524, 0, .277389, .823639, .0149482, 0, .29458, .809699, .0141431, 0, .312216, .794797, .0133527, 0, .3303, .780578, .0126193, 0, .34884, .766019, .0118914, 0, .367842, .751447, .0111839, 0, .387315, .737275, .010514, 0, .40727, .724545, .00987277, 0, .427717, .712644, .00926569, 0, .448671, .700432, .00869029, 0, .470149, .687664, .00814691, 0, .492167, .674288, .00763012, 0, .514746, .660966, .00714437, 0, .537911, .647264, .00668457, 0, .561688, .633431, .00626581, 0, .586108, .619133, .00585593, 0, .611206, .604935, .00548188, 0, .637022, .590236, .00513288, 0, .663599, .575473, .0047906, 0, .690989, .561228, .00448895, 0, .719242, .547054, .00420233, 0, .748411, .533175, .00392869, 0, .778531, .519163, .00367445, 0, .809583, .505328, .00344097, 0, .84127, .491446, .00322003, 0, .873016, .477356, .00301283, 0, .904762, .46356, .00282592, 0, .936508, .449623, .00264956, 0, .968254, .436068, .00246956, 0, 1, 1, .0276135, 0, 0, 1, .0276136, 0, 0, .999998, .0276148, 0, 0, .999993, .0276201, 0, 0, .999976, .0276342, 0, 0, .999945, .027664, 0, 0, .999884, .0277179, 0, 18679e-8, .999784, .027806, 0, .00119607, .99963, .0279394, 0, .00318407, .999401, .0281295, 0, .00613601, .999066, .0283858, 0, .00999963, .998524, .0287027, 0, .0147164, .995702, .0286256, 0, .0202295, .993593, .0286733, 0, .0264876, .992067, .0288989, 0, .0334452, .990548, .0292135, 0, .0410621, .986775, .0291296, 0, .0493032, .984054, .0293099, 0, .0581381, .979481, .0291881, 0, .0675397, .975297, .0291598, 0, .0774848, .96981, .028954, 0, .0879528, .963524, .028628, 0, .0989258, .957398, .0283135, 0, .110388, .950088, .0278469, 0, .122327, .941538, .0271798, 0, .134729, .933332, .0265388, 0, .147587, .924392, .0257776, 0, .160889, .914581, .024916, 0, .174631, .904347, .0240242, 0, .188806, .894324, .0231229, 0, .203409, .883724, .022153, 0, .218437, .872207, .0211355, 0, .233888, .859927, .0201048, 0, .249761, .848373, .0191263, 0, .266056, .836023, .0181306, 0, .282774, .82289, .0171718, 0, .299917, .809324, .0162196, 0, .317488, .795361, .0152622, 0, .335493, .781253, .01439, 0, .353936, .767338, .013533, 0, .372825, .753156, .0127244, 0, .392168, .739122, .0119454, 0, .411976, .725358, .0112054, 0, .432259, .712949, .010487, 0, .453032, .701621, .00984032, 0, .47431, .689703, .00921495, 0, .496111, .677216, .00862492, 0, .518456, .664217, .00806882, 0, .541367, .65137, .00755922, 0, .564872, .638, .00705705, 0, .589001, .62453, .00661266, 0, .613789, .610601, .00618432, 0, .639277, .59676, .00578033, 0, .66551, .582433, .00540927, 0, .692539, .568026, .00506104, 0, .720422, .55414, .0047353, 0, .749216, .540178, .00442889, 0, .778974, .526513, .00414363, 0, .809711, .512954, .00388237, 0, .84127, .499403, .00362875, 0, .873016, .486026, .00340827, 0, .904762, .472345, .00318598, 0, .936508, .458828, .00297635, 0, .968254, .445379, .00279447, 0, 1, 1, .0345716, 0, 0, 1, .0345717, 0, 0, .999999, .034573, 0, 0, .999991, .0345787, 0, 0, .999974, .0345941, 0, 0, .999937, .0346263, 0, 188589e-11, .999869, .0346847, 0, 409238e-9, .999757, .0347798, 0, .0017674, .999582, .0349233, 0, .00413658, .999322, .0351265, 0, .00747408, .998939, .0353967, 0, .0117157, .998219, .0357018, 0, .0167966, .994974, .0354726, 0, .0226572, .993201, .0355621, 0, .0292445, .991573, .0357641, 0, .0365123, .989301, .0359252, 0, .0444203, .985712, .0358017, 0, .0529334, .982411, .0358353, 0, .0620214, .977827, .035617, 0, .0716574, .973278, .0354398, 0, .0818186, .967397, .0350483, 0, .0924846, .960696, .0344795, 0, .103638, .954349, .0339861, 0, .115263, .946066, .0331323, 0, .127348, .938012, .032359, 0, .13988, .929413, .0314413, 0, .152849, .920355, .0304103, 0, .166248, .910586, .0292785, 0, .18007, .900609, .0281391, 0, .194308, .890093, .0269103, 0, .208958, .880013, .0257269, 0, .224018, .869001, .0244671, 0, .239485, .85751, .0232252, 0, .255359, .84582, .0220117, 0, .271638, .834383, .0208274, 0, .288324, .822158, .0196628, 0, .305419, .809056, .0185306, 0, .322927, .795832, .0174174, 0, .340851, .782547, .0163758, 0, .359199, .7689, .015391, 0, .377975, .755526, .0144488, 0, .397189, .741681, .0135372, 0, .416851, .728178, .0126957, 0, .436971, .714642, .0118812, 0, .457564, .702756, .0111165, 0, .478644, .69175, .0104145, 0, .500229, .680159, .00974439, 0, .522339, .668073, .00911926, 0, .544997, .655405, .00851393, 0, .56823, .642921, .00797637, 0, .592068, .629993, .00745119, 0, .616546, .616828, .00696972, 0, .641705, .603305, .00652425, 0, .66759, .589833, .00610188, 0, .694255, .575945, .00570834, 0, .72176, .561745, .00533384, 0, .750168, .548277, .00500001, 0, .779545, .534467, .00467582, 0, .809933, .521032, .00438092, 0, .841272, .507877, .00410348, 0, .873016, .494654, .00383618, 0, .904762, .481592, .00358699, 0, .936508, .468509, .00337281, 0, .968254, .455293, .00316196, 0, 1, 1, .0430698, 0, 0, 1, .0430699, 0, 0, .999998, .0430713, 0, 0, .999991, .0430773, 0, 0, .99997, .0430936, 0, 0, .999928, .0431277, 0, 406396e-10, .999852, .0431893, 0, 744376e-9, .999724, .0432895, 0, .0024806, .999527, .0434397, 0, .00524779, .99923, .0436507, 0, .00898164, .998783, .0439255, 0, .0136083, .997507, .0441104, 0, .0190582, .994418, .0438225, 0, .0252694, .992864, .0439396, 0, .0321879, .991127, .0440962, 0, .039767, .987331, .0438408, 0, .0479667, .984819, .0438991, 0, .056752, .980384, .0435906, 0, .0660929, .975846, .0432543, 0, .075963, .970748, .0428293, 0, .0863398, .964303, .042153, 0, .0972035, .95772, .0414111, 0, .108537, .950747, .0405893, 0, .120325, .942533, .0394887, 0, .132554, .934045, .0383544, 0, .145215, .924942, .037057, 0, .158296, .915811, .0356993, 0, .17179, .90612, .0342401, 0, .185691, .896434, .0328078, 0, .199993, .886021, .031288, 0, .214691, .876081, .0297776, 0, .229782, .865608, .0282334, 0, .245265, .854924, .026749, 0, .261138, .843607, .02526, 0, .277401, .832456, .0238214, 0, .294056, .821342, .0224682, 0, .311104, .809303, .0211297, 0, .328548, .796468, .0198387, 0, .346394, .784046, .0186227, 0, .364645, .771262, .0174561, 0, .38331, .758118, .0163806, 0, .402396, .745075, .0153287, 0, .421912, .731926, .0143647, 0, .44187, .71863, .0134363, 0, .462283, .705414, .0125603, 0, .483165, .693792, .0117508, 0, .504535, .683108, .0110016, 0, .52641, .67183, .0102757, 0, .548816, .66015, .00962044, 0, .571776, .647907, .00898031, 0, .595323, .635734, .00840811, 0, .619489, .623208, .00786211, 0, .644317, .610438, .00734953, 0, .669852, .597345, .00687688, 0, .696148, .584138, .00643469, 0, .723267, .5707, .00602236, 0, .75128, .556966, .0056324, 0, .780258, .543607, .00528277, 0, .810268, .530213, .00493999, 0, .841311, .516912, .00462265, 0, .873016, .503916, .0043307, 0, .904762, .491146, .00406858, 0, .936508, .478439, .00381436, 0, .968254, .465834, .00358003, 0, 1, 1, .0534039, 0, 0, 1, .053404, 0, 0, .999998, .0534055, 0, 0, .999989, .0534116, 0, 0, .999968, .0534283, 0, 0, .999918, .0534633, 0, 155895e-9, .99983, .0535262, 0, .00120914, .999685, .0536281, 0, .00334944, .999461, .0537799, 0, .00653077, .999119, .0539902, 0, .0106718, .998582, .0542524, 0, .0156907, .995919, .0540318, 0, .0215147, .993735, .0538914, 0, .0280801, .992126, .0539557, 0, .0353323, .990266, .0540401, 0, .0432247, .986317, .0536064, 0, .0517172, .983213, .0534425, 0, .0607754, .978303, .0528622, 0, .0703698, .973665, .0523363, 0, .0804742, .968091, .0516165, 0, .0910667, .961026, .0505434, 0, .102128, .954333, .049523, 0, .113641, .946372, .0481698, 0, .125591, .938254, .0467674, 0, .137965, .929516, .0452341, 0, .150754, .920106, .0435083, 0, .163947, .910899, .0417399, 0, .177537, .901532, .0399389, 0, .191516, .891919, .0380901, 0, .205881, .882006, .0362341, 0, .220626, .871965, .0343444, 0, .235749, .862145, .0324832, 0, .251248, .852058, .0306681, 0, .267121, .84161, .0289097, 0, .283368, .830806, .0272079, 0, .299992, .820476, .0256089, 0, .316992, .809514, .0240394, 0, .334374, .797865, .0225379, 0, .35214, .785621, .0211235, 0, .370296, .773765, .0197908, 0, .388849, .761629, .0185235, 0, .407807, .748891, .0173358, 0, .427178, .736437, .0162305, 0, .446974, .723707, .0151778, 0, .467207, .710606, .0141791, 0, .487892, .698019, .0132592, 0, .509046, .686203, .0123887, 0, .530687, .675692, .0115976, 0, .552839, .664826, .0108325, 0, .575527, .65349, .0101348, 0, .59878, .641774, .00947756, 0, .622634, .629794, .00886058, 0, .647128, .617647, .00828526, 0, .672308, .60534, .00775312, 0, .698231, .592718, .00726033, 0, .724958, .579746, .00679731, 0, .752563, .566763, .00636111, 0, .781127, .553515, .00595228, 0, .810733, .540118, .00556876, 0, .841426, .527325, .00523051, 0, .873016, .514265, .00490712, 0, .904762, .501406, .00460297, 0, .936508, .488922, .00431247, 0, .968254, .476541, .0040472, 0, 1, 1, .0659184, 0, 0, 1, .0659185, 0, 0, .999998, .06592, 0, 0, .999988, .0659259, 0, 0, .999963, .0659423, 0, 0, .999907, .0659764, 0, 374198e-9, .999806, .0660376, 0, .00182071, .999639, .0661361, 0, .0043894, .999378, .0662814, 0, .00800055, .998985, .0664779, 0, .0125594, .998285, .0666914, 0, .0179786, .995071, .0661989, 0, .0241822, .993172, .0660454, 0, .031106, .991438, .0660105, 0, .0386952, .988428, .0656875, 0, .0469032, .985218, .0652913, 0, .0556905, .981128, .0647107, 0, .065023, .976015, .0638491, 0, .0748717, .97097, .062993, 0, .0852112, .964582, .0617927, 0, .0960199, .957383, .0603626, 0, .107279, .949969, .0588128, 0, .118971, .941843, .0570274, 0, .131084, .933624, .0551885, 0, .143604, .924543, .053122, 0, .156521, .914919, .0508897, 0, .169825, .905773, .0486418, 0, .18351, .896434, .0463364, 0, .197569, .887195, .0440623, 0, .211997, .877706, .0417799, 0, .226789, .867719, .03945, 0, .241944, .858587, .037243, 0, .257458, .849317, .0350956, 0, .273331, .839585, .0329852, 0, .289563, .829856, .0310028, 0, .306154, .819589, .0290953, 0, .323108, .809714, .0272738, 0, .340426, .79934, .0255631, 0, .358113, .788224, .0239175, 0, .376175, .776619, .0223831, 0, .394616, .76521, .0209298, 0, .413445, .753716, .0195786, 0, .432671, .741564, .0183001, 0, .452305, .729413, .0171259, 0, .472358, .717146, .0159933, 0, .492845, .70436, .0149495, 0, .513783, .69219, .0139681, 0, .535189, .680289, .0130577, 0, .557087, .669611, .0122198, 0, .5795, .659113, .0114174, 0, .602459, .648148, .0106729, 0, .625997, .636905, .00998997, 0, .650154, .625154, .00934313, 0, .674976, .613481, .00874839, 0, .700518, .60154, .00818265, 0, .726845, .58943, .00766889, 0, .754032, .576828, .00717153, 0, .782167, .564194, .00672696, 0, .811344, .551501, .00630863, 0, .841644, .538635, .00592177, 0, .873016, .525724, .00554888, 0, .904762, .513209, .00520225, 0, .936508, .500457, .00488231, 0, .968254, .48799, .00457153, 0, 1, 1, .0810131, 0, 0, 1, .0810133, 0, 0, .999997, .0810145, 0, 0, .999985, .08102, 0, 0, .999956, .0810347, 0, 195026e-10, .999893, .0810656, 0, 719316e-9, .999777, .0811205, 0, .00259774, .999583, .081208, 0, .00561807, .999281, .0813343, 0, .00967472, .998813, .0814969, 0, .0146627, .997597, .0815217, 0, .0204902, .994379, .0808502, 0, .0270802, .992744, .0806792, 0, .0343674, .990745, .0804589, 0, .0422974, .986646, .0796107, 0, .0508242, .983611, .0790913, 0, .0599087, .978869, .0780746, 0, .0695175, .973475, .0768218, 0, .0796223, .967845, .0754926, 0, .0901983, .960778, .0737063, 0, .101224, .953333, .0718052, 0, .112682, .945274, .0695946, 0, .124555, .936955, .0672492, 0, .136831, .928319, .0647732, 0, .149496, .919075, .0620947, 0, .162542, .909114, .0591816, 0, .175958, .900137, .0563917, 0, .189739, .891069, .0535392, 0, .203877, .882262, .0507642, 0, .218368, .873232, .0479793, 0, .233208, .864042, .045226, 0, .248393, .855002, .0425413, 0, .263923, .846569, .0400126, 0, .279796, .837714, .0375269, 0, .296012, .828918, .0352027, 0, .312573, .819783, .0330011, 0, .329479, .810129, .0308908, 0, .346734, .800866, .0289112, 0, .364342, .79093, .0270255, 0, .382307, .780593, .0252758, 0, .400637, .769511, .0236178, 0, .419337, .758558, .0220652, 0, .438418, .747632, .0206289, 0, .457889, .736146, .0192873, 0, .477761, .724093, .0180333, 0, .49805, .71234, .0168264, 0, .51877, .700201, .015746, 0, .53994, .687949, .0147027, 0, .561581, .676163, .0137512, 0, .583718, .665001, .0128655, 0, .60638, .65472, .0120366, 0, .629599, .644213, .0112604, 0, .653415, .633382, .0105413, 0, .677874, .62212, .00986498, 0, .70303, .610631, .00923308, 0, .728948, .599078, .00864206, 0, .755706, .587519, .00811784, 0, .783396, .575505, .00761237, 0, .812121, .563148, .00713949, 0, .841989, .550828, .00668379, 0, .873035, .538458, .00627715, 0, .904762, .525905, .00588336, 0, .936508, .513517, .00552687, 0, .968254, .501395, .00519681, 0, 1, 1, .0991506, 0, 0, 1, .0991504, 0, 0, .999996, .0991515, 0, 0, .999984, .0991558, 0, 0, .999947, .0991672, 0, 114389e-9, .999874, .0991912, 0, .00121503, .999739, .0992331, 0, .00356108, .999514, .0992983, 0, .00705578, .999159, .0993877, 0, .011574, .998586, .0994837, 0, .017003, .995731, .0988425, 0, .0232484, .993384, .098276, 0, .0302318, .991615, .0979269, 0, .0378884, .989029, .0973432, 0, .0461641, .985373, .0963539, 0, .0550136, .981278, .0952306, 0, .0643988, .975777, .0936233, 0, .0742868, .970526, .0920219, 0, .0846501, .963755, .0898912, 0, .0954644, .956676, .0876064, 0, .106709, .948099, .0847751, 0, .118367, .939718, .0818638, 0, .130423, .931305, .078857, 0, .142862, .922342, .0756127, 0, .155674, .912842, .0721473, 0, .168849, .903304, .0686195, 0, .182378, .89411, .0650589, 0, .196255, .885512, .0616022, 0, .210473, .877193, .0582434, 0, .225027, .86877, .0548979, 0, .239915, .860267, .0516095, 0, .255132, .851915, .048468, 0, .270678, .843912, .0454447, 0, .286551, .83604, .0425612, 0, .302751, .828245, .0398752, 0, .31928, .820159, .0373198, 0, .336138, .81167, .034916, 0, .35333, .802659, .0326402, 0, .370858, .793921, .0304901, 0, .388728, .784713, .0284857, 0, .406944, .774946, .0266186, 0, .425515, .76448, .0248593, 0, .444449, .753793, .0232114, 0, .463756, .743506, .0217039, 0, .483447, .732555, .0202841, 0, .503535, .720965, .0189648, 0, .524036, .709422, .0177189, 0, .544968, .697756, .0165626, 0, .56635, .685565, .015483, 0, .588208, .673987, .0144892, 0, .610569, .66244, .0135607, 0, .633466, .651675, .0126956, 0, .656936, .641598, .0118788, 0, .681025, .63121, .0111261, 0, .705788, .620514, .010437, 0, .731289, .609366, .00978747, 0, .757606, .598137, .00917257, 0, .784834, .586966, .00859778, 0, .813085, .575549, .00806803, 0, .842485, .563797, .00757294, 0, .87313, .551758, .00710592, 0, .904762, .539894, .0066841, 0, .936508, .527901, .00627901, 0, .968254, .515819, .00590506, 0, 1, 1, .120864, 0, 0, 1, .120864, 0, 0, .999996, .120864, 0, 0, .99998, .120867, 0, 0, .99994, .120872, 0, 323781e-9, .999852, .120884, 0, .00188693, .999693, .120903, 0, .00473489, .999426, .120929, 0, .00872704, .999002, .120955, 0, .0137237, .998235, .120918, 0, .0196068, .994608, .119764, 0, .0262803, .992997, .119265, 0, .0336657, .990968, .11863, 0, .0416987, .987002, .117261, 0, .0503261, .983524, .116009, 0, .0595035, .97875, .114252, 0, .0691935, .972652, .11193, 0, .0793645, .966613, .109555, 0, .0899894, .959275, .106612, 0, .101045, .951272, .103375, 0, .112512, .942323, .0996594, 0, .124372, .933679, .0958841, 0, .136611, .924822, .0919265, 0, .149216, .915742, .0878061, 0, .162176, .906348, .0834894, 0, .175482, .896883, .079085, 0, .189125, .88774, .0746745, 0, .203098, .87986, .0705773, 0, .217396, .871998, .0665005, 0, .232015, .864325, .0625413, 0, .24695, .856685, .0586781, 0, .2622, .84925, .0550063, 0, .277761, .841719, .0514727, 0, .293634, .834755, .0481398, 0, .309819, .827853, .0450172, 0, .326315, .820888, .0420969, 0, .343126, .813616, .0393702, 0, .360254, .805767, .0367771, 0, .377701, .797338, .0343274, 0, .395474, .789122, .0320529, 0, .413577, .780601, .0299485, 0, .432018, .771424, .0279812, 0, .450804, .761502, .0261054, 0, .469944, .751166, .0243942, 0, .489451, .741276, .0228087, 0, .509337, .730898, .0213265, 0, .529617, .719878, .0199307, 0, .550307, .708379, .0186574, 0, .571428, .697165, .0174446, 0, .593003, .685554, .0163144, 0, .615059, .673631, .015276, 0, .637628, .662385, .0143003, 0, .660746, .651059, .0134112, 0, .68446, .640451, .0125794, 0, .70882, .630536, .011793, 0, .733893, .620316, .0110547, 0, .759756, .609722, .0103668, 0, .786505, .598804, .00973009, 0, .814259, .587871, .00912812, 0, .843157, .577121, .00858916, 0, .87334, .566019, .00807333, 0, .904762, .554664, .00759687, 0, .936508, .543101, .00714759, 0, .968254, .531558, .00673418, 0, 1, 1, .146767, 0, 0, 1, .146767, 0, 0, .999997, .146767, 0, 0, .999977, .146765, 0, 320658e-11, .999929, .146762, 0, 682576e-9, .999823, .146753, 0, .00276402, .999633, .146735, 0, .00614771, .999314, .146699, 0, .0106613, .998796, .14662, 0, .0161546, .997124, .146107, 0, .0225063, .994062, .144857, 0, .0296198, .992154, .144011, 0, .037417, .989186, .142712, 0, .0458348, .985279, .140926, 0, .0548211, .980826, .13885, 0, .0643326, .975056, .136168, 0, .074333, .969005, .133217, 0, .0847917, .961554, .12959, 0, .0956828, .954206, .125886, 0, .106984, .945046, .121335, 0, .118675, .935678, .116492, 0, .130741, .926748, .111635, 0, .143166, .917764, .106625, 0, .155939, .908358, .101325, 0, .169049, .899219, .0960249, 0, .182487, .890089, .0906527, 0, .196245, .881488, .0853905, 0, .210317, .874031, .0804177, 0, .224697, .866932, .0756005, 0, .23938, .859976, .0709019, 0, .254364, .853375, .0664391, 0, .269646, .846971, .0622012, 0, .285223, .840483, .058129, 0, .301096, .833969, .0542762, 0, .317265, .82806, .0507042, 0, .333729, .822128, .047368, 0, .350491, .815989, .044272, 0, .367554, .809336, .0413444, 0, .38492, .802177, .038601, 0, .402594, .79441, .0360227, 0, .420582, .786573, .0336383, 0, .438891, .778619, .0314321, 0, .457527, .77, .029362, 0, .476499, .760698, .0274102, 0, .49582, .750932, .0256146, 0, .5155, .740993, .023974, 0, .535555, .731159, .0224182, 0, .556, .720836, .0209889, 0, .576855, .709913, .0196411, 0, .598143, .698415, .0183824, 0, .619888, .68745, .0172222, 0, .642123, .676154, .0161509, 0, .664883, .664383, .0151397, 0, .688211, .6533, .0141873, 0, .71216, .642072, .0133105, 0, .736792, .631412, .0124932, 0, .762186, .621622, .0117408, 0, .788439, .611681, .0110358, 0, .815672, .60142, .0103775, 0, .844034, .59083, .00975623, 0, .873699, .580254, .00918084, 0, .904765, .569841, .00864721, 0, .936508, .559224, .00815731, 0, .968254, .548315, .00767924, 0, 1, 1, .177563, 0, 0, 1, .177563, 0, 0, .999994, .177562, 0, 0, .999972, .177555, 0, 664171e-10, .999914, .177536, 0, .0012276, .999787, .177496, 0, .00388025, .999556, .17742, 0, .00783463, .999165, .177285, 0, .0128953, .9985, .177037, 0, .0189053, .995388, .175634, 0, .025742, .993102, .174375, 0, .033309, .990992, .173121, 0, .0415298, .986932, .170896, 0, .0503425, .982786, .16847, 0, .0596964, .977592, .165455, 0, .0695498, .971075, .161676, 0, .0798676, .963967, .157458, 0, .0906201, .956397, .152836, 0, .101783, .947489, .147467, 0, .113333, .937564, .14145, 0, .125254, .928182, .135383, 0, .137529, .919027, .129212, 0, .150144, .909618, .12276, 0, .163088, .900492, .116273, 0, .176351, .891671, .1098, 0, .189924, .883146, .103362, 0, .203799, .875151, .0970799, 0, .21797, .868338, .0911732, 0, .232433, .862033, .0854966, 0, .247182, .856107, .0800691, 0, .262216, .850644, .0749618, 0, .27753, .845261, .070079, 0, .293124, .839885, .0654321, 0, .308997, .834609, .0610975, 0, .325149, .829083, .0569741, 0, .341581, .82404, .0531736, 0, .358294, .818968, .049665, 0, .37529, .813496, .0463856, 0, .392573, .807533, .0433217, 0, .410148, .80099, .0404402, 0, .428019, .793891, .0377578, 0, .446192, .786281, .0352616, 0, .464676, .778773, .0329577, 0, .483478, .770737, .030808, 0, .502608, .762094, .0287964, 0, .522079, .752898, .0269254, 0, .541905, .743306, .0251926, 0, .5621, .733416, .023595, 0, .582684, .723742, .0221155, 0, .603677, .713542, .0207435, 0, .625106, .702755, .019434, 0, .646998, .691484, .0182046, 0, .66939, .680531, .0170771, 0, .692324, .66953, .0160339, 0, .715849, .658126, .0150677, 0, .740028, .646933, .0141551, 0, .764937, .636107, .0133179, 0, .790673, .625271, .0125284, 0, .817358, .615225, .0117937, 0, .84515, .605678, .0111181, 0, .874244, .59583, .0104759, 0, .904828, .585704, .00986672, 0, .936508, .575413, .00929712, 0, .968254, .565373, .00876713, 0, 1, 1, .214058, 0, 0, .999999, .214058, 0, 0, .999994, .214055, 0, 0, .999966, .214039, 0, 259642e-9, .999893, .213998, 0, .00200075, .999737, .21391, 0, .00527775, .999449, .213745, 0, .00983959, .99896, .213458, 0, .0154755, .9979, .212855, 0, .0220249, .994278, .210779, 0, .0293654, .992254, .20926, 0, .0374021, .98881, .206908, 0, .0460604, .984715, .204009, 0, .0552802, .979738, .200471, 0, .0650127, .972884, .195813, 0, .0752175, .965996, .190856, 0, .0858612, .957974, .185077, 0, .0969155, .949155, .17868, 0, .108356, .939288, .171513, 0, .120163, .928996, .163838, 0, .132319, .919563, .156246, 0, .144808, .910004, .148359, 0, .157618, .900791, .140417, 0, .170737, .892135, .132569, 0, .184155, .883803, .124741, 0, .197866, .876034, .117091, 0, .211861, .869219, .109835, 0, .226134, .863062, .102859, 0, .240682, .857795, .0962928, 0, .255499, .853009, .0900725, 0, .270583, .848603, .0842101, 0, .285931, .844335, .0786527, 0, .301542, .840208, .0734397, 0, .317415, .836035, .0685334, 0, .33355, .83172, .0639275, 0, .349948, .827135, .0595909, 0, .36661, .822797, .0556204, 0, .383539, .818387, .0519394, 0, .400738, .813565, .0485317, 0, .41821, .808142, .0453138, 0, .435961, .802212, .0423354, 0, .453997, .79573, .0395553, 0, .472324, .788741, .036988, 0, .490951, .781093, .0345688, 0, .509887, .773597, .0323297, 0, .529144, .765622, .0302719, 0, .548735, .757083, .0283477, 0, .568674, .747992, .0265562, 0, .588979, .738591, .0248844, 0, .609671, .728719, .0233342, 0, .630773, .719146, .0219081, 0, .652314, .709165, .0205711, 0, .674328, .69875, .0193248, 0, .696854, .687884, .0181582, 0, .719942, .676818, .0170746, 0, .743651, .666247, .0160718, 0, .768057, .655284, .0151262, 0, .793253, .64401, .0142561, 0, .819363, .633353, .0134327, 0, .846547, .622674, .012653, 0, .875017, .612265, .0119354, 0, .905021, .602455, .0112533, 0, .936508, .593147, .0106234, 0, .968254, .583592, .0100213, 0, 1, 1, .25717, 0, 0, 1, .25717, 0, 0, .999992, .257164, 0, 0, .999958, .257135, 0, 641715e-9, .999864, .25706, 0, .00305314, .999666, .256897, 0, .00700975, .999302, .256596, 0, .0122194, .998663, .25607, 0, .0184622, .995607, .254123, 0, .0255773, .993094, .252081, 0, .0334439, .9907, .249867, 0, .0419696, .98594, .246118, 0, .0510823, .981214, .242049, 0, .0607242, .974966, .236869, 0, .0708486, .967589, .230724, 0, .081417, .95915, .223635, 0, .0923974, .950257, .21596, 0, .103763, .940165, .207296, 0, .115491, .929396, .197901, 0, .127562, .919288, .188437, 0, .13996, .909428, .178762, 0, .15267, .900105, .169072, 0, .165679, .891418, .159478, 0, .178979, .883347, .15002, 0, .192558, .875992, .140813, 0, .20641, .869466, .13196, 0, .220529, .863699, .123501, 0, .234907, .858553, .115436, 0, .249542, .854379, .107901, 0, .264428, .850894, .10088, 0, .279564, .847632, .0942296, 0, .294947, .844571, .0879861, 0, .310575, .84163, .0821534, 0, .326448, .838542, .0766409, 0, .342566, .835412, .0715322, 0, .358929, .831899, .0666883, 0, .37554, .828177, .0622175, 0, .392399, .82416, .0580452, 0, .409511, .820393, .054267, 0, .426878, .816068, .0507172, 0, .444506, .811201, .0474041, 0, .4624, .805785, .0443174, 0, .480566, .799878, .0414562, 0, .499013, .793469, .0388147, 0, .517749, .786473, .0363453, 0, .536785, .778874, .0340225, 0, .556134, .771277, .0318599, 0, .575809, .763426, .0298859, 0, .595827, .755044, .0280357, 0, .616207, .746161, .0262979, 0, .636973, .737124, .0247295, 0, .65815, .72761, .0232514, 0, .679772, .717822, .0218755, 0, .701876, .708279, .0205942, 0, .724509, .698333, .0193947, 0, .74773, .68802, .0182717, 0, .771609, .677321, .0172044, 0, .79624, .666504, .0162122, 0, .821743, .656184, .0152924, 0, .84828, .64556, .0144326, 0, .876069, .634636, .0136157, 0, .905404, .624124, .0128612, 0, .936508, .613914, .0121435, 0, .968254, .603589, .0114887, 0, 1, 1, .307946, 0, 0, .999999, .307945, 0, 0, .999988, .307934, 0, 204479e-10, .999944, .307886, 0, .00127833, .999824, .307756, 0, .00445047, .999565, .30748, 0, .00914673, .999085, .306966, 0, .0150498, .998103, .306004, 0, .0219367, .994249, .303028, 0, .0296485, .991807, .300435, 0, .038068, .987773, .296554, 0, .0471062, .982673, .2916, 0, .0566942, .976623, .285641, 0, .0667768, .968757, .27815, 0, .0773099, .959849, .269529, 0, .088257, .950663, .260248, 0, .0995879, .940129, .249704, 0, .111277, .92895, .238291, 0, .123304, .917996, .226501, 0, .13565, .907813, .214669, 0, .148299, .898305, .202835, 0, .161237, .889626, .191158, 0, .174455, .88175, .179695, 0, .187941, .874715, .168548, 0, .201687, .868746, .15792, 0, .215687, .863703, .147807, 0, .229933, .859315, .138149, 0, .24442, .855538, .128993, 0, .259145, .852428, .120414, 0, .274103, .850168, .112498, 0, .289293, .848132, .105054, 0, .304711, .846291, .0981087, 0, .320357, .844431, .0915942, 0, .33623, .842493, .0855056, 0, .35233, .840368, .0798204, 0, .368658, .83798, .0745097, 0, .385214, .83523, .0695424, 0, .402002, .832091, .0649092, 0, .419023, .828667, .0606291, 0, .436282, .824805, .0566523, 0, .453782, .820988, .0530229, 0, .471529, .816635, .0496364, 0, .489528, .811725, .0464658, 0, .507788, .806316, .0435082, 0, .526317, .800469, .0407873, 0, .545124, .794107, .038255, 0, .564221, .787218, .0358825, 0, .583621, .779872, .0336785, 0, .603341, .772097, .0316379, 0, .623397, .764484, .0297379, 0, .643812, .756428, .0279581, 0, .664611, .748022, .0263153, 0, .685824, .739268, .0247799, 0, .707488, .73024, .0233385, 0, .729646, .720893, .0220035, 0, .752354, .71119, .0207555, 0, .77568, .701791, .0195843, 0, .799715, .692184, .0184891, 0, .824574, .682258, .0174541, 0, .850417, .67206, .0164873, 0, .877466, .661717, .0155959, 0, .90604, .651462, .0147519, 0, .936528, .641467, .0139727, 0, .968254, .631229, .0132363, 0, 1, 1, .367573, 0, 0, .999999, .367571, 0, 0, .999984, .367553, 0, 183382e-9, .999925, .367473, 0, .00225254, .999759, .367259, 0, .00628165, .99941, .366801, 0, .0117858, .998739, .365946, 0, .0184359, .995529, .363191, 0, .0260114, .992875, .360171, 0, .0343581, .989135, .355981, 0, .0433637, .984166, .350401, 0, .0529438, .977871, .343348, 0, .0630334, .96951, .334341, 0, .0735805, .959964, .323862, 0, .0845437, .950162, .312521, 0, .095889, .938882, .299577, 0, .107588, .926992, .285573, 0, .119617, .915589, .271212, 0, .131957, .904791, .256611, 0, .144591, .895177, .242224, 0, .157503, .886403, .227952, 0, .170682, .878957, .214192, 0, .184117, .872418, .200795, 0, .197799, .867029, .188015, 0, .21172, .862835, .175975, 0, .225873, .859411, .164526, 0, .240253, .856655, .153693, 0, .254854, .854519, .14352, 0, .269673, .852828, .13397, 0, .284707, .851412, .124984, 0, .299953, .850609, .116748, 0, .315408, .849855, .10905, 0, .331073, .849017, .101839, 0, .346946, .848079, .0951359, 0, .363028, .846911, .0888774, 0, .379318, .845445, .0830375, 0, .395818, .84362, .0775844, 0, .41253, .841411, .0725054, 0, .429457, .838768, .0677691, 0, .446602, .835801, .0634016, 0, .463968, .832341, .0593095, 0, .481561, .828424, .0555121, 0, .499386, .824312, .052024, 0, .51745, .819918, .0487865, 0, .535761, .815072, .0457801, 0, .554328, .809863, .0430184, 0, .573162, .804164, .0404245, 0, .592275, .798034, .0380146, 0, .611681, .791436, .0357436, 0, .631398, .784498, .0336475, 0, .651445, .777125, .0316666, 0, .671845, .769365, .0298122, 0, .692628, .761579, .0281001, 0, .713827, .753746, .0265049, 0, .735484, .745573, .0250067, 0, .75765, .737083, .0236026, 0, .78039, .728545, .0223302, 0, .803789, .719691, .0211243, 0, .82796, .710569, .0199983, 0, .853056, .701216, .0189569, 0, .879298, .692094, .0179702, 0, .907014, .682909, .0170418, 0, .936691, .673509, .0161732, 0, .968254, .663863, .0153406, 0, 1, 1, .437395, 0, 0, .999998, .437394, 0, 0, .99998, .437363, 0, 616704e-9, .999891, .437232, 0, .00367925, .999656, .436877, 0, .00867446, .999148, .436121, 0, .0150679, .997959, .434564, 0, .022531, .993464, .430134, 0, .0308507, .990606, .426077, 0, .0398805, .985027, .419397, 0, .0495148, .978491, .41118, 0, .0596749, .969643, .40048, 0, .0703001, .959189, .38769, 0, .0813427, .948223, .373575, 0, .0927641, .935955, .357622, 0, .104533, .923237, .34043, 0, .116624, .911074, .322735, 0, .129015, .899724, .30479, 0, .141687, .890189, .287392, 0, .154626, .881796, .270248, 0, .167818, .874781, .253659, 0, .181252, .869166, .237786, 0, .194918, .864725, .222618, 0, .208807, .861565, .208356, 0, .222913, .859284, .194867, 0, .237229, .857677, .18212, 0, .25175, .856714, .17018, 0, .266473, .856155, .158969, 0, .281392, .8558, .148413, 0, .296505, .855672, .138578, 0, .311811, .855538, .129345, 0, .327306, .855689, .120861, 0, .342991, .855767, .112969, 0, .358864, .855618, .105593, 0, .374925, .85525, .0987451, 0, .391176, .854583, .0923727, 0, .407616, .853534, .0864143, 0, .424249, .852061, .0808338, 0, .441076, .850253, .0756771, 0, .4581, .848004, .0708612, 0, .475324, .845333, .0663784, 0, .492754, .842376, .0622631, 0, .510394, .838956, .0584112, 0, .528251, .835121, .0548328, 0, .546331, .830842, .0514838, 0, .564644, .826212, .048355, 0, .583198, .821522, .0454714, 0, .602005, .816551, .0428263, 0, .621078, .811211, .0403612, 0, .640434, .805479, .038039, 0, .660089, .799409, .0358739, 0, .680066, .79306, .0338727, 0, .70039, .786395, .0319985, 0, .721094, .779416, .030241, 0, .742215, .77214, .0285951, 0, .7638, .764636, .0270747, 0, .785912, .756836, .0256354, 0, .808628, .749315, .0243027, 0, .832055, .741561, .0230497, 0, .856338, .733589, .0218801, 0, .88169, .725479, .020784, 0, .908441, .717255, .0197702, 0, .937125, .708829, .0188168, 0, .968254, .700191, .0179113, 0, 1, 1, .518937, 0, 0, .999998, .518933, 0, 0, .999967, .518883, 0, .00147741, .999832, .51866, 0, .00573221, .999466, .518057, 0, .011826, .998644, .516752, 0, .0192116, .994458, .512347, 0, .027573, .991223, .507675, 0, .0367099, .985515, .500188, 0, .046487, .978308, .490408, 0, .0568071, .968359, .477357, 0, .0675984, .95682, .461752, 0, .0788059, .943929, .443796, 0, .090386, .930224, .423893, 0, .102304, .916514, .402682, 0, .114532, .903653, .380914, 0, .127047, .892315, .359212, 0, .139828, .882942, .338102, 0, .152861, .875438, .31773, 0, .16613, .869642, .298186, 0, .179624, .865304, .279491, 0, .193332, .862382, .261804, 0, .207247, .860666, .245146, 0, .22136, .859788, .229406, 0, .235666, .859608, .214605, 0, .250158, .859912, .200691, 0, .264832, .86053, .187623, 0, .279684, .861368, .17539, 0, .294711, .862237, .163901, 0, .309911, .863127, .153175, 0, .32528, .863923, .143147, 0, .340819, .864567, .133781, 0, .356524, .865013, .125042, 0, .372397, .86539, .116952, 0, .388438, .865591, .109476, 0, .404645, .865517, .102542, 0, .421022, .865084, .0960688, 0, .437569, .864309, .0900499, 0, .454287, .863151, .0844328, 0, .471181, .861649, .0792218, 0, .488253, .859742, .0743482, 0, .505507, .857446, .0697963, 0, .522947, .854757, .0655364, 0, .54058, .851783, .061608, 0, .558412, .848516, .0579701, 0, .576449, .844897, .0545742, 0, .594701, .840956, .0514167, 0, .613178, .836676, .0484598, 0, .631892, .832075, .0456934, 0, .650856, .827191, .0431178, 0, .670088, .822295, .0407718, 0, .689606, .817294, .0386032, 0, .709434, .812013, .0365675, 0, .7296, .806465, .0346547, 0, .750138, .800691, .0328717, 0, .771093, .794709, .031211, 0, .792519, .788493, .0296504, 0, .814488, .782049, .0281782, 0, .837097, .775403, .0267965, 0, .860481, .76857, .0255002, 0, .884842, .761536, .0242759, 0, .910494, .754303, .0231142, 0, .937985, .74692, .0220305, 0, .968254, .739745, .0210192, 0, 1, 1, .613914, 0, 0, .999996, .613907, 0, 963597e-10, .999942, .613814, 0, .00301247, .999704, .613407, 0, .00870385, .999046, .612302, 0, .0160714, .995516, .608266, 0, .0245899, .991726, .602863, 0, .0339681, .985157, .593956, 0, .0440254, .97642, .581748, 0, .0546409, .964404, .565183, 0, .0657284, .950601, .545273, 0, .0772246, .935158, .522129, 0, .0890812, .919364, .496782, 0, .10126, .904754, .470571, 0, .113731, .89176, .444037, 0, .126469, .881492, .418322, 0, .139454, .873656, .393522, 0, .15267, .868053, .369795, 0, .166101, .864336, .347171, 0, .179736, .862259, .325737, 0, .193565, .861556, .305532, 0, .207578, .861776, .286416, 0, .221769, .862661, .268355, 0, .23613, .864015, .251334, 0, .250656, .865711, .235352, 0, .265343, .867519, .220302, 0, .280187, .869351, .206161, 0, .295183, .871144, .192908, 0, .31033, .872839, .180505, 0, .325624, .874307, .168848, 0, .341065, .875667, .158021, 0, .35665, .876758, .147877, 0, .37238, .87764, .138441, 0, .388253, .878237, .129627, 0, .404269, .878563, .121415, 0, .42043, .878572, .113741, 0, .436735, .87842, .106652, 0, .453187, .878057, .100097, 0, .469786, .877413, .0940128, 0, .486536, .87646, .0883462, 0, .503439, .875233, .0830924, 0, .520498, .8737, .0781975, 0, .537717, .871873, .07364, 0, .555102, .86978, .0694103, 0, .572657, .867405, .0654696, 0, .59039, .864751, .0617914, 0, .608307, .861818, .0583491, 0, .626419, .858645, .0551443, 0, .644733, .855307, .0521894, 0, .663264, .851736, .0494334, 0, .682025, .847927, .0468504, 0, .701032, .843888, .0444261, 0, .720308, .839629, .0421497, 0, .739875, .835158, .0400082, 0, .759764, .830509, .0380076, 0, .780014, .825714, .0361488, 0, .800673, .820729, .0343956, 0, .821803, .815751, .0327781, 0, .843492, .810752, .031275, 0, .86586, .805587, .0298542, 0, .889087, .800317, .0285397, 0, .913466, .79489, .0272948, 0, .93952, .789314, .0261139, 0, .96835, .783593, .0249938, 0, 1, 1, .724258, 0, 0, .999992, .724243, 0, 726889e-9, .99987, .724044, 0, .00569574, .999336, .72317, 0, .0131702, .996271, .719432, 0, .0220738, .991159, .712576, 0, .0319405, .982465, .700927, 0, .0425202, .97049, .684297, 0, .0536599, .953973, .661244, 0, .065258, .935546, .633804, 0, .0772427, .916596, .603071, 0, .0895616, .899353, .57105, 0, .102175, .885216, .539206, 0, .11505, .875076, .508714, 0, .128164, .868334, .479571, 0, .141495, .864414, .451796, 0, .155026, .862678, .425328, 0, .168745, .862835, .400352, 0, .182639, .864067, .376532, 0, .196699, .866086, .35391, 0, .210915, .868557, .332424, 0, .225282, .871271, .312053, 0, .239792, .874058, .292764, 0, .25444, .8768, .27453, 0, .269223, .87939, .257297, 0, .284135, .8819, .24114, 0, .299174, .884187, .225934, 0, .314337, .886262, .211669, 0, .329622, .888119, .198311, 0, .345026, .889709, .185783, 0, .360549, .891054, .174063, 0, .376189, .892196, .163143, 0, .391946, .893101, .152952, 0, .407819, .893803, .143475, 0, .423808, .894277, .134647, 0, .439914, .894532, .126434, 0, .456137, .894576, .1188, 0, .472479, .894393, .111694, 0, .48894, .893976, .105069, 0, .505523, .893346, .0989077, 0, .52223, .892502, .0931724, 0, .539064, .891441, .0878276, 0, .556028, .890276, .082903, 0, .573125, .888972, .0783505, 0, .590361, .887469, .0741083, 0, .607741, .885785, .0701633, 0, .62527, .883914, .0664835, 0, .642957, .881872, .0630567, 0, .660809, .879651, .0598527, 0, .678836, .877267, .0568615, 0, .69705, .874717, .05406, 0, .715465, .872012, .0514378, 0, .734098, .869157, .0489805, 0, .752968, .866155, .0466727, 0, .772101, .863014, .0445056, 0, .791529, .859748, .0424733, 0, .81129, .856416, .0405957, 0, .831438, .852958, .0388273, 0, .852044, .849382, .0371619, 0, .87321, .845694, .0355959, 0, .89509, .841893, .0341155, 0, .917932, .837981, .0327141, 0, .942204, .833963, .0313856, 0, .968981, .829847, .0301275, 0, 1, 1, .85214, 0, 0, .999969, .852095, 0, .00279627, .999483, .851408, 0, .0107635, .994545, .84579, 0, .0206454, .986188, .835231, 0, .0315756, .969847, .814687, 0, .0432021, .945951, .783735, 0, .0553396, .91917, .746074, 0, .0678766, .895488, .706938, 0, .0807395, .878232, .669534, 0, .0938767, .868252, .635168, 0, .10725, .863873, .603069, 0, .120832, .863369, .572514, 0, .134598, .86545, .543169, 0, .148533, .868803, .514578, 0, .16262, .872794, .486762, 0, .176849, .87702, .459811, 0, .19121, .881054, .433654, 0, .205694, .884974, .408574, 0, .220294, .888587, .384525, 0, .235005, .891877, .36156, 0, .24982, .894793, .339661, 0, .264737, .89743, .318913, 0, .279751, .899796, .299302, 0, .294859, .901943, .280843, 0, .310058, .903858, .263481, 0, .325346, .905574, .247197, 0, .340721, .907069, .231915, 0, .356181, .908379, .217614, 0, .371725, .90952, .20425, 0, .387353, .910483, .191758, 0, .403063, .91128, .180092, 0, .418854, .911936, .169222, 0, .434727, .912454, .159098, 0, .450682, .912835, .149668, 0, .466718, .913078, .140884, 0, .482837, .913192, .132709, 0, .499038, .913175, .125095, 0, .515324, .91304, .118012, 0, .531695, .912781, .111417, 0, .548153, .91241, .105281, 0, .5647, .911924, .0995691, 0, .581338, .911331, .0942531, 0, .59807, .910637, .0893076, 0, .6149, .90984, .0846998, 0, .63183, .908941, .0804044, 0, .648865, .907944, .0763984, 0, .666011, .906857, .0726638, 0, .683273, .90568, .0691783, 0, .700659, .904416, .0659222, 0, .718176, .903067, .0628782, 0, .735834, .901637, .0600307, 0, .753646, .900128, .0573647, 0, .771625, .898544, .0548668, 0, .78979, .89689, .052527, 0, .808162, .895165, .0503306, 0, .826771, .893371, .0482668, 0, .845654, .891572, .0463605, 0, .864863, .889763, .0445998, 0, .884472, .887894, .0429451, 0, .904592, .885967, .0413884, 0, .925407, .883984, .0399225, 0, .947271, .881945, .0385405, 0, .97105, .879854, .0372362, 0, 1, .999804, .995833, 0, 0, .938155, .933611, 0, .0158731, .864755, .854311, 0, .0317461, .888594, .865264, 0, .0476191, .905575, .863922, 0, .0634921, .915125, .850558, 0, .0793651, .920665, .829254, 0, .0952381, .924073, .802578, 0, .111111, .926304, .772211, 0, .126984, .927829, .739366, 0, .142857, .928924, .705033, 0, .15873, .92973, .670019, 0, .174603, .930339, .634993, 0, .190476, .930811, .600485, 0, .206349, .931191, .566897, 0, .222222, .93149, .534485, 0, .238095, .931737, .503429, 0, .253968, .931939, .473811, 0, .269841, .932108, .445668, 0, .285714, .93225, .418993, 0, .301587, .932371, .393762, 0, .31746, .932474, .369939, 0, .333333, .932562, .347479, 0, .349206, .932638, .326336, 0, .365079, .932703, .306462, 0, .380952, .93276, .287805, 0, .396825, .932809, .270313, 0, .412698, .932851, .253933, 0, .428571, .932887, .23861, 0, .444444, .932917, .224289, 0, .460317, .932943, .210917, 0, .47619, .932965, .19844, 0, .492063, .932982, .186807, 0, .507937, .932995, .175966, 0, .52381, .933005, .165869, 0, .539683, .933011, .156468, 0, .555556, .933013, .147719, 0, .571429, .933013, .139579, 0, .587302, .93301, .132007, 0, .603175, .933004, .124965, 0, .619048, .932994, .118416, 0, .634921, .932982, .112326, 0, .650794, .932968, .106663, 0, .666667, .93295, .101397, 0, .68254, .932931, .0964993, 0, .698413, .932908, .0919438, 0, .714286, .932883, .0877057, 0, .730159, .932856, .0837623, 0, .746032, .932827, .0800921, 0, .761905, .932796, .0766754, 0, .777778, .932762, .0734936, 0, .793651, .932727, .0705296, 0, .809524, .932689, .0677676, 0, .825397, .93265, .0651929, 0, .84127, .932609, .0627917, 0, .857143, .932565, .0605515, 0, .873016, .932521, .0584606, 0, .888889, .932474, .0565082, 0, .904762, .932427, .0546841, 0, .920635, .932377, .0529793, 0, .936508, .932326, .0513851, 0, .952381, .932274, .0498936, 0, .968254, .93222, .0484975, 0, .984127, .932164, .0471899, 0, 1 ]; const ltc_float_1 = new Float32Array(LTC_MAT_1); const ltc_float_2 = new Float32Array(LTC_MAT_2); UniformsLib.LTC_FLOAT_1 = new DataTexture(ltc_float_1, 64, 64, RGBAFormat, FloatType, 300, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); UniformsLib.LTC_FLOAT_2 = new DataTexture(ltc_float_2, 64, 64, RGBAFormat, FloatType, 300, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); UniformsLib.LTC_FLOAT_1.needsUpdate = true; UniformsLib.LTC_FLOAT_2.needsUpdate = true; const ltc_half_1 = new Uint16Array(LTC_MAT_1.length); LTC_MAT_1.forEach(function(x, index) { ltc_half_1[index] = DataUtils.toHalfFloat(x); }); const ltc_half_2 = new Uint16Array(LTC_MAT_2.length); LTC_MAT_2.forEach(function(x, index) { ltc_half_2[index] = DataUtils.toHalfFloat(x); }); UniformsLib.LTC_HALF_1 = new DataTexture(ltc_half_1, 64, 64, RGBAFormat, HalfFloatType, 300, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); UniformsLib.LTC_HALF_2 = new DataTexture(ltc_half_2, 64, 64, RGBAFormat, HalfFloatType, 300, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); UniformsLib.LTC_HALF_1.needsUpdate = true; UniformsLib.LTC_HALF_2.needsUpdate = true; } }; //#endregion //#region node_modules/three-stdlib/lights/LightProbeGenerator.js var LightProbeGenerator = { fromCubeTexture(cubeTexture) { let totalWeight = 0; const coord = new Vector3(); const dir = new Vector3(); const color = new Color(); const shBasis = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const sh = new SphericalHarmonics3(); const shCoefficients = sh.coefficients; for (let faceIndex = 0; faceIndex < 6; faceIndex++) { const image = cubeTexture.image[faceIndex]; const width = image.width; const height = image.height; const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; const context = canvas.getContext("2d"); context.drawImage(image, 0, 0, width, height); const imageData = context.getImageData(0, 0, width, height); const data = imageData.data; const imageWidth = imageData.width; const pixelSize = 2 / imageWidth; for (let i = 0, il = data.length; i < il; i += 4) { color.setRGB(data[i] / 255, data[i + 1] / 255, data[i + 2] / 255); if ("colorSpace" in cubeTexture) { if (cubeTexture.colorSpace === "srgb") color.convertSRGBToLinear(); } else if (cubeTexture.encoding === 3001) color.convertSRGBToLinear(); const pixelIndex = i / 4; const col = -1 + (pixelIndex % imageWidth + .5) * pixelSize; const row = 1 - (Math.floor(pixelIndex / imageWidth) + .5) * pixelSize; switch (faceIndex) { case 0: coord.set(-1, row, -col); break; case 1: coord.set(1, row, col); break; case 2: coord.set(-col, 1, -row); break; case 3: coord.set(-col, -1, row); break; case 4: coord.set(-col, row, 1); break; case 5: coord.set(col, row, -1); break; } const lengthSq = coord.lengthSq(); const weight = 4 / (Math.sqrt(lengthSq) * lengthSq); totalWeight += weight; dir.copy(coord).normalize(); SphericalHarmonics3.getBasisAt(dir, shBasis); for (let j = 0; j < 9; j++) { shCoefficients[j].x += shBasis[j] * color.r * weight; shCoefficients[j].y += shBasis[j] * color.g * weight; shCoefficients[j].z += shBasis[j] * color.b * weight; } } } const norm = 4 * Math.PI / totalWeight; for (let j = 0; j < 9; j++) { shCoefficients[j].x *= norm; shCoefficients[j].y *= norm; shCoefficients[j].z *= norm; } return new LightProbe(sh); }, fromCubeRenderTarget(renderer, cubeRenderTarget) { let totalWeight = 0; const coord = new Vector3(); const dir = new Vector3(); const color = new Color(); const shBasis = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const sh = new SphericalHarmonics3(); const shCoefficients = sh.coefficients; for (let faceIndex = 0; faceIndex < 6; faceIndex++) { const imageWidth = cubeRenderTarget.width; const data = new Uint8Array(imageWidth * imageWidth * 4); renderer.readRenderTargetPixels(cubeRenderTarget, 0, 0, imageWidth, imageWidth, data, faceIndex); const pixelSize = 2 / imageWidth; for (let i = 0, il = data.length; i < il; i += 4) { color.setRGB(data[i] / 255, data[i + 1] / 255, data[i + 2] / 255); if ("colorSpace" in cubeRenderTarget.texture) { if (cubeRenderTarget.texture.colorSpace === "srgb") color.convertSRGBToLinear(); } else if (cubeRenderTarget.texture.encoding === 3001) color.convertSRGBToLinear(); const pixelIndex = i / 4; const col = -1 + (pixelIndex % imageWidth + .5) * pixelSize; const row = 1 - (Math.floor(pixelIndex / imageWidth) + .5) * pixelSize; switch (faceIndex) { case 0: coord.set(1, row, -col); break; case 1: coord.set(-1, row, col); break; case 2: coord.set(col, 1, -row); break; case 3: coord.set(col, -1, row); break; case 4: coord.set(col, row, 1); break; case 5: coord.set(-col, row, -1); break; } const lengthSq = coord.lengthSq(); const weight = 4 / (Math.sqrt(lengthSq) * lengthSq); totalWeight += weight; dir.copy(coord).normalize(); SphericalHarmonics3.getBasisAt(dir, shBasis); for (let j = 0; j < 9; j++) { shCoefficients[j].x += shBasis[j] * color.r * weight; shCoefficients[j].y += shBasis[j] * color.g * weight; shCoefficients[j].z += shBasis[j] * color.b * weight; } } } const norm = 4 * Math.PI / totalWeight; for (let j = 0; j < 9; j++) { shCoefficients[j].x *= norm; shCoefficients[j].y *= norm; shCoefficients[j].z *= norm; } return new LightProbe(sh); } }; //#endregion //#region node_modules/three-stdlib/curves/NURBSSurface.js var NURBSSurface = class { constructor(degree1, degree2, knots1, knots2, controlPoints) { this.degree1 = degree1; this.degree2 = degree2; this.knots1 = knots1; this.knots2 = knots2; this.controlPoints = []; const len1 = knots1.length - degree1 - 1; const len2 = knots2.length - degree2 - 1; for (let i = 0; i < len1; ++i) { this.controlPoints[i] = []; for (let j = 0; j < len2; ++j) { const point = controlPoints[i][j]; this.controlPoints[i][j] = new Vector4(point.x, point.y, point.z, point.w); } } } getPoint(t1, t2, target) { const u = this.knots1[0] + t1 * (this.knots1[this.knots1.length - 1] - this.knots1[0]); const v = this.knots2[0] + t2 * (this.knots2[this.knots2.length - 1] - this.knots2[0]); calcSurfacePoint(this.degree1, this.degree2, this.knots1, this.knots2, this.controlPoints, u, v, target); } }; //#endregion //#region node_modules/three-stdlib/curves/CurveExtras.js var GrannyKnot = class extends Curve { getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; t = 2 * Math.PI * t; const x = -.22 * Math.cos(t) - 1.28 * Math.sin(t) - .44 * Math.cos(3 * t) - .78 * Math.sin(3 * t); const y = -.1 * Math.cos(2 * t) - .27 * Math.sin(2 * t) + .38 * Math.cos(4 * t) + .46 * Math.sin(4 * t); const z = .7 * Math.cos(3 * t) - .4 * Math.sin(3 * t); return point.set(x, y, z).multiplyScalar(20); } }; var HeartCurve = class extends Curve { constructor(scale = 5) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; t *= 2 * Math.PI; const x = 16 * Math.pow(Math.sin(t), 3); const y = 13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t); return point.set(x, y, 0).multiplyScalar(this.scale); } }; var VivianiCurve = class extends Curve { constructor(scale = 70) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; t = t * 4 * Math.PI; const a = this.scale / 2; const x = a * (1 + Math.cos(t)); const y = a * Math.sin(t); const z = 2 * a * Math.sin(t / 2); return point.set(x, y, z); } }; var KnotCurve = class extends Curve { getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; t *= 2 * Math.PI; const R = 10; const s = 50; const x = s * Math.sin(t); const y = Math.cos(t) * (R + s * Math.cos(t)); const z = Math.sin(t) * (R + s * Math.cos(t)); return point.set(x, y, z); } }; var HelixCurve = class extends Curve { getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; const a = 30; const b = 150; const t2 = 2 * Math.PI * t * b / 30; const x = Math.cos(t2) * a; const y = Math.sin(t2) * a; const z = b * t; return point.set(x, y, z); } }; var TrefoilKnot = class extends Curve { constructor(scale = 10) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; t *= Math.PI * 2; const x = (2 + Math.cos(3 * t)) * Math.cos(2 * t); const y = (2 + Math.cos(3 * t)) * Math.sin(2 * t); const z = Math.sin(3 * t); return point.set(x, y, z).multiplyScalar(this.scale); } }; var TorusKnot = class extends Curve { constructor(scale = 10) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; const p = 3; const q = 4; t *= Math.PI * 2; const x = (2 + Math.cos(q * t)) * Math.cos(p * t); const y = (2 + Math.cos(q * t)) * Math.sin(p * t); const z = Math.sin(q * t); return point.set(x, y, z).multiplyScalar(this.scale); } }; var CinquefoilKnot = class extends Curve { constructor(scale = 10) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; const p = 2; const q = 5; t *= Math.PI * 2; const x = (2 + Math.cos(q * t)) * Math.cos(p * t); const y = (2 + Math.cos(q * t)) * Math.sin(p * t); const z = Math.sin(q * t); return point.set(x, y, z).multiplyScalar(this.scale); } }; var TrefoilPolynomialKnot = class extends Curve { constructor(scale = 10) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; t = t * 4 - 2; const x = Math.pow(t, 3) - 3 * t; const y = Math.pow(t, 4) - 4 * t * t; const z = 1 / 5 * Math.pow(t, 5) - 2 * t; return point.set(x, y, z).multiplyScalar(this.scale); } }; function scaleTo(x, y, t) { return t * (y - x) + x; } var FigureEightPolynomialKnot = class extends Curve { constructor(scale = 1) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; t = scaleTo(-4, 4, t); const x = 2 / 5 * t * (t * t - 7) * (t * t - 10); const y = Math.pow(t, 4) - 13 * t * t; const z = 1 / 10 * t * (t * t - 4) * (t * t - 9) * (t * t - 12); return point.set(x, y, z).multiplyScalar(this.scale); } }; var DecoratedTorusKnot4a = class extends Curve { constructor(scale = 40) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; t *= Math.PI * 2; const x = Math.cos(2 * t) * (1 + .6 * (Math.cos(5 * t) + .75 * Math.cos(10 * t))); const y = Math.sin(2 * t) * (1 + .6 * (Math.cos(5 * t) + .75 * Math.cos(10 * t))); const z = .35 * Math.sin(5 * t); return point.set(x, y, z).multiplyScalar(this.scale); } }; var DecoratedTorusKnot4b = class extends Curve { constructor(scale = 40) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; const fi = t * Math.PI * 2; const x = Math.cos(2 * fi) * (1 + .45 * Math.cos(3 * fi) + .4 * Math.cos(9 * fi)); const y = Math.sin(2 * fi) * (1 + .45 * Math.cos(3 * fi) + .4 * Math.cos(9 * fi)); const z = .2 * Math.sin(9 * fi); return point.set(x, y, z).multiplyScalar(this.scale); } }; var DecoratedTorusKnot5a = class extends Curve { constructor(scale = 40) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; const fi = t * Math.PI * 2; const x = Math.cos(3 * fi) * (1 + .3 * Math.cos(5 * fi) + .5 * Math.cos(10 * fi)); const y = Math.sin(3 * fi) * (1 + .3 * Math.cos(5 * fi) + .5 * Math.cos(10 * fi)); const z = .2 * Math.sin(20 * fi); return point.set(x, y, z).multiplyScalar(this.scale); } }; var DecoratedTorusKnot5c = class extends Curve { constructor(scale = 40) { super(); this.scale = scale; } getPoint(t, optionalTarget = new Vector3()) { const point = optionalTarget; const fi = t * Math.PI * 2; const x = Math.cos(4 * fi) * (1 + .5 * (Math.cos(5 * fi) + .4 * Math.cos(20 * fi))); const y = Math.sin(4 * fi) * (1 + .5 * (Math.cos(5 * fi) + .4 * Math.cos(20 * fi))); const z = .35 * Math.sin(15 * fi); return point.set(x, y, z).multiplyScalar(this.scale); } }; //#endregion //#region node_modules/three-stdlib/deprecated/Geometry.js var _m1 = /* @__PURE__ */ new Matrix4(); var _obj = /* @__PURE__ */ new Object3D(); var _offset = /* @__PURE__ */ new Vector3(); var Geometry = /* @__PURE__ */ (() => { class Geometry2 extends EventDispatcher$1 { static createBufferGeometryFromObject(object) { let buffergeometry = new BufferGeometry(); const geometry = object.geometry; if (object.isPoints || object.isLine) { const positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3); const colors = new Float32BufferAttribute(geometry.colors.length * 3, 3); buffergeometry.setAttribute("position", positions.copyVector3sArray(geometry.vertices)); buffergeometry.setAttribute("color", colors.copyColorsArray(geometry.colors)); if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) { const lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1); buffergeometry.setAttribute("lineDistance", lineDistances.copyArray(geometry.lineDistances)); } if (geometry.boundingSphere !== null) buffergeometry.boundingSphere = geometry.boundingSphere.clone(); if (geometry.boundingBox !== null) buffergeometry.boundingBox = geometry.boundingBox.clone(); } else if (object.isMesh) buffergeometry = geometry.toBufferGeometry(); return buffergeometry; } constructor() { super(); this.isGeometry = true; this.uuid = MathUtils.generateUUID(); this.name = ""; this.type = "Geometry"; this.vertices = []; this.colors = []; this.faces = []; this.faceVertexUvs = [[]]; this.morphTargets = []; this.morphNormals = []; this.skinWeights = []; this.skinIndices = []; this.lineDistances = []; this.boundingBox = null; this.boundingSphere = null; this.elementsNeedUpdate = false; this.verticesNeedUpdate = false; this.uvsNeedUpdate = false; this.normalsNeedUpdate = false; this.colorsNeedUpdate = false; this.lineDistancesNeedUpdate = false; this.groupsNeedUpdate = false; } applyMatrix4(matrix) { const normalMatrix = new Matrix3().getNormalMatrix(matrix); for (let i = 0, il = this.vertices.length; i < il; i++) this.vertices[i].applyMatrix4(matrix); for (let i = 0, il = this.faces.length; i < il; i++) { const face = this.faces[i]; face.normal.applyMatrix3(normalMatrix).normalize(); for (let j = 0, jl = face.vertexNormals.length; j < jl; j++) face.vertexNormals[j].applyMatrix3(normalMatrix).normalize(); } if (this.boundingBox !== null) this.computeBoundingBox(); if (this.boundingSphere !== null) this.computeBoundingSphere(); this.verticesNeedUpdate = true; this.normalsNeedUpdate = true; return this; } rotateX(angle) { _m1.makeRotationX(angle); this.applyMatrix4(_m1); return this; } rotateY(angle) { _m1.makeRotationY(angle); this.applyMatrix4(_m1); return this; } rotateZ(angle) { _m1.makeRotationZ(angle); this.applyMatrix4(_m1); return this; } translate(x, y, z) { _m1.makeTranslation(x, y, z); this.applyMatrix4(_m1); return this; } scale(x, y, z) { _m1.makeScale(x, y, z); this.applyMatrix4(_m1); return this; } lookAt(vector) { _obj.lookAt(vector); _obj.updateMatrix(); this.applyMatrix4(_obj.matrix); return this; } fromBufferGeometry(geometry) { const scope = this; const index = geometry.index !== null ? geometry.index : void 0; const attributes = geometry.attributes; if (attributes.position === void 0) { console.error("THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion."); return this; } const position = attributes.position; const normal = attributes.normal; const color = attributes.color; const uv = attributes.uv; const uv2 = attributes.uv2; if (uv2 !== void 0) this.faceVertexUvs[1] = []; for (let i = 0; i < position.count; i++) { scope.vertices.push(new Vector3().fromBufferAttribute(position, i)); if (color !== void 0) scope.colors.push(new Color().fromBufferAttribute(color, i)); } function addFace(a, b, c, materialIndex) { const vertexColors = color === void 0 ? [] : [ scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone() ]; const face = new Face3(a, b, c, normal === void 0 ? [] : [ new Vector3().fromBufferAttribute(normal, a), new Vector3().fromBufferAttribute(normal, b), new Vector3().fromBufferAttribute(normal, c) ], vertexColors, materialIndex); scope.faces.push(face); if (uv !== void 0) scope.faceVertexUvs[0].push([ new Vector2().fromBufferAttribute(uv, a), new Vector2().fromBufferAttribute(uv, b), new Vector2().fromBufferAttribute(uv, c) ]); if (uv2 !== void 0) scope.faceVertexUvs[1].push([ new Vector2().fromBufferAttribute(uv2, a), new Vector2().fromBufferAttribute(uv2, b), new Vector2().fromBufferAttribute(uv2, c) ]); } const groups = geometry.groups; if (groups.length > 0) for (let i = 0; i < groups.length; i++) { const group = groups[i]; const start = group.start; const count = group.count; for (let j = start, jl = start + count; j < jl; j += 3) if (index !== void 0) addFace(index.getX(j), index.getX(j + 1), index.getX(j + 2), group.materialIndex); else addFace(j, j + 1, j + 2, group.materialIndex); } else if (index !== void 0) for (let i = 0; i < index.count; i += 3) addFace(index.getX(i), index.getX(i + 1), index.getX(i + 2)); else for (let i = 0; i < position.count; i += 3) addFace(i, i + 1, i + 2); this.computeFaceNormals(); if (geometry.boundingBox !== null) this.boundingBox = geometry.boundingBox.clone(); if (geometry.boundingSphere !== null) this.boundingSphere = geometry.boundingSphere.clone(); return this; } center() { this.computeBoundingBox(); this.boundingBox.getCenter(_offset).negate(); this.translate(_offset.x, _offset.y, _offset.z); return this; } normalize() { this.computeBoundingSphere(); const center = this.boundingSphere.center; const radius = this.boundingSphere.radius; const s = radius === 0 ? 1 : 1 / radius; const matrix = new Matrix4(); matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1); this.applyMatrix4(matrix); return this; } computeFaceNormals() { const cb = new Vector3(), ab = new Vector3(); for (let f = 0, fl = this.faces.length; f < fl; f++) { const face = this.faces[f]; const vA = this.vertices[face.a]; const vB = this.vertices[face.b]; const vC = this.vertices[face.c]; cb.subVectors(vC, vB); ab.subVectors(vA, vB); cb.cross(ab); cb.normalize(); face.normal.copy(cb); } } computeVertexNormals(areaWeighted = true) { const vertices = new Array(this.vertices.length); for (let v = 0, vl = this.vertices.length; v < vl; v++) vertices[v] = new Vector3(); if (areaWeighted) { const cb = new Vector3(), ab = new Vector3(); for (let f = 0, fl = this.faces.length; f < fl; f++) { const face = this.faces[f]; const vA = this.vertices[face.a]; const vB = this.vertices[face.b]; const vC = this.vertices[face.c]; cb.subVectors(vC, vB); ab.subVectors(vA, vB); cb.cross(ab); vertices[face.a].add(cb); vertices[face.b].add(cb); vertices[face.c].add(cb); } } else { this.computeFaceNormals(); for (let f = 0, fl = this.faces.length; f < fl; f++) { const face = this.faces[f]; vertices[face.a].add(face.normal); vertices[face.b].add(face.normal); vertices[face.c].add(face.normal); } } for (let v = 0, vl = this.vertices.length; v < vl; v++) vertices[v].normalize(); for (let f = 0, fl = this.faces.length; f < fl; f++) { const face = this.faces[f]; const vertexNormals = face.vertexNormals; if (vertexNormals.length === 3) { vertexNormals[0].copy(vertices[face.a]); vertexNormals[1].copy(vertices[face.b]); vertexNormals[2].copy(vertices[face.c]); } else { vertexNormals[0] = vertices[face.a].clone(); vertexNormals[1] = vertices[face.b].clone(); vertexNormals[2] = vertices[face.c].clone(); } } if (this.faces.length > 0) this.normalsNeedUpdate = true; } computeFlatVertexNormals() { this.computeFaceNormals(); for (let f = 0, fl = this.faces.length; f < fl; f++) { const face = this.faces[f]; const vertexNormals = face.vertexNormals; if (vertexNormals.length === 3) { vertexNormals[0].copy(face.normal); vertexNormals[1].copy(face.normal); vertexNormals[2].copy(face.normal); } else { vertexNormals[0] = face.normal.clone(); vertexNormals[1] = face.normal.clone(); vertexNormals[2] = face.normal.clone(); } } if (this.faces.length > 0) this.normalsNeedUpdate = true; } computeMorphNormals() { for (let f = 0, fl = this.faces.length; f < fl; f++) { const face = this.faces[f]; if (!face.__originalFaceNormal) face.__originalFaceNormal = face.normal.clone(); else face.__originalFaceNormal.copy(face.normal); if (!face.__originalVertexNormals) face.__originalVertexNormals = []; for (let i = 0, il = face.vertexNormals.length; i < il; i++) if (!face.__originalVertexNormals[i]) face.__originalVertexNormals[i] = face.vertexNormals[i].clone(); else face.__originalVertexNormals[i].copy(face.vertexNormals[i]); } const tmpGeo = new Geometry2(); tmpGeo.faces = this.faces; for (let i = 0, il = this.morphTargets.length; i < il; i++) { if (!this.morphNormals[i]) { this.morphNormals[i] = {}; this.morphNormals[i].faceNormals = []; this.morphNormals[i].vertexNormals = []; const dstNormalsFace = this.morphNormals[i].faceNormals; const dstNormalsVertex = this.morphNormals[i].vertexNormals; for (let f = 0, fl = this.faces.length; f < fl; f++) { const faceNormal = new Vector3(); const vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; dstNormalsFace.push(faceNormal); dstNormalsVertex.push(vertexNormals); } } const morphNormals = this.morphNormals[i]; tmpGeo.vertices = this.morphTargets[i].vertices; tmpGeo.computeFaceNormals(); tmpGeo.computeVertexNormals(); for (let f = 0, fl = this.faces.length; f < fl; f++) { const face = this.faces[f]; const faceNormal = morphNormals.faceNormals[f]; const vertexNormals = morphNormals.vertexNormals[f]; faceNormal.copy(face.normal); vertexNormals.a.copy(face.vertexNormals[0]); vertexNormals.b.copy(face.vertexNormals[1]); vertexNormals.c.copy(face.vertexNormals[2]); } } for (let f = 0, fl = this.faces.length; f < fl; f++) { const face = this.faces[f]; face.normal = face.__originalFaceNormal; face.vertexNormals = face.__originalVertexNormals; } } computeBoundingBox() { if (this.boundingBox === null) this.boundingBox = new Box3(); this.boundingBox.setFromPoints(this.vertices); } computeBoundingSphere() { if (this.boundingSphere === null) this.boundingSphere = new Sphere(); this.boundingSphere.setFromPoints(this.vertices); } merge(geometry, matrix, materialIndexOffset = 0) { if (!(geometry && geometry.isGeometry)) { console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.", geometry); return; } let normalMatrix; const vertexOffset = this.vertices.length, vertices1 = this.vertices, vertices2 = geometry.vertices, faces1 = this.faces, faces2 = geometry.faces, colors1 = this.colors, colors2 = geometry.colors; if (matrix !== void 0) normalMatrix = new Matrix3().getNormalMatrix(matrix); for (let i = 0, il = vertices2.length; i < il; i++) { const vertexCopy = vertices2[i].clone(); if (matrix !== void 0) vertexCopy.applyMatrix4(matrix); vertices1.push(vertexCopy); } for (let i = 0, il = colors2.length; i < il; i++) colors1.push(colors2[i].clone()); for (let i = 0, il = faces2.length; i < il; i++) { const face = faces2[i]; let normal, color; const faceVertexNormals = face.vertexNormals, faceVertexColors = face.vertexColors; const faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset); faceCopy.normal.copy(face.normal); if (normalMatrix !== void 0) faceCopy.normal.applyMatrix3(normalMatrix).normalize(); for (let j = 0, jl = faceVertexNormals.length; j < jl; j++) { normal = faceVertexNormals[j].clone(); if (normalMatrix !== void 0) normal.applyMatrix3(normalMatrix).normalize(); faceCopy.vertexNormals.push(normal); } faceCopy.color.copy(face.color); for (let j = 0, jl = faceVertexColors.length; j < jl; j++) { color = faceVertexColors[j]; faceCopy.vertexColors.push(color.clone()); } faceCopy.materialIndex = face.materialIndex + materialIndexOffset; faces1.push(faceCopy); } for (let i = 0, il = geometry.faceVertexUvs.length; i < il; i++) { const faceVertexUvs2 = geometry.faceVertexUvs[i]; if (this.faceVertexUvs[i] === void 0) this.faceVertexUvs[i] = []; for (let j = 0, jl = faceVertexUvs2.length; j < jl; j++) { const uvs2 = faceVertexUvs2[j], uvsCopy = []; for (let k = 0, kl = uvs2.length; k < kl; k++) uvsCopy.push(uvs2[k].clone()); this.faceVertexUvs[i].push(uvsCopy); } } } mergeMesh(mesh) { if (!(mesh && mesh.isMesh)) { console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.", mesh); return; } if (mesh.matrixAutoUpdate) mesh.updateMatrix(); this.merge(mesh.geometry, mesh.matrix); } mergeVertices(precisionPoints = 4) { const verticesMap = {}; const unique = [], changes = []; const precision = Math.pow(10, precisionPoints); for (let i = 0, il = this.vertices.length; i < il; i++) { const v = this.vertices[i]; const key = `${Math.round(v.x * precision)}_${Math.round(v.y * precision)}_${Math.round(v.z * precision)}`; if (verticesMap[key] === void 0) { verticesMap[key] = i; unique.push(this.vertices[i]); changes[i] = unique.length - 1; } else changes[i] = changes[verticesMap[key]]; } const faceIndicesToRemove = []; for (let i = 0, il = this.faces.length; i < il; i++) { const face = this.faces[i]; face.a = changes[face.a]; face.b = changes[face.b]; face.c = changes[face.c]; const indices = [ face.a, face.b, face.c ]; for (let n = 0; n < 3; n++) if (indices[n] === indices[(n + 1) % 3]) { faceIndicesToRemove.push(i); break; } } for (let i = faceIndicesToRemove.length - 1; i >= 0; i--) { const idx = faceIndicesToRemove[i]; this.faces.splice(idx, 1); for (let j = 0, jl = this.faceVertexUvs.length; j < jl; j++) this.faceVertexUvs[j].splice(idx, 1); } const diff = this.vertices.length - unique.length; this.vertices = unique; return diff; } setFromPoints(points) { this.vertices = []; for (let i = 0, l = points.length; i < l; i++) { const point = points[i]; this.vertices.push(new Vector3(point.x, point.y, point.z || 0)); } return this; } sortFacesByMaterialIndex() { const faces = this.faces; const length = faces.length; for (let i = 0; i < length; i++) faces[i]._id = i; function materialIndexSort(a, b) { return a.materialIndex - b.materialIndex; } faces.sort(materialIndexSort); const uvs1 = this.faceVertexUvs[0]; const uvs2 = this.faceVertexUvs[1]; let newUvs1, newUvs2; if (uvs1 && uvs1.length === length) newUvs1 = []; if (uvs2 && uvs2.length === length) newUvs2 = []; for (let i = 0; i < length; i++) { const id = faces[i]._id; if (newUvs1) newUvs1.push(uvs1[id]); if (newUvs2) newUvs2.push(uvs2[id]); } if (newUvs1) this.faceVertexUvs[0] = newUvs1; if (newUvs2) this.faceVertexUvs[1] = newUvs2; } toJSON() { const data = { metadata: { version: 4.5, type: "Geometry", generator: "Geometry.toJSON" } }; data.uuid = this.uuid; data.type = this.type; if (this.name !== "") data.name = this.name; if (this.parameters !== void 0) { const parameters = this.parameters; for (let key in parameters) if (parameters[key] !== void 0) data[key] = parameters[key]; return data; } const vertices = []; for (let i = 0; i < this.vertices.length; i++) { const vertex = this.vertices[i]; vertices.push(vertex.x, vertex.y, vertex.z); } const faces = []; const normals = []; const normalsHash = {}; const colors = []; const colorsHash = {}; const uvs = []; const uvsHash = {}; for (let i = 0; i < this.faces.length; i++) { const face = this.faces[i]; const hasMaterial = true; const hasFaceUv = false; const hasFaceVertexUv = this.faceVertexUvs[0][i] !== void 0; const hasFaceNormal = face.normal.length() > 0; const hasFaceVertexNormal = face.vertexNormals.length > 0; const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; const hasFaceVertexColor = face.vertexColors.length > 0; let faceType = 0; faceType = setBit(faceType, 0, 0); faceType = setBit(faceType, 1, hasMaterial); faceType = setBit(faceType, 2, hasFaceUv); faceType = setBit(faceType, 3, hasFaceVertexUv); faceType = setBit(faceType, 4, hasFaceNormal); faceType = setBit(faceType, 5, hasFaceVertexNormal); faceType = setBit(faceType, 6, hasFaceColor); faceType = setBit(faceType, 7, hasFaceVertexColor); faces.push(faceType); faces.push(face.a, face.b, face.c); faces.push(face.materialIndex); if (hasFaceVertexUv) { const faceVertexUvs = this.faceVertexUvs[0][i]; faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2])); } if (hasFaceNormal) faces.push(getNormalIndex(face.normal)); if (hasFaceVertexNormal) { const vertexNormals = face.vertexNormals; faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2])); } if (hasFaceColor) faces.push(getColorIndex(face.color)); if (hasFaceVertexColor) { const vertexColors = face.vertexColors; faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2])); } } function setBit(value, position, enabled) { return enabled ? value | 1 << position : value & ~(1 << position); } function getNormalIndex(normal) { const hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); if (normalsHash[hash] !== void 0) return normalsHash[hash]; normalsHash[hash] = normals.length / 3; normals.push(normal.x, normal.y, normal.z); return normalsHash[hash]; } function getColorIndex(color) { const hash = color.r.toString() + color.g.toString() + color.b.toString(); if (colorsHash[hash] !== void 0) return colorsHash[hash]; colorsHash[hash] = colors.length; colors.push(color.getHex()); return colorsHash[hash]; } function getUvIndex(uv) { const hash = uv.x.toString() + uv.y.toString(); if (uvsHash[hash] !== void 0) return uvsHash[hash]; uvsHash[hash] = uvs.length / 2; uvs.push(uv.x, uv.y); return uvsHash[hash]; } data.data = {}; data.data.vertices = vertices; data.data.normals = normals; if (colors.length > 0) data.data.colors = colors; if (uvs.length > 0) data.data.uvs = [uvs]; data.data.faces = faces; return data; } clone() { return new Geometry2().copy(this); } copy(source) { this.vertices = []; this.colors = []; this.faces = []; this.faceVertexUvs = [[]]; this.morphTargets = []; this.morphNormals = []; this.skinWeights = []; this.skinIndices = []; this.lineDistances = []; this.boundingBox = null; this.boundingSphere = null; this.name = source.name; const vertices = source.vertices; for (let i = 0, il = vertices.length; i < il; i++) this.vertices.push(vertices[i].clone()); const colors = source.colors; for (let i = 0, il = colors.length; i < il; i++) this.colors.push(colors[i].clone()); const faces = source.faces; for (let i = 0, il = faces.length; i < il; i++) this.faces.push(faces[i].clone()); for (let i = 0, il = source.faceVertexUvs.length; i < il; i++) { const faceVertexUvs = source.faceVertexUvs[i]; if (this.faceVertexUvs[i] === void 0) this.faceVertexUvs[i] = []; for (let j = 0, jl = faceVertexUvs.length; j < jl; j++) { const uvs = faceVertexUvs[j], uvsCopy = []; for (let k = 0, kl = uvs.length; k < kl; k++) { const uv = uvs[k]; uvsCopy.push(uv.clone()); } this.faceVertexUvs[i].push(uvsCopy); } } const morphTargets = source.morphTargets; for (let i = 0, il = morphTargets.length; i < il; i++) { const morphTarget = {}; morphTarget.name = morphTargets[i].name; if (morphTargets[i].vertices !== void 0) { morphTarget.vertices = []; for (let j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) morphTarget.vertices.push(morphTargets[i].vertices[j].clone()); } if (morphTargets[i].normals !== void 0) { morphTarget.normals = []; for (let j = 0, jl = morphTargets[i].normals.length; j < jl; j++) morphTarget.normals.push(morphTargets[i].normals[j].clone()); } this.morphTargets.push(morphTarget); } const morphNormals = source.morphNormals; for (let i = 0, il = morphNormals.length; i < il; i++) { const morphNormal = {}; if (morphNormals[i].vertexNormals !== void 0) { morphNormal.vertexNormals = []; for (let j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) { const srcVertexNormal = morphNormals[i].vertexNormals[j]; const destVertexNormal = {}; destVertexNormal.a = srcVertexNormal.a.clone(); destVertexNormal.b = srcVertexNormal.b.clone(); destVertexNormal.c = srcVertexNormal.c.clone(); morphNormal.vertexNormals.push(destVertexNormal); } } if (morphNormals[i].faceNormals !== void 0) { morphNormal.faceNormals = []; for (let j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone()); } this.morphNormals.push(morphNormal); } const skinWeights = source.skinWeights; for (let i = 0, il = skinWeights.length; i < il; i++) this.skinWeights.push(skinWeights[i].clone()); const skinIndices = source.skinIndices; for (let i = 0, il = skinIndices.length; i < il; i++) this.skinIndices.push(skinIndices[i].clone()); const lineDistances = source.lineDistances; for (let i = 0, il = lineDistances.length; i < il; i++) this.lineDistances.push(lineDistances[i]); const boundingBox = source.boundingBox; if (boundingBox !== null) this.boundingBox = boundingBox.clone(); const boundingSphere = source.boundingSphere; if (boundingSphere !== null) this.boundingSphere = boundingSphere.clone(); this.elementsNeedUpdate = source.elementsNeedUpdate; this.verticesNeedUpdate = source.verticesNeedUpdate; this.uvsNeedUpdate = source.uvsNeedUpdate; this.normalsNeedUpdate = source.normalsNeedUpdate; this.colorsNeedUpdate = source.colorsNeedUpdate; this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate; this.groupsNeedUpdate = source.groupsNeedUpdate; return this; } toBufferGeometry() { const geometry = new DirectGeometry().fromGeometry(this); const buffergeometry = new BufferGeometry(); const positions = new Float32Array(geometry.vertices.length * 3); buffergeometry.setAttribute("position", new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices)); if (geometry.normals.length > 0) { const normals = new Float32Array(geometry.normals.length * 3); buffergeometry.setAttribute("normal", new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals)); } if (geometry.colors.length > 0) { const colors = new Float32Array(geometry.colors.length * 3); buffergeometry.setAttribute("color", new BufferAttribute(colors, 3).copyColorsArray(geometry.colors)); } if (geometry.uvs.length > 0) { const uvs = new Float32Array(geometry.uvs.length * 2); buffergeometry.setAttribute("uv", new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs)); } if (geometry.uvs2.length > 0) { const uvs2 = new Float32Array(geometry.uvs2.length * 2); buffergeometry.setAttribute("uv2", new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2)); } buffergeometry.groups = geometry.groups; for (let name in geometry.morphTargets) { const array = []; const morphTargets = geometry.morphTargets[name]; for (let i = 0, l = morphTargets.length; i < l; i++) { const morphTarget = morphTargets[i]; const attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3); attribute.name = morphTarget.name; array.push(attribute.copyVector3sArray(morphTarget.data)); } buffergeometry.morphAttributes[name] = array; } if (geometry.skinIndices.length > 0) { const skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4); buffergeometry.setAttribute("skinIndex", skinIndices.copyVector4sArray(geometry.skinIndices)); } if (geometry.skinWeights.length > 0) { const skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4); buffergeometry.setAttribute("skinWeight", skinWeights.copyVector4sArray(geometry.skinWeights)); } if (geometry.boundingSphere !== null) buffergeometry.boundingSphere = geometry.boundingSphere.clone(); if (geometry.boundingBox !== null) buffergeometry.boundingBox = geometry.boundingBox.clone(); return buffergeometry; } computeTangents() { console.error("THREE.Geometry: .computeTangents() has been removed."); } computeLineDistances() { console.error("THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead."); } applyMatrix(matrix) { console.warn("THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4()."); return this.applyMatrix4(matrix); } dispose() { this.dispatchEvent({ type: "dispose" }); } } return Geometry2; })(); var DirectGeometry = class { constructor() { this.vertices = []; this.normals = []; this.colors = []; this.uvs = []; this.uvs2 = []; this.groups = []; this.morphTargets = {}; this.skinWeights = []; this.skinIndices = []; this.boundingBox = null; this.boundingSphere = null; this.verticesNeedUpdate = false; this.normalsNeedUpdate = false; this.colorsNeedUpdate = false; this.uvsNeedUpdate = false; this.groupsNeedUpdate = false; } computeGroups(geometry) { const groups = []; let group, i; let materialIndex = void 0; const faces = geometry.faces; for (i = 0; i < faces.length; i++) { const face = faces[i]; if (face.materialIndex !== materialIndex) { materialIndex = face.materialIndex; if (group !== void 0) { group.count = i * 3 - group.start; groups.push(group); } group = { start: i * 3, materialIndex }; } } if (group !== void 0) { group.count = i * 3 - group.start; groups.push(group); } this.groups = groups; } fromGeometry(geometry) { const faces = geometry.faces; const vertices = geometry.vertices; const faceVertexUvs = geometry.faceVertexUvs; const hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0; const hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; const morphTargets = geometry.morphTargets; const morphTargetsLength = morphTargets.length; let morphTargetsPosition; if (morphTargetsLength > 0) { morphTargetsPosition = []; for (let i = 0; i < morphTargetsLength; i++) morphTargetsPosition[i] = { name: morphTargets[i].name, data: [] }; this.morphTargets.position = morphTargetsPosition; } const morphNormals = geometry.morphNormals; const morphNormalsLength = morphNormals.length; let morphTargetsNormal; if (morphNormalsLength > 0) { morphTargetsNormal = []; for (let i = 0; i < morphNormalsLength; i++) morphTargetsNormal[i] = { name: morphNormals[i].name, data: [] }; this.morphTargets.normal = morphTargetsNormal; } const skinIndices = geometry.skinIndices; const skinWeights = geometry.skinWeights; const hasSkinIndices = skinIndices.length === vertices.length; const hasSkinWeights = skinWeights.length === vertices.length; if (vertices.length > 0 && faces.length === 0) console.error("THREE.DirectGeometry: Faceless geometries are not supported."); for (let i = 0; i < faces.length; i++) { const face = faces[i]; this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]); const vertexNormals = face.vertexNormals; if (vertexNormals.length === 3) this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]); else { const normal = face.normal; this.normals.push(normal, normal, normal); } const vertexColors = face.vertexColors; if (vertexColors.length === 3) this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]); else { const color = face.color; this.colors.push(color, color, color); } if (hasFaceVertexUv === true) { const vertexUvs = faceVertexUvs[0][i]; if (vertexUvs !== void 0) this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]); else { console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ", i); this.uvs.push(new Vector2(), new Vector2(), new Vector2()); } } if (hasFaceVertexUv2 === true) { const vertexUvs = faceVertexUvs[1][i]; if (vertexUvs !== void 0) this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]); else { console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ", i); this.uvs2.push(new Vector2(), new Vector2(), new Vector2()); } } for (let j = 0; j < morphTargetsLength; j++) { const morphTarget = morphTargets[j].vertices; morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]); } for (let j = 0; j < morphNormalsLength; j++) { const morphNormal = morphNormals[j].vertexNormals[i]; morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c); } if (hasSkinIndices) this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]); if (hasSkinWeights) this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]); } this.computeGroups(geometry); this.verticesNeedUpdate = geometry.verticesNeedUpdate; this.normalsNeedUpdate = geometry.normalsNeedUpdate; this.colorsNeedUpdate = geometry.colorsNeedUpdate; this.uvsNeedUpdate = geometry.uvsNeedUpdate; this.groupsNeedUpdate = geometry.groupsNeedUpdate; if (geometry.boundingSphere !== null) this.boundingSphere = geometry.boundingSphere.clone(); if (geometry.boundingBox !== null) this.boundingBox = geometry.boundingBox.clone(); return this; } }; var Face3 = class { constructor(a, b, c, normal, color, materialIndex = 0) { this.a = a; this.b = b; this.c = c; this.normal = normal && normal.isVector3 ? normal : new Vector3(); this.vertexNormals = Array.isArray(normal) ? normal : []; this.color = color && color.isColor ? color : new Color(); this.vertexColors = Array.isArray(color) ? color : []; this.materialIndex = materialIndex; } clone() { return new this.constructor().copy(this); } copy(source) { this.a = source.a; this.b = source.b; this.c = source.c; this.normal.copy(source.normal); this.color.copy(source.color); this.materialIndex = source.materialIndex; for (let i = 0, il = source.vertexNormals.length; i < il; i++) this.vertexNormals[i] = source.vertexNormals[i].clone(); for (let i = 0, il = source.vertexColors.length; i < il; i++) this.vertexColors[i] = source.vertexColors[i].clone(); return this; } }; //#endregion //#region 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 wasm = wasm_base; if (WebAssembly.validate(detector)) wasm = wasm_simd; let instance; const promise = WebAssembly.instantiate(unpack(wasm), {}).then((result) => { instance = result.instance; instance.exports.__wasm_call_ctors(); }); function unpack(data) { const result = new Uint8Array(data.length); for (let i = 0; i < data.length; ++i) { const ch = data.charCodeAt(i); result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62; } let write = 0; for (let i = 0; i < data.length; ++i) result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i]; return result.buffer.slice(0, write); } function decode(fun, target, count, size, source, filter) { const sbrk = instance.exports.sbrk; const count4 = count + 3 & -4; const tp = sbrk(count4 * size); const sp = sbrk(source.length); const heap = new Uint8Array(instance.exports.memory.buffer); heap.set(source, sp); const res = fun(tp, count, size, sp, source.length); if (res === 0 && filter) filter(tp, count4, size); target.set(heap.subarray(tp, tp + count * size)); sbrk(tp - sbrk(0)); if (res !== 0) throw new Error(`Malformed buffer data: ${res}`); } const filters = { 0: "", 1: "meshopt_decodeFilterOct", 2: "meshopt_decodeFilterQuat", 3: "meshopt_decodeFilterExp", NONE: "", OCTAHEDRAL: "meshopt_decodeFilterOct", QUATERNION: "meshopt_decodeFilterQuat", EXPONENTIAL: "meshopt_decodeFilterExp" }; const decoders = { 0: "meshopt_decodeVertexBuffer", 1: "meshopt_decodeIndexBuffer", 2: "meshopt_decodeIndexSequence", ATTRIBUTES: "meshopt_decodeVertexBuffer", TRIANGLES: "meshopt_decodeIndexBuffer", INDICES: "meshopt_decodeIndexSequence" }; generated = { ready: promise, supported: true, decodeVertexBuffer(target, count, size, source, filter) { decode(instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]); }, decodeIndexBuffer(target, count, size, source) { decode(instance.exports.meshopt_decodeIndexBuffer, target, count, size, source); }, decodeIndexSequence(target, count, size, source) { decode(instance.exports.meshopt_decodeIndexSequence, target, count, size, source); }, decodeGltfBuffer(target, count, size, source, mode, filter) { decode(instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]); } }; return generated; }; //#endregion export { TDSLoader as $, CSS2DRenderer as $a, MarchingCubes as $i, MotionControllerConstants as $n, HalftonePass as $r, VerticalTiltShiftShader as $t, Wireframe as A, mergeBufferGeometries as Aa, Capsule as Ai, ColorCorrectionShader as An, SAOShader as Ar, calcBSplineDerivatives as At, RGBMLoader as B, FlakesTexture as Ba, SkeletonUtils as Bi, TextGeometry as Bn, SavePass as Br, AsciiEffect as Bt, PositionalAudioHelper as C, TessellateModifier as Ca, STATE$1 as Ci, GammaCorrectionShader as Cn, HalfEdge as Co, ClearMaskPass as Cr, NRRDLoader as Ct, Line2 as D, estimateBytesUsed as Da, Octree as Di, FXAAShader as Dn, MorphBlendMesh as Do, SAOPass as Dr, FontLoader as Dt, LightProbeHelper as E, computeMorphedAttributes as Ea, Lut as Ei, FocusShader as En, MD2CharacterComplex as Eo, AfterimageShader as Er, Font as Et, LWOLoader as F, InstancedFlow as Fa, BokehShader2 as Fi, ACESFilmicToneMappingShader as Fn, ToneMapShader as Fr, calcNURBSDerivatives as Ft, TiltLoader as G, RenderableLine as Ga, GroundProjectedEnv as Gi, RoundedBoxGeometry as Gn, OutlinePass as Gr, AmmoPhysics as Gt, PDBLoader as H, SVGRenderer as Ha, GeometryUtils as Hi, DecalGeometry as Hn, SSAOBlurShader as Hr, OutlineEffect as Ht, PCDLoader as I, getUniforms as Ia, GeometryCompressionUtils as Ii, CSMHelper as In, LuminosityShader as Ir, calcRationalCurveDerivatives as It, AMFLoader as J, RenderableVertex as Ja, ReflectorForSSRPass as Ji, XRHandModelFactory as Jn, FilmShader as Jr, InteractiveGroup as Jt, KTXLoader as K, RenderableObject as Ka, Water2 as Ki, ParametricGeometries as Kn, CopyShader as Kr, SelectionBox as Kt, VOXData3DTexture as L, initSplineTexture as La, PackedPhongMaterial as Li, CSM as Ln, TexturePass as Lr, calcSurfacePoint as Lt, LineGeometry as M, toCreasedNormals as Ma, MeshSurfaceSampler as Mi, BlendShader as Mn, UnrealBloomPass as Mr, calcBasisFunctionDerivatives as Mt, LineSegmentsGeometry as N, toTrianglesDrawMode as Na, CinematicCamera as Ni, BleachBypassShader as Nn, LuminosityHighPassShader as Nr, calcBasisFunctions as Nt, LineSegments2 as O, interleaveAttributes as Oa, ImprovedNoise as Oi, DOFMipMapShader as On, MD2Loader as Oo, BlurShaderUtils as Or, FBXLoader as Ot, PLYLoader as P, Flow as Pa, BokehDepthShader as Pi, BasicShader as Pn, AdaptiveToneMappingPass as Pr, calcKoverI as Pt, LDrawLoader as Q, CSS2DObject as Qa, SimplexNoise as Qi, MotionController as Qn, SMAAWeightsShader as Qr, VignetteShader as Qt, VOXLoader as R, modifyShader as Ra, ShadowMapViewer as Ri, CSMShader as Rn, BokehPass as Rr, findSpan as Rt, VertexNormalsHelper as S, GLTFExporter as Sa, OrbitControlsExp as Si, GodRaysGenerateShader as Sn, Face$1 as So, EffectComposer as Sr, STLLoader as St, RaycasterHelper as T, SimplifyModifier as Ta, ColorMapKeywords as Ti, FreiChenShader as Tn, VertexNode as To, AfterimagePass as Tr, TGALoader as Tt, HDRCubeTextureLoader as U, Projector as Ua, UVsDebug as Ui, DecalVertex as Un, SSAODepthShader as Ur, PeppersGhostEffect as Ut, PRWMLoader as V, SVGObject as Va, RoughnessMipmapper as Vi, TeapotGeometry as Vn, SSAOPass as Vr, AnaglyphEffect as Vt, DRACOLoader as W, RenderableFace as Wa, SceneUtils as Wi, BoxLineGeometry as Wn, SSAOShader as Wr, ParallaxBarrierEffect as Wt, Rhino3dmLoader as X, CSS3DRenderer as Xa, LightningStorm as Xi, XREstimatedLight as Xn, SMAABlendShader as Xr, WaterRefractionShader as Xt, OBJLoader as Y, CSS3DObject as Ya, ReflectorRTT as Yi, XRHandPrimitiveModel as Yn, SMAAPass as Yr, HTMLMesh as Yt, SVGLoader as Z, CSS3DSprite as Za, LightningStrike as Zi, XRControllerModelFactory as Zn, SMAAEdgesShader as Zr, VolumeRenderShader1 as Zt, VivianiCurve as _, MMDExporter as _a, TransformControlsGizmo as _i, HorizontalTiltShiftShader as _n, Gyroscope as _o, SSRBlurShader as _r, KMZLoader as _t, DecoratedTorusKnot4a as a, ShadowMesh as aa, ShaderPass as ai, ToonShaderHatching as an, getErrorMessage as ao, OculusHandModel as ar, VTKLoader as at, RectAreaLightUniformsLib as b, PLYExporter as ba, CameraControls as bi, GodRaysDepthMaskShader as bn, ConvexGeometry as bo, DotScreenPass as br, XLoader as bt, DecoratedTorusKnot5c as c, BatchedMesh as ca, FlyControls as ci, SobelOperatorShader as cn, isWebGL2Available as co, ARButton as cr, EXRLoader as ct, HeartCurve as d, CCDIKHelper as da, OrbitControls as di, PixelShader as dn, RollerCoasterGeometry as do, ConvolutionShader as dr, RGBELoader as dt, edgeTable as ea, HalftoneShader as ei, VerticalBlurShader as en, ProgressiveLightMap as eo, fetchProfile as er, BasisTextureLoader as et, HelixCurve as f, CCDIKSolver as fa, TrackballControls as fi, ParallaxShader as fn, RollerCoasterLiftersGeometry as fo, RenderPixelatedPass as fr, TTFLoader as ft, TrefoilPolynomialKnot as g, STLExporter as ga, TransformControls as gi, HueSaturationShader as gn, MorphAnimMesh as go, SSRPass as gr, VRMLoader as gt, TrefoilKnot as h, OBJExporter as ha, DragControls as hi, KaleidoShader as hn, TreesGeometry as ho, SSAARenderPass as hr, VRMLLoader as ht, CinquefoilKnot as i, LensflareElement as ia, LUTPass as ii, ToonShaderDotted as in, MD2Character as io, OculusHandPointerModel as ir, LUT3dlLoader as it, LineMaterial as j, mergeVertices as ja, OBB as ji, BrightnessContrastShader as jn, CubeTexturePass as jr, calcBSplinePoint as jt, WireframeGeometry2 as k, mergeBufferAttributes as ka, ColorConverter as ki, ColorifyShader as kn, DepthLimitedBlurShader as kr, NURBSCurve as kt, FigureEightPolynomialKnot as l, MMDAnimationHelper as la, ArcballControls as li, SepiaShader as ln, isWebGLAvailable as lo, WaterPass as lr, MDDLoader as lt, TorusKnot as m, RoomEnvironment as ma, PointerLockControls as mi, MirrorShader as mn, SkyGeometry as mo, TAARenderPass as mr, KTX2Loader as mt, Face3 as n, Water as na, DigitalGlitch as ni, ToonShader1 as nn, TubePainter as no, VRButton as nr, PVRLoader as nt, DecoratedTorusKnot4b as o, Refractor as oa, FullScreenQuad as oi, TechnicolorShader as on, getWebGL2ErrorMessage as oo, XRHandMeshModel as or, XYZLoader as ot, KnotCurve as p, AnimationClipCreator as pa, DeviceOrientationControls as pi, NormalMapShader as pn, RollerCoasterShadowGeometry as po, RenderPass as pr, LottieLoader as pt, MMDLoader as q, RenderableSprite as qa, Sky as qi, ParametricGeometry as qn, FilmPass as qr, SelectionHelper as qt, Geometry as r, Lensflare as ra, ClearPass as ri, ToonShader2 as rn, VolumeSlice as ro, createText as rr, DDSLoader as rt, DecoratedTorusKnot5a as s, Reflector as sa, Pass as si, SubsurfaceScatteringShader as sn, getWebGLErrorMessage as so, GLTFLoader as sr, ThreeMFLoader as st, MeshoptDecoder as t, triTable as ta, GlitchPass as ti, TriangleBlurShader as tn, Volume as to, fetchProfilesList as tr, GCodeLoader as tt, GrannyKnot as u, MMDPhysics as ua, MapControls as ui, RGBShiftShader as un, Timer as uo, BloomPass as ur, AssimpLoader as ut, NURBSSurface as v, ColladaExporter as va, TransformControlsPlane as vi, HorizontalBlurShader as vn, GPUComputationRenderer as vo, SSRDepthShader as vr, ColladaLoader as vt, VertexTangentsHelper as w, EdgeSplitModifier as wa, TrackballControlsExp as wi, FresnelShader as wn, VertexList as wo, MaskPass as wr, LUTCubeLoader as wt, RectAreaLightHelper as x, USDZExporter as xa, MapControlsExp as xi, GodRaysFakeSunShader as xn, ConvexHull as xo, DotScreenShader as xr, MTLLoader as xt, LightProbeGenerator as y, DRACOExporter as ya, FirstPersonControls as yi, GodRaysCombineShader as yn, ConvexObjectBreaker as yo, SSRShader as yr, BVHLoader as yt, VOXMesh as z, updateSplineTexture as za, UnpackDepthRGBAShader as zi, CSMFrustum as zn, BokehShader as zr, StereoEffect as zt }; //# sourceMappingURL=three-stdlib-BHZ1qH6e.js.map