PageSourceSearch

https://www.dneg.com/_next/static/chunks/77c02b24-620491a124952a04.js

js dneg.com collected 2026-10-02 02:28:15 UTC 352,162 bytes, 1,295 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4168],{76612:function(e,t,r){let i,a,n,s,o,l,c,u,h;r.d(t,{L1_:function(){return LineGeometry},YRm:function(){return LineMaterial},wUb:function(){return LineSegments2},w_R:function(){return Line2},zOz:function(){return LineSegmentsGeometry}});var d,p,f,m,g,v,y,T,x,S,E,b,R,A,_,M,C,w,I,P=r(96995);r(87367);var N=r(58558),O=r(54937);r(53553);var L=Object.defineProperty,__defNormalProp=(e,t,r)=>t in e?L(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__publicField=(e,t,r)=>(__defNormalProp(e,"symbol"!=typeof t?t+"":t,r),r);function decompress(e,t=1/0,r=null){a||(a=new P.PlaneGeometry(2,2,1,1)),n||(n=new P.ShaderMaterial({uniforms:{blitTexture:new P.Uniform(e)},vertexShader:`
2        varying vec2 vUv;
3        void main(){
4            vUv = uv;
5            gl_Position = vec4(position.xy * 1.0,0.,.999999);
6        }
7      `,fragmentShader:`
8          uniform sampler2D blitTexture; 
9          varying vec2 vUv;
10
11          void main(){ 
12              gl_FragColor = vec4(vUv.xy, 0, 1);
13              
14              #ifdef IS_SRGB
15              gl_FragColor = LinearTosRGB( texture2D( blitTexture, vUv) );
16              #else
17              gl_FragColor = texture2D( blitTexture, vUv);
18              #endif
19          }
20      `})),n.uniforms.blitTexture.value=e,n.defines.IS_SRGB="colorSpace"in e?"srgb"===e.colorSpace:3001===e.encoding,n.needsUpdate=!0,s||((s=new P.Mesh(a,n)).frustrumCulled=!1);let o=new P.PerspectiveCamera,l=new P.Scene;l.add(s),r||(r=i=new P.WebGLRenderer({antialias:!1})),r.setSize(Math.min(e.image.width,t),Math.min(e.image.height,t)),r.clear(),r.render(l,o);let c=new P.Texture(r.domElement);return c.minFilter=e.minFilter,c.magFilter=e.magFilter,c.wrapS=e.wrapS,c.wrapT=e.wrapT,c.name=e.name,i&&(i.dispose(),i=null),c}let k={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"]};let GLTFExporter=class GLTFExporter{constructor(){this.pluginCallbacks=[],this.register(function(e){return new GLTFLightExtension(e)}),this.register(function(e){return new z(e)}),this.register(function(e){return new W(e)}),this.register(function(e){return new H(e)}),this.register(function(e){return new K(e)}),this.register(function(e){return new $(e)}),this.register(function(e){return new j(e)}),this.register(function(e){return new G(e)}),this.register(function(e){return new Y(e)}),this.register(function(e){return new X(e)}),this.register(function(e){return new Z(e)})}register(e){return -1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return -1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,r,i){let a=new GLTFWriter,n=[];for(let e=0,t=this.pluginCallbacks.length;e<t;e++)n.push(this.pluginCallbacks[e](a));a.setPlugins(n),a.write(e,t,i).catch(r)}parseAsync(e,t){let r=this;return new Promise(function(i,a){r.parse(e,i,a,t)})}};let F={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,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},D="KHR_mesh_quantization",U={};U[P.NearestFilter]=F.NEAREST,U[P.NearestMipmapNearestFilter]=F.NEAREST_MIPMAP_NEAREST,U[P.NearestMipmapLinearFilter]=F.NEAREST_MIPMAP_LINEAR,U[P.LinearFilter]=F.LINEAR,U[P.LinearMipmapNearestFilter]=F.LINEAR_MIPMAP_NEAREST,U[P.LinearMipmapLinearFilter]=F.LINEAR_MIPMAP_LINEAR,U[P.ClampToEdgeWrapping]=F.CLAMP_TO_EDGE,U[P.RepeatWrapping]=F.REPEAT,U[P.MirroredRepeatWrapping]=F.MIRRORED_REPEAT;let B={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},V=new P.Color;function equalArray(e,t){return e.length===t.length&&e.every(function(e,r){return e===t[r]})}function getPaddedBufferSize(e){return 4*Math.ceil(e/4)}function getPaddedArrayBuffer(e,t=0){let r=getPaddedBufferSize(e.byteLength);if(r!==e.byteLength){let i=new Uint8Array(r);if(i.set(new Uint8Array(e)),0!==t)for(let a=e.byteLength;a<r;a++)i[a]=t;return i.buffer}return e}function getCanvas(){return"undefined"==typeof document&&"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(1,1):document.createElement("canvas")}function getToBlobPromise(e,t){let r;return void 0!==e.toBlob?new Promise(r=>e.toBlob(r,t)):("image/jpeg"===t?r=.92:"image/webp"===t&&(r=.8),e.convertToBlob({type:t,quality:r}))}let GLTFWriter=class GLTFWriter{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter"}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map}}setPlugins(e){this.plugins=e}async write(e,t,r={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},r),this.options.animations.length>0&&(this.options.trs=!0),this.processInput(e),await Promise.all(this.pending);let i=this.buffers,a=this.json;r=this.options;let n=this.extensionsUsed,s=this.extensionsRequired,o=new Blob(i,{type:"application/octet-stream"}),l=Object.keys(n),c=Object.keys(s);if(l.length>0&&(a.extensionsUsed=l),c.length>0&&(a.extensionsRequired=c),a.buffers&&a.buffers.length>0&&(a.buffers[0].byteLength=o.size),!0===r.binary){let e=new FileReader;e.readAsArrayBuffer(o),e.onloadend=function(){var r;let i=getPaddedArrayBuffer(e.result),n=new DataView(new ArrayBuffer(8));n.setUint32(0,i.byteLength,!0),n.setUint32(4,5130562,!0);let s=getPaddedArrayBuffer((r=JSON.stringify(a),new TextEncoder().encode(r).buffer),32),o=new DataView(new ArrayBuffer(8));o.setUint32(0,s.byteLength,!0),o.setUint32(4,1313821514,!0);let l=new ArrayBuffer(12),c=new DataView(l);c.setUint32(0,1179937895,!0),c.setUint32(4,2,!0);let u=12+o.byteLength+s.byteLength+n.byteLength+i.byteLength;c.setUint32(8,u,!0);let h=new Blob([l,o,s,n,i],{type:"application/octet-stream"}),d=new FileReader;d.readAsArrayBuffer(h),d.onloadend=function(){t(d.result)}}}else if(a.buffers&&a.buffers.length>0){let e=new FileReader;
20e.readAsDataURL(o),e.onloadend=function(){let r=e.result;a.buffers[0].uri=r,t(a)}}else t(a)}serializeUserData(e,t){if(0===Object.keys(e.userData).length)return;let r=this.options,i=this.extensionsUsed;try{let a=JSON.parse(JSON.stringify(e.userData));if(r.includeCustomExtensions&&a.gltfExtensions){for(let e in void 0===t.extensions&&(t.extensions={}),a.gltfExtensions)t.extensions[e]=a.gltfExtensions[e],i[e]=!0;delete a.gltfExtensions}Object.keys(a).length>0&&(t.extras=a)}catch(t){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+t.message)}}getUID(e,t=!1){if(!1===this.uids.has(e)){let t=new Map;t.set(!0,this.uid++),t.set(!1,this.uid++),this.uids.set(e,t)}let r=this.uids.get(e);return r.get(t)}isNormalizedNormalAttribute(e){let t=this.cache;if(t.attributesNormalized.has(e))return!1;let r=new P.Vector3;for(let t=0,i=e.count;t<i;t++)if(Math.abs(r.fromBufferAttribute(e,t).length()-1)>5e-4)return!1;return!0}createNormalizedNormalAttribute(e){let t=this.cache;if(t.attributesNormalized.has(e))return t.attributesNormalized.get(e);let r=e.clone(),i=new P.Vector3;for(let e=0,t=r.count;e<t;e++)i.fromBufferAttribute(r,e),0===i.x&&0===i.y&&0===i.z?i.setX(1):i.normalize(),r.setXYZ(e,i.x,i.y,i.z);return t.attributesNormalized.set(e,r),r}applyTextureTransform(e,t){let r=!1,i={};(0!==t.offset.x||0!==t.offset.y)&&(i.offset=t.offset.toArray(),r=!0),0!==t.rotation&&(i.rotation=t.rotation,r=!0),(1!==t.repeat.x||1!==t.repeat.y)&&(i.scale=t.repeat.toArray(),r=!0),r&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=i,this.extensionsUsed.KHR_texture_transform=!0)}buildMetalRoughTexture(e,t){if(e===t)return e;function getEncodingConversion(e){return("colorSpace"in e?"srgb"===e.colorSpace:3001===e.encoding)?function(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}:function(e){return e}}console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."),e instanceof P.CompressedTexture&&(e=decompress(e)),t instanceof P.CompressedTexture&&(t=decompress(t));let r=e?e.image:null,i=t?t.image:null,a=Math.max(r?r.width:0,i?i.width:0),n=Math.max(r?r.height:0,i?i.height:0),s=getCanvas();s.width=a,s.height=n;let o=s.getContext("2d");o.fillStyle="#00ffff",o.fillRect(0,0,a,n);let l=o.getImageData(0,0,a,n);if(r){o.drawImage(r,0,0,a,n);let t=getEncodingConversion(e),i=o.getImageData(0,0,a,n).data;for(let e=2;e<i.length;e+=4)l.data[e]=256*t(i[e]/256)}if(i){o.drawImage(i,0,0,a,n);let e=getEncodingConversion(t),r=o.getImageData(0,0,a,n).data;for(let t=1;t<r.length;t+=4)l.data[t]=256*e(r[t]/256)}o.putImageData(l,0,0);let c=e||t,u=c.clone();return u.source=new P.Texture(s).source,"colorSpace"in u?u.colorSpace="":u.encoding=3e3,u.channel=(e||t).channel,e&&t&&e.channel!==t.channel&&console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."),u}processBuffer(e){let t=this.json,r=this.buffers;return t.buffers||(t.buffers=[{byteLength:0}]),r.push(e),0}processBufferView(e,t,r,i,a){let n;let s=this.json;switch(s.bufferViews||(s.bufferViews=[]),t){case F.BYTE:case F.UNSIGNED_BYTE:n=1;break;case F.SHORT:case F.UNSIGNED_SHORT:n=2;break;default:n=4}let o=getPaddedBufferSize(i*e.itemSize*n),l=new DataView(new ArrayBuffer(o)),c=0;for(let a=r;a<r+i;a++)for(let r=0;r<e.itemSize;r++){let i;e.itemSize>4?i=e.array[a*e.itemSize+r]:(0===r?i=e.getX(a):1===r?i=e.getY(a):2===r?i=e.getZ(a):3===r&&(i=e.getW(a)),!0===e.normalized&&(i=P.MathUtils.normalize(i,e.array))),t===F.FLOAT?l.setFloat32(c,i,!0):t===F.INT?l.setInt32(c,i,!0):t===F.UNSIGNED_INT?l.setUint32(c,i,!0):t===F.SHORT?l.setInt16(c,i,!0):t===F.UNSIGNED_SHORT?l.setUint16(c,i,!0):t===F.BYTE?l.setInt8(c,i):t===F.UNSIGNED_BYTE&&l.setUint8(c,i),c+=n}let u={buffer:this.processBuffer(l.buffer),byteOffset:this.byteOffset,byteLength:o};void 0!==a&&(u.target=a),a===F.ARRAY_BUFFER&&(u.byteStride=e.itemSize*n),this.byteOffset+=o,s.bufferViews.push(u);let h={id:s.bufferViews.length-1,byteLength:0};return h}processBufferViewImage(e){let t=this,r=t.json;return r.bufferViews||(r.bufferViews=[]),new Promise(function(i){let a=new FileReader;a.readAsArrayBuffer(e),a.onloadend=function(){let e=getPaddedArrayBuffer(a.result),n={buffer:t.processBuffer(e),byteOffset:t.byteOffset,byteLength:e.byteLength};t.byteOffset+=e.byteLength,i(r.bufferViews.push(n)-1)}})}
20processAccessor(e,t,r,i){let a,n;let s=this.json;if(e.array.constructor===Float32Array)a=F.FLOAT;else if(e.array.constructor===Int32Array)a=F.INT;else if(e.array.constructor===Uint32Array)a=F.UNSIGNED_INT;else if(e.array.constructor===Int16Array)a=F.SHORT;else if(e.array.constructor===Uint16Array)a=F.UNSIGNED_SHORT;else if(e.array.constructor===Int8Array)a=F.BYTE;else if(e.array.constructor===Uint8Array)a=F.UNSIGNED_BYTE;else throw Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);if(void 0===r&&(r=0),void 0===i&&(i=e.count),0===i)return null;let o=function(e,t,r){let i={min:Array(e.itemSize).fill(Number.POSITIVE_INFINITY),max:Array(e.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let a=t;a<t+r;a++)for(let t=0;t<e.itemSize;t++){let r;e.itemSize>4?r=e.array[a*e.itemSize+t]:(0===t?r=e.getX(a):1===t?r=e.getY(a):2===t?r=e.getZ(a):3===t&&(r=e.getW(a)),!0===e.normalized&&(r=P.MathUtils.normalize(r,e.array))),i.min[t]=Math.min(i.min[t],r),i.max[t]=Math.max(i.max[t],r)}return i}(e,r,i);void 0!==t&&(n=e===t.index?F.ELEMENT_ARRAY_BUFFER:F.ARRAY_BUFFER);let l=this.processBufferView(e,a,r,i,n),c={bufferView:l.id,byteOffset:l.byteOffset,componentType:a,count:i,max:o.max,min:o.min,type:{1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"}[e.itemSize]};return!0===e.normalized&&(c.normalized=!0),s.accessors||(s.accessors=[]),s.accessors.push(c)-1}processImage(e,t,r,i="image/png"){if(null!==e){let a=this,n=a.cache,s=a.json,o=a.options,l=a.pending;n.images.has(e)||n.images.set(e,{});let c=n.images.get(e),u=i+":flipY/"+r.toString();if(void 0!==c[u])return c[u];s.images||(s.images=[]);let h={mimeType:i},d=getCanvas();d.width=Math.min(e.width,o.maxTextureSize),d.height=Math.min(e.height,o.maxTextureSize);let p=d.getContext("2d");if(!0===r&&(p.translate(0,d.height),p.scale(1,-1)),void 0!==e.data){t!==P.RGBAFormat&&console.error("GLTFExporter: Only RGBAFormat is supported.",t),(e.width>o.maxTextureSize||e.height>o.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);let r=new Uint8ClampedArray(e.height*e.width*4);for(let t=0;t<r.length;t+=4)r[t+0]=e.data[t+0],r[t+1]=e.data[t+1],r[t+2]=e.data[t+2],r[t+3]=e.data[t+3];p.putImageData(new ImageData(r,e.width,e.height),0,0)}else p.drawImage(e,0,0,d.width,d.height);!0===o.binary?l.push(getToBlobPromise(d,i).then(e=>a.processBufferViewImage(e)).then(e=>{h.bufferView=e})):void 0!==d.toDataURL?h.uri=d.toDataURL(i):l.push(getToBlobPromise(d,i).then(e=>new FileReader().readAsDataURL(e)).then(e=>{h.uri=e}));let f=s.images.push(h)-1;return c[u]=f,f}throw Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){let t=this.json;t.samplers||(t.samplers=[]);let r={magFilter:U[e.magFilter],minFilter:U[e.minFilter],wrapS:U[e.wrapS],wrapT:U[e.wrapT]};return t.samplers.push(r)-1}processTexture(e){let t=this.options,r=this.cache,i=this.json;if(r.textures.has(e))return r.textures.get(e);i.textures||(i.textures=[]),e instanceof P.CompressedTexture&&(e=decompress(e,t.maxTextureSize));let a=e.userData.mimeType;"image/webp"===a&&(a="image/png");let n={sampler:this.processSampler(e),source:this.processImage(e.image,e.format,e.flipY,a)};e.name&&(n.name=e.name),this._invokeAll(function(t){t.writeTexture&&t.writeTexture(e,n)});let s=i.textures.push(n)-1;return r.textures.set(e,s),s}processMaterial(e){let t=this.cache,r=this.json;if(t.materials.has(e))return t.materials.get(e);if(e.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;r.materials||(r.materials=[]);let i={pbrMetallicRoughness:{}};!0!==e.isMeshStandardMaterial&&!0!==e.isMeshBasicMaterial&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");let a=e.color.toArray().concat([e.opacity]);if(equalArray(a,[1,1,1,1])||(i.pbrMetallicRoughness.baseColorFactor=a),e.isMeshStandardMaterial?(i.pbrMetallicRoughness.metallicFactor=e.metalness,i.pbrMetallicRoughness.roughnessFactor=e.roughness):(i.pbrMetallicRoughness.metallicFactor=.5,i.pbrMetallicRoughness.roughnessFactor=.5),e.metalnessMap||e.roughnessMap){let t=this.buildMetalRoughTexture(e.metalnessMap,e.roughnessMap),r
20={index:this.processTexture(t),channel:t.channel};this.applyTextureTransform(r,t),i.pbrMetallicRoughness.metallicRoughnessTexture=r}if(e.map){let t={index:this.processTexture(e.map),texCoord:e.map.channel};this.applyTextureTransform(t,e.map),i.pbrMetallicRoughness.baseColorTexture=t}if(e.emissive){let t=e.emissive,r=Math.max(t.r,t.g,t.b);if(r>0&&(i.emissiveFactor=e.emissive.toArray()),e.emissiveMap){let t={index:this.processTexture(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(t,e.emissiveMap),i.emissiveTexture=t}}if(e.normalMap){let t={index:this.processTexture(e.normalMap),texCoord:e.normalMap.channel};e.normalScale&&1!==e.normalScale.x&&(t.scale=e.normalScale.x),this.applyTextureTransform(t,e.normalMap),i.normalTexture=t}if(e.aoMap){let t={index:this.processTexture(e.aoMap),texCoord:e.aoMap.channel};1!==e.aoMapIntensity&&(t.strength=e.aoMapIntensity),this.applyTextureTransform(t,e.aoMap),i.occlusionTexture=t}e.transparent?i.alphaMode="BLEND":e.alphaTest>0&&(i.alphaMode="MASK",i.alphaCutoff=e.alphaTest),e.side===P.DoubleSide&&(i.doubleSided=!0),""!==e.name&&(i.name=e.name),this.serializeUserData(e,i),this._invokeAll(function(t){t.writeMaterial&&t.writeMaterial(e,i)});let n=r.materials.push(i)-1;return t.materials.set(e,n),n}processMesh(e){let t;let r=this.cache,i=this.json,a=[e.geometry.uuid];if(Array.isArray(e.material))for(let t=0,r=e.material.length;t<r;t++)a.push(e.material[t].uuid);else a.push(e.material.uuid);let n=a.join(":");if(r.meshes.has(n))return r.meshes.get(n);let s=e.geometry;t=e.isLineSegments?F.LINES:e.isLineLoop?F.LINE_LOOP:e.isLine?F.LINE_STRIP:e.isPoints?F.POINTS:e.material.wireframe?F.LINES:F.TRIANGLES;let o={},l={},c=[],u=[],h={uv:"TEXCOORD_0",[P.REVISION.replace(/\D+/g,"")>=152?"uv1":"uv2"]:"TEXCOORD_1",color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},d=s.getAttribute("normal");void 0===d||this.isNormalizedNormalAttribute(d)||(console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."),s.setAttribute("normal",this.createNormalizedNormalAttribute(d)));let p=null;for(let e in s.attributes){if("morph"===e.slice(0,5))continue;let t=s.attributes[e];e=h[e]||e.toUpperCase();let i=/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;if(i.test(e)||(e="_"+e),r.attributes.has(this.getUID(t))){l[e]=r.attributes.get(this.getUID(t));continue}p=null;let a=t.array;"JOINTS_0"!==e||a instanceof Uint16Array||a instanceof Uint8Array||(console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'),p=new P.BufferAttribute(new Uint16Array(a),t.itemSize,t.normalized));let n=this.processAccessor(p||t,s);null!==n&&(e.startsWith("_")||this.detectMeshQuantization(e,t),l[e]=n,r.attributes.set(this.getUID(t),n))}if(void 0!==d&&s.setAttribute("normal",d),0===Object.keys(l).length)return null;if(void 0!==e.morphTargetInfluences&&e.morphTargetInfluences.length>0){let t=[],i=[],a={};if(void 0!==e.morphTargetDictionary)for(let t in e.morphTargetDictionary)a[e.morphTargetDictionary[t]]=t;for(let n=0;n<e.morphTargetInfluences.length;++n){let o={},l=!1;for(let e in s.morphAttributes){if("position"!==e&&"normal"!==e){l||(console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."),l=!0);continue}let t=s.morphAttributes[e][n],i=e.toUpperCase(),a=s.attributes[e];if(r.attributes.has(this.getUID(t,!0))){o[i]=r.attributes.get(this.getUID(t,!0));continue}let c=t.clone();if(!s.morphTargetsRelative)for(let e=0,r=t.count;e<r;e++)for(let r=0;r<t.itemSize;r++)0===r&&c.setX(e,t.getX(e)-a.getX(e)),1===r&&c.setY(e,t.getY(e)-a.getY(e)),2===r&&c.setZ(e,t.getZ(e)-a.getZ(e)),3===r&&c.setW(e,t.getW(e)-a.getW(e));o[i]=this.processAccessor(c,s),r.attributes.set(this.getUID(a,!0),o[i])}u.push(o),t.push(e.morphTargetInfluences[n]),void 0!==e.morphTargetDictionary&&i.push(a[n])}o.weights=t,i.length>0&&(o.extras={},o.extras.targetNames=i)}let f=Array.isArray(e.material);if(f&&0===s.groups.length)return null;let m=f?e.material:[e.material],g=f?s.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let e=0,i=g.length;e<i;e++){let i={mode:t,attributes:l};if(this.serializeUserData(s,i),u.length>0&&(i.targets=u),null!==s.index){let t=this.getUID(s.index);(void 0!==g[e].start||void 0!==g[e].count)&&(t+=":"+g[e].start+":"+g[e].
20count),r.attributes.has(t)?i.indices=r.attributes.get(t):(i.indices=this.processAccessor(s.index,s,g[e].start,g[e].count),r.attributes.set(t,i.indices)),null===i.indices&&delete i.indices}let a=this.processMaterial(m[g[e].materialIndex]);null!==a&&(i.material=a),c.push(i)}o.primitives=c,i.meshes||(i.meshes=[]),this._invokeAll(function(t){t.writeMesh&&t.writeMesh(e,o)});let v=i.meshes.push(o)-1;return r.meshes.set(n,v),v}detectMeshQuantization(e,t){let r;if(this.extensionsUsed[D])return;switch(t.array.constructor){case Int8Array:r="byte";break;case Uint8Array:r="unsigned byte";break;case Int16Array:r="short";break;case Uint16Array:r="unsigned short";break;default:return}t.normalized&&(r+=" normalized");let i=e.split("_",1)[0];k[i]&&k[i].includes(r)&&(this.extensionsUsed[D]=!0,this.extensionsRequired[D]=!0)}processCamera(e){let t=this.json;t.cameras||(t.cameras=[]);let r=e.isOrthographicCamera,i={type:r?"orthographic":"perspective"};return r?i.orthographic={xmag:2*e.right,ymag:2*e.top,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:i.perspective={aspectRatio:e.aspect,yfov:P.MathUtils.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},""!==e.name&&(i.name=e.type),t.cameras.push(i)-1}processAnimation(e,t){let r=this.json,i=this.nodeMap;r.animations||(r.animations=[]),e=GLTFExporter.Utils.mergeMorphTargetTracks(e.clone(),t);let a=e.tracks,n=[],s=[];for(let e=0;e<a.length;++e){let r;let o=a[e],l=P.PropertyBinding.parseTrackName(o.name),c=P.PropertyBinding.findNode(t,l.nodeName),u=B[l.propertyName];if("bones"===l.objectName&&(c=!0===c.isSkinnedMesh?c.skeleton.getBoneByName(l.objectIndex):void 0),!c||!u)return console.warn('THREE.GLTFExporter: Could not export animation track "%s".',o.name),null;let h=o.values.length/o.times.length;u===B.morphTargetInfluences&&(h/=c.morphTargetInfluences.length),!0===o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline?(r="CUBICSPLINE",h/=3):r=o.getInterpolation()===P.InterpolateDiscrete?"STEP":"LINEAR",s.push({input:this.processAccessor(new P.BufferAttribute(o.times,1)),output:this.processAccessor(new P.BufferAttribute(o.values,h)),interpolation:r}),n.push({sampler:s.length-1,target:{node:i.get(c),path:u}})}return r.animations.push({name:e.name||"clip_"+r.animations.length,samplers:s,channels:n}),r.animations.length-1}processSkin(e){let t=this.json,r=this.nodeMap,i=t.nodes[r.get(e)],a=e.skeleton;if(void 0===a)return null;let n=e.skeleton.bones[0];if(void 0===n)return null;let s=[],o=new Float32Array(16*a.bones.length),l=new P.Matrix4;for(let t=0;t<a.bones.length;++t)s.push(r.get(a.bones[t])),l.copy(a.boneInverses[t]),l.multiply(e.bindMatrix).toArray(o,16*t);void 0===t.skins&&(t.skins=[]),t.skins.push({inverseBindMatrices:this.processAccessor(new P.BufferAttribute(o,16)),joints:s,skeleton:r.get(n)});let c=i.skin=t.skins.length-1;return c}processNode(e){let t=this.json,r=this.options,i=this.nodeMap;t.nodes||(t.nodes=[]);let a={};if(r.trs){let t=e.quaternion.toArray(),r=e.position.toArray(),i=e.scale.toArray();equalArray(t,[0,0,0,1])||(a.rotation=t),equalArray(r,[0,0,0])||(a.translation=r),equalArray(i,[1,1,1])||(a.scale=i)}else e.matrixAutoUpdate&&e.updateMatrix(),!1===equalArray(e.matrix.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])&&(a.matrix=e.matrix.elements);if(""!==e.name&&(a.name=String(e.name)),this.serializeUserData(e,a),e.isMesh||e.isLine||e.isPoints){let t=this.processMesh(e);null!==t&&(a.mesh=t)}else e.isCamera&&(a.camera=this.processCamera(e));if(e.isSkinnedMesh&&this.skins.push(e),e.children.length>0){let t=[];for(let i=0,a=e.children.length;i<a;i++){let a=e.children[i];if(a.visible||!1===r.onlyVisible){let e=this.processNode(a);null!==e&&t.push(e)}}t.length>0&&(a.children=t)}this._invokeAll(function(t){t.writeNode&&t.writeNode(e,a)});let n=t.nodes.push(a)-1;return i.set(e,n),n}processScene(e){let t=this.json,r=this.options;t.scenes||(t.scenes=[],t.scene=0);let i={};""!==e.name&&(i.name=e.name),t.scenes.push(i);let a=[];for(let t=0,i=e.children.length;t<i;t++){let i=e.children[t];if(i.visible||!1===r.onlyVisible){let e=this.processNode(i);null!==e&&a.push(e)}}a.length>0&&(i.nodes=a),this.serializeUserData(e,i)}processObjects(e){let t=new P.Scene;t.name="AuxScene";for(let r=0;r<e.length;r++)t.children.push(e[r]);this.processScene(t)}processInput(e){let t=this.options;e=e instanceof Array?e:[e],this._invokeAll(function(t){t.beforeParse&&t.beforeParse(e)});let r=[];for(let t=0;t<e.length;t++)e[t]instanceof P.Scene?this.processScene(e[t]):r.push(e[t]);r.length>0&&this.processObjects(r);for(let e=0;e<this.skins.length;++e)this.processSkin(this.skins[e]);for(let r=0;r<t.animations.length;++r)this.processAnimation(t.animations[r],e[0]);this._invokeAll(function(t){t.afterParse&&t.afterParse(e)})}_invokeAll(e){for(let t=0,r=this.plugins.length;t<r;t++)e(this.plugins[t])}};let GLTFLightExtension=class GLTFLightExtension{constructor(e){this.writer=e,this.name="KHR_lights_punctual"}writeNode(e,t){if(!e.isLight)return;if(!e.isDirectionalLight&&!e.isPointLight&&!e.isSpotLight){console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.",e);return}let r=this.writer,i=r.json,a=r.extensionsUsed,n={};e.name&&(n.name=e.name),n.color=e.color.toArray(),n.intensity=e.intensity,e.isDirectionalLight?n.type="directional":e.isPointLight?(n.type="point",e.distance>0&&(n.range=e.distance)):e.isSpotLight&&(n.type="spot",e.distance>0&&(n.range=e.distance),n.spot={},n.spot.innerConeAngle=-((e.penumbra-1)*e.angle*1),n.spot.outerConeAngle=e.angle),void 0!==e.decay&&2!==e.decay&&console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."),e.target&&(e.target.parent!==e||0!==e.target.position.x||0!==e.target.position.y||-1!==e.target.position.z)&&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."),a[this.name]||(i.extensions=i.extensions||{},i.extensions[this.name]={lights:[]},a[this.name]=!0);let s=i.extensions[this.name].lights;s.push(n),t.extensions=t.extensions||{},t.extensions[this.name]={light:s.length-1}}};let z=class{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}writeMaterial(e,t){if(!e.isMeshBasicMaterial)return;let r=this.writer,i=r.extensionsUsed;t.extensions=t.extensions||{},t.extensions[this.name]={},i[this.name]=!0,t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=.9}},j=class{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0===e.clearcoat)return;let r=this.writer,i=r.extensionsUsed,a={};if(a.clearcoatFactor=e.clearcoat,e.clearcoatMap){let t={index:r.processTexture(e.clearcoatMap),texCoord:e.clearcoatMap.channel};r.applyTextureTransform(t,e.clearcoatMap),a.clearcoatTexture=t}if(a.clearcoatRoughnessFactor=e.clearcoatRoughness,e.clearcoatRoughnessMap){let t={index:r.processTexture(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};r.applyTextureTransform(t,e.clearcoatRoughnessMap),a.clearcoatRoughnessTexture=t}if(e.clearcoatNormalMap){let t={index:r.processTexture(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};r.applyTextureTransform(t,e.clearcoatNormalMap),a.clearcoatNormalTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=a,i[this.name]=!0}},G=class{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0===e.iridescence)return;let r=this.writer,i=r.extensionsUsed,a={};if(a.iridescenceFactor=e.iridescence,e.iridescenceMap){let t={index:r.processTexture(e.iridescenceMap),texCoord:e.iridescenceMap.channel};r.applyTextureTransform(t,e.iridescenceMap),a.iridescenceTexture=t}if(a.iridescenceIor=e.iridescenceIOR,a.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],a.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1],e.iridescenceThicknessMap){let t={index:r.processTexture(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};r.applyTextureTransform(t,e.iridescenceThicknessMap),a.iridescenceThicknessTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=a,i[this.name]=!0}},W=class{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;let r=this.writer,i=r.extensionsUsed,a={};if(a.transmissionFactor=e.transmission,e.transmissionMap){let t={index:r.processTexture(e.transmissionMap),texCoord:e.transmissionMap.channel};r.applyTextureTransform(t,e.transmissionMap),a.transmissionTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=a,i[this.name]=!0}},H=class{constructor(e){this.writer=e,this.name="KHR_materials_volume"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;let r=this.writer,i=r.extensionsUsed,a={};if(a.thicknessFactor=e.thickness,e.thicknessMap){let t={index:r.processTexture(e.thicknessMap),texCoord:e.thicknessMap.channel};r.applyTextureTransform(t,e.thicknessMap),a.thicknessTexture=t}a.attenuationDistance=e.attenuationDistance,a.attenuationColor=e.attenuationColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=a,i[this.name]=!0}},K=class{constructor(e){this.writer=e,this.name="KHR_materials_ior"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||1.5===e.ior)return;let r=this.writer,i=r.extensionsUsed,a={};a.ior=e.ior,t.extensions=t.extensions||{},t.extensions[this.name]=a,i[this.name]=!0}},$=class{constructor(e){this.writer=e,this.name="KHR_materials_specular"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||1===e.specularIntensity&&e.specularColor.equals(V)&&!e.specularIntensityMap&&!e.specularColorTexture)return;let r=this.writer,i=r.extensionsUsed,a={};if(e.specularIntensityMap){let t={index:r.processTexture(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};r.applyTextureTransform(t,e.specularIntensityMap),a.specularTexture=t}if(e.specularColorMap){let t={index:r.processTexture(e.specularColorMap),texCoord:e.specularColorMap.channel};r.applyTextureTransform(t,e.specularColorMap),a.specularColorTexture=t}a.specularFactor=e.specularIntensity,a.specularColorFactor=e.specularColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=a,i[this.name]=!0}},Y=class{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0==e.sheen)return;let r=this.writer,i=r.extensionsUsed,a={};if(e.sheenRoughnessMap){let t={index:r.processTexture(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};r.applyTextureTransform(t,e.sheenRoughnessMap),a.sheenRoughnessTexture=t}if(e.sheenColorMap){let t={index:r.processTexture(e.sheenColorMap),texCoord:e.sheenColorMap.channel};r.applyTextureTransform(t,e.sheenColorMap),a.sheenColorTexture=t}a.sheenRoughnessFactor=e.sheenRoughness,a.sheenColorFactor=e.sheenColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=a,i[this.name]=!0}},X=class{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0==e.anisotropy)return;let r=this.writer,i=r.extensionsUsed,a={};if(e.anisotropyMap){let t={index:r.processTexture(e.anisotropyMap)};r.applyTextureTransform(t,e.anisotropyMap),a.anisotropyTexture=t}a.anisotropyStrength=e.anisotropy,a.anisotropyRotation=e.anisotropyRotation,t.extensions=t.extensions||{},t.extensions[this.name]=a,i[this.name]=!0}},Z=class{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}writeMaterial(e,t){if(!e.isMeshStandardMaterial||1===e.emissiveIntensity)return;let r=this.writer,i=r.extensionsUsed,a={};a.emissiveStrength=e.emissiveIntensity,t.extensions=t.extensions||{},t.extensions[this.name]=a,i[this.name]=!0}};GLTFExporter.Utils={insertKeyframe:function(e,t){let r;let i=e.getValueSize(),a=new e.TimeBufferType(e.times.length+1),n=new e.ValueBufferType(e.values.length+i),s=e.createInterpolant(new e.ValueBufferType(i));if(0===e.times.length){a[0]=t;for(let e=0;e<i;e++)n[e]=0;r=0}
20else if(t<e.times[0]){if(.001>Math.abs(e.times[0]-t))return 0;a[0]=t,a.set(e.times,1),n.set(s.evaluate(t),0),n.set(e.values,i),r=0}else if(t>e.times[e.times.length-1]){if(.001>Math.abs(e.times[e.times.length-1]-t))return e.times.length-1;a[a.length-1]=t,a.set(e.times,0),n.set(e.values,0),n.set(s.evaluate(t),e.values.length),r=a.length-1}else for(let o=0;o<e.times.length;o++){if(.001>Math.abs(e.times[o]-t))return o;if(e.times[o]<t&&e.times[o+1]>t){a.set(e.times.slice(0,o+1),0),a[o+1]=t,a.set(e.times.slice(o+1),o+2),n.set(e.values.slice(0,(o+1)*i),0),n.set(s.evaluate(t),(o+1)*i),n.set(e.values.slice((o+1)*i),(o+2)*i),r=o+1;break}}return e.times=a,e.values=n,r},mergeMorphTargetTracks:function(e,t){let r=[],i={},a=e.tracks;for(let e=0;e<a.length;++e){let n,s=a[e],o=P.PropertyBinding.parseTrackName(s.name),l=P.PropertyBinding.findNode(t,o.nodeName);if("morphTargetInfluences"!==o.propertyName||void 0===o.propertyIndex){r.push(s);continue}if(s.createInterpolant!==s.InterpolantFactoryMethodDiscrete&&s.createInterpolant!==s.InterpolantFactoryMethodLinear){if(s.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline)throw Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."),(s=s.clone()).setInterpolation(P.InterpolateLinear)}let c=l.morphTargetInfluences.length,u=l.morphTargetDictionary[o.propertyIndex];if(void 0===u)throw Error("THREE.GLTFExporter: Morph target name not found: "+o.propertyIndex);if(void 0===i[l.uuid]){n=s.clone();let e=new n.ValueBufferType(c*n.times.length);for(let t=0;t<n.times.length;t++)e[t*c+u]=n.values[t];n.name=(o.nodeName||"")+".morphTargetInfluences",n.values=e,i[l.uuid]=n,r.push(n);continue}let h=s.createInterpolant(new s.ValueBufferType(1));n=i[l.uuid];for(let e=0;e<n.times.length;e++)n.values[e*c+u]=h.evaluate(n.times[e]);for(let e=0;e<s.times.length;e++){let t=this.insertKeyframe(n,s.times[e]);n.values[t*c+u]=s.values[e]}}return e.tracks=r,e}};let q=class{parse(e,t={decodeSpeed:5,encodeSpeed:5,encoderMethod:q.MESH_EDGEBREAKER_ENCODING,quantization:[16,8,8,8,8],exportUvs:!0,exportNormals:!0,exportColor:!1}){let r,i,a;if(e instanceof P.BufferGeometry&&e.isBufferGeometry)throw Error("DRACOExporter: The first parameter of parse() is now an instance of Mesh or Points.");if(void 0===DracoEncoderModule)throw Error("THREE.DRACOExporter: required the draco_encoder to work.");let n=e.geometry,s=DracoEncoderModule(),o=new s.Encoder;if(!n.isBufferGeometry)throw Error("THREE.DRACOExporter.parse(geometry, options): geometry is not a THREE.BufferGeometry instance.");if(e instanceof P.Mesh&&e.isMesh){r=new s.MeshBuilder,i=new s.Mesh;let e=n.getAttribute("position");r.AddFloatAttributeToMesh(i,s.POSITION,e.count,e.itemSize,e.array);let a=n.getIndex();if(null!==a)r.AddFacesToMesh(i,a.count/3,a.array);else{let t=new(e.count>65535?Uint32Array:Uint16Array)(e.count);for(let e=0;e<t.length;e++)t[e]=e;r.AddFacesToMesh(i,e.count,t)}if(t.exportNormals){let e=n.getAttribute("normal");void 0!==e&&r.AddFloatAttributeToMesh(i,s.NORMAL,e.count,e.itemSize,e.array)}if(t.exportUvs){let e=n.getAttribute("uv");void 0!==e&&r.AddFloatAttributeToMesh(i,s.TEX_COORD,e.count,e.itemSize,e.array)}if(t.exportColor){let e=n.getAttribute("color");void 0!==e&&r.AddFloatAttributeToMesh(i,s.COLOR,e.count,e.itemSize,e.array)}}else if(e instanceof P.Points&&e.isPoints){r=new s.PointCloudBuilder,i=new s.PointCloud;let e=n.getAttribute("position");if(r.AddFloatAttribute(i,s.POSITION,e.count,e.itemSize,e.array),t.exportColor){let e=n.getAttribute("color");void 0!==e&&r.AddFloatAttribute(i,s.COLOR,e.count,e.itemSize,e.array)}}else throw Error("DRACOExporter: Unsupported object type.");let l=new s.DracoInt8Array,c=void 0!==t.encodeSpeed?t.encodeSpeed:5,u=void 0!==t.decodeSpeed?t.decodeSpeed:5;if(o.SetSpeedOptions(c,u),void 0!==t.encoderMethod&&o.SetEncodingMethod(t.encoderMethod),void 0!==t.quantization)for(let e=0;e<5;e++)void 0!==t.quantization[e]&&o.SetAttributeQuantization(e,t.quantization[e]);if(a=e instanceof P.Mesh&&e.isMesh?o.EncodeMeshToDracoBuffer(i,l):o.EncodePointCloudToDracoBuffer(i,!0,l),s.destroy(i),0===a)throw Error("THREE.DRACOExporter: Draco encoding failed.");let h=new Int8Array(new ArrayBuffer(a));for(let e=0;e<a;e++)h[e]=l.GetValue(e);return s.destroy(l),s.destroy(o),s.destroy(r),h}};__publicField(q,"MESH_EDGEBREAKER_ENCODING",1),__publicField(q,"MESH_SEQUENTIAL_ENCODING",0),__publicField(q,"POINT_CLOUD",0),__publicField(q,"TRIANGULAR_MESH",1),__publicField(q,"INVALID",-1),__publicField(q,"POSITION",0),__publicField(q,"NORMAL",1),__publicField(q,"COLOR",2),__publicField(q,"TEX_COORD",3),__publicField(q,"GENERIC",4);let Q=class extends P.Mesh{constructor(e,t={}){super(e),this.isReflector=!0,this.type="Reflector",this.camera=new P.PerspectiveCamera;let r=this,i=new P.Color(void 0!==t.color?t.color:8355711),a=t.textureWidth||512,n=t.textureHeight||512,s=t.clipBias||0,o=t.shader||Q.ReflectorShader,l=void 0!==t.multisample?t.multisample:4,c=new P.Plane,u=new P.Vector3,h=new P.Vector3,d=new P.Vector3,p=new P.Matrix4,f=new P.Vector3(0,0,-1),m=new P.Vector4,g=new P.Vector3,v=new P.Vector3,y=new P.Vector4,T=new P.Matrix4,x=this.camera,S=new P.WebGLRenderTarget(a,n,{samples:l,type:P.HalfFloatType}
20),E=new P.ShaderMaterial({uniforms:P.UniformsUtils.clone(o.uniforms),fragmentShader:o.fragmentShader,vertexShader:o.vertexShader});E.uniforms.tDiffuse.value=S.texture,E.uniforms.color.value=i,E.uniforms.textureMatrix.value=T,this.material=E,this.onBeforeRender=function(e,t,i){if(h.setFromMatrixPosition(r.matrixWorld),d.setFromMatrixPosition(i.matrixWorld),p.extractRotation(r.matrixWorld),u.set(0,0,1),u.applyMatrix4(p),g.subVectors(h,d),g.dot(u)>0)return;g.reflect(u).negate(),g.add(h),p.extractRotation(i.matrixWorld),f.set(0,0,-1),f.applyMatrix4(p),f.add(d),v.subVectors(h,f),v.reflect(u).negate(),v.add(h),x.position.copy(g),x.up.set(0,1,0),x.up.applyMatrix4(p),x.up.reflect(u),x.lookAt(v),x.far=i.far,x.updateMatrixWorld(),x.projectionMatrix.copy(i.projectionMatrix),T.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),T.multiply(x.projectionMatrix),T.multiply(x.matrixWorldInverse),T.multiply(r.matrixWorld),c.setFromNormalAndCoplanarPoint(u,h),c.applyMatrix4(x.matrixWorldInverse),m.set(c.normal.x,c.normal.y,c.normal.z,c.constant);let a=x.projectionMatrix;y.x=(Math.sign(m.x)+a.elements[8])/a.elements[0],y.y=(Math.sign(m.y)+a.elements[9])/a.elements[5],y.z=-1,y.w=(1+a.elements[10])/a.elements[14],m.multiplyScalar(2/m.dot(y)),a.elements[2]=m.x,a.elements[6]=m.y,a.elements[10]=m.z+1-s,a.elements[14]=m.w,r.visible=!1;let n=e.getRenderTarget(),o=e.xr.enabled,l=e.shadowMap.autoUpdate,E=e.toneMapping,b=!1;b="outputColorSpace"in e?"srgb"===e.outputColorSpace:3001===e.outputEncoding,e.xr.enabled=!1,e.shadowMap.autoUpdate=!1,"outputColorSpace"in e?e.outputColorSpace="linear-srgb":e.outputEncoding=3e3,e.toneMapping=P.NoToneMapping,e.setRenderTarget(S),e.state.buffers.depth.setMask(!0),!1===e.autoClear&&e.clear(),e.render(t,x),e.xr.enabled=o,e.shadowMap.autoUpdate=l,e.toneMapping=E,"outputColorSpace"in e?e.outputColorSpace=b?"srgb":"srgb-linear":e.outputEncoding=b?3001:3e3,e.setRenderTarget(n);let R=i.viewport;void 0!==R&&e.state.viewport(R),r.visible=!0},this.getRenderTarget=function(){return S},this.dispose=function(){S.dispose(),r.material.dispose()}}};__publicField(Q,"ReflectorShader",{uniforms:{color:{value:null},tDiffuse:{value:null},textureMatrix:{value:null}},vertexShader:`
21		uniform mat4 textureMatrix;
22		varying vec4 vUv;
23
24		#include <common>
25		#include <logdepthbuf_pars_vertex>
26
27		void main() {
28
29			vUv = textureMatrix * vec4( position, 1.0 );
30
31			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
32
33			#include <logdepthbuf_vertex>
34
35		}`,fragmentShader:`
36		uniform vec3 color;
37		uniform sampler2D tDiffuse;
38		varying vec4 vUv;
39
40		#include <logdepthbuf_pars_fragment>
41
42		float blendOverlay( float base, float blend ) {
43
44			return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
45
46		}
47
48		vec3 blendOverlay( vec3 base, vec3 blend ) {
49
50			return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
51
52		}
53
54		void main() {
55
56			#include <logdepthbuf_fragment>
57
58			vec4 base = texture2DProj( tDiffuse, vUv );
59			gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
60
61			#include <tonemapping_fragment>
62			#include <${parseInt(P.REVISION.replace(/\D+/g,""))>=154?"colorspace_fragment":"encodings_fragment"}>
63
64		}`});let J=class extends P.Mesh{constructor(e,t={}){super(e),this.isRefractor=!0,this.type="Refractor",this.camera=new P.PerspectiveCamera;let r=this,i=new P.Color(void 0!==t.color?t.color:8355711),a=t.textureWidth||512,n=t.textureHeight||512,s=t.clipBias||0,o=t.shader||J.RefractorShader,l=void 0!==t.multisample?t.multisample:4,c=this.camera;c.matrixAutoUpdate=!1,c.userData.refractor=!0;let u=new P.Plane,h=new P.Matrix4,d=new P.WebGLRenderTarget(a,n,{samples:l,type:P.HalfFloatType});this.material=new P.ShaderMaterial({uniforms:P.UniformsUtils.clone(o.uniforms),vertexShader:o.vertexShader,fragmentShader:o.fragmentShader,transparent:!0}),this.material.uniforms.color.value=i,this.material.uniforms.tDiffuse.value=d.texture,this.material.uniforms.textureMatrix.value=h;let p=function(){let e=new P.Vector3,t=new P.Vector3,i=new P.Matrix4,a=new P.Vector3,
64n=new P.Vector3;return function(s){return e.setFromMatrixPosition(r.matrixWorld),t.setFromMatrixPosition(s.matrixWorld),a.subVectors(e,t),i.extractRotation(r.matrixWorld),n.set(0,0,1),n.applyMatrix4(i),0>a.dot(n)}}(),f=function(){let e=new P.Vector3,t=new P.Vector3,i=new P.Quaternion,a=new P.Vector3;return function(){r.matrixWorld.decompose(t,i,a),e.set(0,0,1).applyQuaternion(i).normalize(),e.negate(),u.setFromNormalAndCoplanarPoint(e,t)}}(),m=function(){let e=new P.Plane,t=new P.Vector4,r=new P.Vector4;return function(i){c.matrixWorld.copy(i.matrixWorld),c.matrixWorldInverse.copy(c.matrixWorld).invert(),c.projectionMatrix.copy(i.projectionMatrix),c.far=i.far,e.copy(u),e.applyMatrix4(c.matrixWorldInverse),t.set(e.normal.x,e.normal.y,e.normal.z,e.constant);let a=c.projectionMatrix;r.x=(Math.sign(t.x)+a.elements[8])/a.elements[0],r.y=(Math.sign(t.y)+a.elements[9])/a.elements[5],r.z=-1,r.w=(1+a.elements[10])/a.elements[14],t.multiplyScalar(2/t.dot(r)),a.elements[2]=t.x,a.elements[6]=t.y,a.elements[10]=t.z+1-s,a.elements[14]=t.w}}();this.onBeforeRender=function(e,t,i){!0!==i.userData.refractor&&!0!=!p(i)&&(f(),h.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),h.multiply(i.projectionMatrix),h.multiply(i.matrixWorldInverse),h.multiply(r.matrixWorld),m(i),function(e,t,i){r.visible=!1;let a=e.getRenderTarget(),n=e.xr.enabled,s=e.shadowMap.autoUpdate,o=e.toneMapping,l=!1;l="outputColorSpace"in e?"srgb"===e.outputColorSpace:3001===e.outputEncoding,e.xr.enabled=!1,e.shadowMap.autoUpdate=!1,"outputColorSpace"in e?e.outputColorSpace="linear-srgb":e.outputEncoding=3e3,e.toneMapping=P.NoToneMapping,e.setRenderTarget(d),!1===e.autoClear&&e.clear(),e.render(t,c),e.xr.enabled=n,e.shadowMap.autoUpdate=s,e.toneMapping=o,e.setRenderTarget(a),"outputColorSpace"in e?e.outputColorSpace=l?"srgb":"srgb-linear":e.outputEncoding=l?3001:3e3;let u=i.viewport;void 0!==u&&e.state.viewport(u),r.visible=!0}(e,t,i))},this.getRenderTarget=function(){return d},this.dispose=function(){d.dispose(),r.material.dispose()}}};__publicField(J,"RefractorShader",{uniforms:{color:{value:null},tDiffuse:{value:null},textureMatrix:{value:null}},vertexShader:`
65
66		uniform mat4 textureMatrix;
67
68		varying vec4 vUv;
69
70		void main() {
71
72			vUv = textureMatrix * vec4( position, 1.0 );
73			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
74
75		}`,fragmentShader:`
76
77		uniform vec3 color;
78		uniform sampler2D tDiffuse;
79
80		varying vec4 vUv;
81
82		float blendOverlay( float base, float blend ) {
83
84			return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
85
86		}
87
88		vec3 blendOverlay( vec3 base, vec3 blend ) {
89
90			return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
91
92		}
93
94		void main() {
95
96			vec4 base = texture2DProj( tDiffuse, vUv );
97			gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
98
99			#include <tonemapping_fragment>
100			#include <${parseInt(P.REVISION.replace(/\D+/g,""))>=154?"colorspace_fragment":"encodings_fragment"}>
101
102		}`});let ee=new P.BufferGeometry,et=class extends P.Mesh{constructor(){super(et.Geometry,new P.MeshBasicMaterial({opacity:0,transparent:!0})),this.isLensflare=!0,this.type="Lensflare",this.frustumCulled=!1,this.renderOrder=1/0;let e=new P.Vector3,t=new P.Vector3,r=new P.DataTexture(new Uint8Array(768),16,16,P.RGBAFormat);r.minFilter=P.NearestFilter,r.magFilter=P.NearestFilter,r.wrapS=P.ClampToEdgeWrapping,r.wrapT=P.ClampToEdgeWrapping;let i=new P.DataTexture(new Uint8Array(768),16,16,P.RGBAFormat);i.minFilter=P.NearestFilter,i.magFilter=P.NearestFilter,i.wrapS=P.ClampToEdgeWrapping,i.wrapT=P.ClampToEdgeWrapping;let a=et.Geometry,n=new P.RawShaderMaterial({uniforms:{scale:{value:null},screenPosition:{value:null}},vertexShader:`
103
104				precision highp float;
105
106				uniform vec3 screenPosition;
107				uniform vec2 scale;
108
109				attribute vec3 position;
110
111				void main() {
112
113					gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );
114
115				}`,fragmentShader:`
116
117				precision highp float;
118
119				void main() {
120
121					gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 );
122
123				}`,depthTest:!0,depthWrite:!1,transparent:!1}),s=new P.RawShaderMaterial({uniforms:{map:{value:r},scale:{value:null},screenPosition:{value:null}},vertexShader:`
124
125				precision highp float;
126
127				uniform vec3 screenPosition;
128				uniform vec2 scale;
129
130				attribute vec3 position;
131				attribute vec2 uv;
132
133				varying vec2 vUV;
134
135				void main() {
136
137					vUV = uv;
138
139					gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );
140
141				}`,fragmentShader:`
142
143				precision highp float;
144
145				uniform sampler2D map;
146
147				varying vec2 vUV;
148
149				void main() {
150
151					gl_FragColor = texture2D( map, vUV );
152
153				}`,depthTest:!1,depthWrite:!1,transparent:!1}),o=new P.Mesh(a,n),l=[],c=LensflareElement.Shader,u=new P.RawShaderMaterial({uniforms:{map:{value:null},occlusionMap:{value:i},color:{value:new P.Color(16777215)},scale:{value:new P.Vector2},screenPosition:{value:new P.Vector3}},vertexShader:c.vertexShader,fragmentShader:c.fragmentShader,blending:P.AdditiveBlending,transparent:!0,depthWrite:!1}),h=new P.Mesh(a,u);this.addElement=function(e){l.push(e)};let d=new P.Vector2,p=new P.Vector2,f=new P.Box2,m=new P.Vector4;this.onBeforeRender=function(c,g,v){c.getCurrentViewport(m);let y=m.w/m.z,T=m.z/2,x=m.w/2,S=16/m.w;if(d.set(S*y,S),f.min.set(m.x,m.y),f.max.set(m.x+(m.z-16),m.y+(m.w-16)),t.setFromMatrixPosition(this.matrixWorld),t.applyM
153atrix4(v.matrixWorldInverse),!(t.z>0)&&(e.copy(t).applyMatrix4(v.projectionMatrix),p.x=m.x+e.x*T+T-8,p.y=m.y+e.y*x+x-8,f.containsPoint(p))){c.copyFramebufferToTexture(p,r);let t=n.uniforms;t.scale.value=d,t.screenPosition.value=e,c.renderBufferDirect(v,null,a,n,o,null),c.copyFramebufferToTexture(p,i),(t=s.uniforms).scale.value=d,t.screenPosition.value=e,c.renderBufferDirect(v,null,a,s,o,null);let f=-(2*e.x),g=-(2*e.y);for(let t=0,r=l.length;t<r;t++){let r=l[t],i=u.uniforms;i.color.value.copy(r.color),i.map.value=r.texture,i.screenPosition.value.x=e.x+f*r.distance,i.screenPosition.value.y=e.y+g*r.distance,S=r.size/m.w;let n=m.w/m.z;i.scale.value.set(S*n,S),u.uniformsNeedUpdate=!0,c.renderBufferDirect(v,null,a,u,h,null)}}},this.dispose=function(){n.dispose(),s.dispose(),u.dispose(),r.dispose(),i.dispose();for(let e=0,t=l.length;e<t;e++)l[e].texture.dispose()}}};__publicField(et,"Geometry",ee);let LensflareElement=class LensflareElement{constructor(e,t=1,r=0,i=new P.Color(16777215)){this.texture=e,this.size=t,this.distance=r,this.color=i}};__publicField(LensflareElement,"Shader",{uniforms:{map:{value:null},occlusionMap:{value:null},color:{value:null},scale:{value:null},screenPosition:{value:null}},vertexShader:`
154
155		precision highp float;
156
157		uniform vec3 screenPosition;
158		uniform vec2 scale;
159
160		uniform sampler2D occlusionMap;
161
162		attribute vec3 position;
163		attribute vec2 uv;
164
165		varying vec2 vUV;
166		varying float vVisibility;
167
168		void main() {
169
170			vUV = uv;
171
172			vec2 pos = position.xy;
173
174			vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );
175			visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );
176			visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );
177			visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );
178			visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );
179			visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );
180			visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );
181			visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );
182			visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );
183
184			vVisibility =        visibility.r / 9.0;
185			vVisibility *= 1.0 - visibility.g / 9.0;
186			vVisibility *=       visibility.b / 9.0;
187
188			gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );
189
190		}`,fragmentShader:`
191
192		precision highp float;
193
194		uniform sampler2D map;
195		uniform vec3 color;
196
197		varying vec2 vUV;
198		varying float vVisibility;
199
200		void main() {
201
202			vec4 texture = texture2D( map, vUV );
203			texture.a *= vVisibility;
204			gl_FragColor = texture;
205			gl_FragColor.rgb *= color;
206
207		}`}),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]),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,
207-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,
2076,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]);let SimplexNoise=class SimplexNoise{constructor(e=Math){__publicField(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(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(this,"p",[]),__publicField(this,"perm",[]),__publicField(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(this,"dot",(e,t,r)=>
207e[0]*t+e[1]*r),__publicField(this,"dot3",(e,t,r,i)=>e[0]*t+e[1]*r+e[2]*i),__publicField(this,"dot4",(e,t,r,i,a)=>e[0]*t+e[1]*r+e[2]*i+e[3]*a),__publicField(this,"noise",(e,t)=>{let r,i,a;let n=(e+t)*(.5*(Math.sqrt(3)-1)),s=Math.floor(e+n),o=Math.floor(t+n),l=(3-Math.sqrt(3))/6,c=(s+o)*l,u=e-(s-c),h=t-(o-c),d=0,p=1;u>h&&(d=1,p=0);let f=u-d+l,m=h-p+l,g=u-1+2*l,v=h-1+2*l,y=255&s,T=255&o,x=this.perm[y+this.perm[T]]%12,S=this.perm[y+d+this.perm[T+p]]%12,E=this.perm[y+1+this.perm[T+1]]%12,b=.5-u*u-h*h;b<0?r=0:(b*=b,r=b*b*this.dot(this.grad3[x],u,h));let R=.5-f*f-m*m;R<0?i=0:(R*=R,i=R*R*this.dot(this.grad3[S],f,m));let A=.5-g*g-v*v;return A<0?a=0:(A*=A,a=A*A*this.dot(this.grad3[E],g,v)),70*(r+i+a)}),__publicField(this,"noise3d",(e,t,r)=>{let i,a,n,s,o,l,c,u,h,d;let p=(e+t+r)*(1/3),f=Math.floor(e+p),m=Math.floor(t+p),g=Math.floor(r+p),v=1/6,y=(f+m+g)*v,T=e-(f-y),x=t-(m-y),S=r-(g-y);T>=x?x>=S?(o=1,l=0,c=0,u=1,h=1,d=0):(T>=S?(o=1,l=0,c=0):(o=0,l=0,c=1),u=1,h=0,d=1):x<S?(o=0,l=0,c=1,u=0,h=1,d=1):T<S?(o=0,l=1,c=0,u=0,h=1,d=1):(o=0,l=1,c=0,u=1,h=1,d=0);let E=T-o+v,b=x-l+v,R=S-c+v,A=T-u+2*v,_=x-h+2*v,M=S-d+2*v,C=T-1+3*v,w=x-1+3*v,I=S-1+3*v,P=255&f,N=255&m,O=255&g,L=this.perm[P+this.perm[N+this.perm[O]]]%12,k=this.perm[P+o+this.perm[N+l+this.perm[O+c]]]%12,F=this.perm[P+u+this.perm[N+h+this.perm[O+d]]]%12,D=this.perm[P+1+this.perm[N+1+this.perm[O+1]]]%12,U=.6-T*T-x*x-S*S;U<0?i=0:(U*=U,i=U*U*this.dot3(this.grad3[L],T,x,S));let B=.6-E*E-b*b-R*R;B<0?a=0:(B*=B,a=B*B*this.dot3(this.grad3[k],E,b,R));let V=.6-A*A-_*_-M*M;V<0?n=0:(V*=V,n=V*V*this.dot3(this.grad3[F],A,_,M));let z=.6-C*C-w*w-I*I;return z<0?s=0:(z*=z,s=z*z*this.dot3(this.grad3[D],C,w,I)),32*(i+a+n+s)}),__publicField(this,"noise4d",(e,t,r,i)=>{let a,n,s,o,l,c,u,h,d,p,f,m,g,v,y,T,x;let S=this.grad4,E=this.simplex,b=this.perm,R=(5-Math.sqrt(5))/20,A=(e+t+r+i)*((Math.sqrt(5)-1)/4),_=Math.floor(e+A),M=Math.floor(t+A),C=Math.floor(r+A),w=Math.floor(i+A),I=(_+M+C+w)*R,P=e-(_-I),N=t-(M-I),O=r-(C-I),L=i-(w-I),k=P>N?32:0,F=P>O?16:0,D=N>O?8:0,U=P>L?4:0,B=N>L?2:0,V=O>L?1:0,z=k+F+D+U+B+V;c=E[z][0]>=3?1:0,u=E[z][1]>=3?1:0,h=E[z][2]>=3?1:0,d=E[z][3]>=3?1:0,p=E[z][0]>=2?1:0,f=E[z][1]>=2?1:0,m=E[z][2]>=2?1:0,g=E[z][3]>=2?1:0,v=E[z][0]>=1?1:0,y=E[z][1]>=1?1:0,T=E[z][2]>=1?1:0,x=E[z][3]>=1?1:0;let j=P-c+R,G=N-u+R,W=O-h+R,H=L-d+R,K=P-p+2*R,$=N-f+2*R,Y=O-m+2*R,X=L-g+2*R,Z=P-v+3*R,q=N-y+3*R,Q=O-T+3*R,J=L-x+3*R,ee=P-1+4*R,et=N-1+4*R,er=O-1+4*R,ei=L-1+4*R,ea=255&_,en=255&M,es=255&C,eo=255&w,el=b[ea+b[en+b[es+b[eo]]]]%32,ec=b[ea+c+b[en+u+b[es+h+b[eo+d]]]]%32,eu=b[ea+p+b[en+f+b[es+m+b[eo+g]]]]%32,eh=b[ea+v+b[en+y+b[es+T+b[eo+x]]]]%32,ed=b[ea+1+b[en+1+b[es+1+b[eo+1]]]]%32,ep=.6-P*P-N*N-O*O-L*L;ep<0?a=0:(ep*=ep,a=ep*ep*this.dot4(S[el],P,N,O,L));let ef=.6-j*j-G*G-W*W-H*H;ef<0?n=0:(ef*=ef,n=ef*ef*this.dot4(S[ec],j,G,W,H));let em=.6-K*K-$*$-Y*Y-X*X;em<0?s=0:(em*=em,s=em*em*this.dot4(S[eu],K,$,Y,X));let eg=.6-Z*Z-q*q-Q*Q-J*J;eg<0?o=0:(eg*=eg,o=eg*eg*this.dot4(S[eh],Z,q,Q,J));let ev=.6-ee*ee-et*et-er*er-ei*ei;return ev<0?l=0:(ev*=ev,l=ev*ev*this.dot4(S[ed],ee,et,er,ei)),27*(a+n+s+o+l)});for(let t=0;t<256;t++)this.p[t]=Math.floor(256*e.random());for(let e=0;e<512;e++)this.perm[e]=this.p[255&e]}};let er=class extends P.BufferGeometry{constructor(e={}){super(),this.isLightningStrike=!0,this.type="LightningStrike",this.init(er.copyParameters(e,e)),this.createMesh()}static createRandomGenerator(){let e=[];for(let t=0;t<2053;t++)e.push(Math.random());let t={currentSeed:0,random:function(){let r=e[t.currentSeed];return t.currentSeed=(t.currentSeed+1)%2053,r},getSeed:function(){return t.currentSeed/2053},setSeed:function(e){t.currentSeed=Math.floor(2053*e)%2053}};return t}static copyParameters(e={},t={}){let vecCopy=function(r){return t===e?r:r.clone()};return e.sourceOffset=void 0!==t.sourceOffset?vecCopy(t.sourceOffset):new P.Vector3(0,100,0),e.destOffset=void 0!==t.destOffset?vecCopy(t.destOffset):new P.Vector3(0,0,0),e.timeScale=void 0!==t.timeScale?t.timeScale:1,e.roughness=void 0!==t.roughness?t.roughness:.9,e.straightness=void 0!==t.straightness?t.straightness:.7,e.up0=void 0!==t.up0?vecCopy(t.up0):new P.Vector3(0,0,1),e.up1=void 0!==t.up1?vecCopy(t.up1):new P.Vector3(0,0,1),e.radius0=void 0!==t.radius0?t.radius0:1,e.radius1=void 0!==t.radius1?t.radius1:1,e.radius0Factor=void 0!==t.radius0Factor?t.radiu
207s0Factor:.5,e.radius1Factor=void 0!==t.radius1Factor?t.radius1Factor:.2,e.minRadius=void 0!==t.minRadius?t.minRadius:.2,e.isEternal=void 0!==t.isEternal?t.isEternal:void 0===t.birthTime||void 0===t.deathTime,e.birthTime=t.birthTime,e.deathTime=t.deathTime,e.propagationTimeFactor=void 0!==t.propagationTimeFactor?t.propagationTimeFactor:.1,e.vanishingTimeFactor=void 0!==t.vanishingTimeFactor?t.vanishingTimeFactor:.9,e.subrayPeriod=void 0!==t.subrayPeriod?t.subrayPeriod:4,e.subrayDutyCycle=void 0!==t.subrayDutyCycle?t.subrayDutyCycle:.6,e.maxIterations=void 0!==t.maxIterations?t.maxIterations:9,e.isStatic=void 0!==t.isStatic&&t.isStatic,e.ramification=void 0!==t.ramification?t.ramification:5,e.maxSubrayRecursion=void 0!==t.maxSubrayRecursion?t.maxSubrayRecursion:3,e.recursionProbability=void 0!==t.recursionProbability?t.recursionProbability:.6,e.generateUVs=void 0!==t.generateUVs&&t.generateUVs,e.randomGenerator=t.randomGenerator,e.noiseSeed=t.noiseSeed,e.onDecideSubrayCreation=t.onDecideSubrayCreation,e.onSubrayCreation=t.onSubrayCreation,e}update(e){this.isStatic||(this.rayParameters.isEternal||this.rayParameters.birthTime<=e&&e<=this.rayParameters.deathTime?(this.updateMesh(e),e<this.subrays[0].endPropagationTime?this.state=er.RAY_PROPAGATING:e>this.subrays[0].beginVanishingTime?this.state=er.RAY_VANISHING:this.state=er.RAY_STEADY,this.visible=!0):(this.visible=!1,e<this.rayParameters.birthTime?this.state=er.RAY_UNBORN:this.state=er.RAY_EXTINGUISHED))}init(e){this.rayParameters=e,this.maxIterations=void 0!==e.maxIterations?Math.floor(e.maxIterations):9,e.maxIterations=this.maxIterations,this.isStatic=void 0!==e.isStatic&&e.isStatic,e.isStatic=this.isStatic,this.ramification=void 0!==e.ramification?Math.floor(e.ramification):5,e.ramification=this.ramification,this.maxSubrayRecursion=void 0!==e.maxSubrayRecursion?Math.floor(e.maxSubrayRecursion):3,e.maxSubrayRecursion=this.maxSubrayRecursion,this.recursionProbability=void 0!==e.recursionProbability?e.recursionProbability:.6,e.recursionProbability=this.recursionProbability,this.generateUVs=void 0!==e.generateUVs&&e.generateUVs,e.generateUVs=this.generateUVs,void 0!==e.randomGenerator?(this.randomGenerator=e.randomGenerator,this.seedGenerator=e.randomGenerator,void 0!==e.noiseSeed&&this.seedGenerator.setSeed(e.noiseSeed)):(this.randomGenerator=er.createRandomGenerator(),this.seedGenerator=Math),void 0!==e.onDecideSubrayCreation?this.onDecideSubrayCreation=e.onDecideSubrayCreation:(this.createDefaultSubrayCreationCallbacks(),void 0!==e.onSubrayCreation&&(this.onSubrayCreation=e.onSubrayCreation)),this.state=er.RAY_INITIALIZED,this.maxSubrays=Math.ceil(1+Math.pow(this.ramification,Math.max(0,this.maxSubrayRecursion-1))),e.maxSubrays=this.maxSubrays,this.maxRaySegments=2*(1<<this.maxIterations),this.subrays=[];for(let e=0;e<this.maxSubrays;e++)this.subrays.push(this.createSubray());this.raySegments=[];for(let e=0;e<this.maxRaySegments;e++)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=!1,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 P.Vector3,this.forwardsFill=new P.Vector3,this.side=new P.Vector3,this.down=new P.Vector3,this.middlePos=new P.Vector3,this.middleLinPos=new P.Vector3,this.newPos=new P.Vector3,this.vPos=new P.Vector3,this.cross1=new P.Vector3}createMesh(){let e=1<<this.maxIterations,t=3*(e+1)*this.maxSubrays,r=18*e*this.maxSubrays;this.vertices=new Float32Array(3*t),this.indices=new Uint32Array(r),this.generateUVs&&(this.uvs=new Float32Array(2*t)),this.fillMesh(0),this.setIndex(new P.Uint32BufferAttribute(this.indices,1)),this.positionAttribute=new P.Float32BufferAttribute(this.vertices,3),this.setAttribute("position",this.positionAttribute),this.generateUVs&&(this.uvsAttribute=new P.Float32BufferAttribute(new Float32Array(this.uvs),2),this.setAttribute("uv",this.uvsAttribute)),!this.isStatic&&(this.index.usage=P.DynamicDrawUsage,this.positionAttribute.usage=P.DynamicDrawUsage,this.generateUVs&&(this.uvsAttribute.usage=P.DynamicDrawUsage)),this.vertices=this.positionAttribute.array,this.indices=this.index.array,this.generateUVs&&(this.uvs=this.uvsAttribute.array)}updateMesh(e){this.fillMesh(e),this.drawRange.count=this.currentIndex,this.index.needsUpdate=!0,this.positionAttribute.needsUpdate=!0,this.generateUVs&&(this.uvsAttribute.needsUpdate=!0)}fillMesh(e){let t=this;this.currentVertex=0,this.currentIndex=0,this.currentCoordinate=0,this.currentUVCoordinate=0,this.fractalRay(e,function(r){let i=t.currentSubray;!(e<i.birthTime)&&(this.rayParameters.isEternal&&0==t.currentSubray.recursion?(t.createPrism(r),t.onDecideSubrayCreation(r,t)):e<i.endPropagationTime?t.timeFraction>=r.fraction0*i.propagationTimeFactor&&(t.createPrism(r),t.onDecideSubrayCreation(r,t)):(e<i.beginVanishingTime?t.createPrism(r):t.timeFraction<=i.vanishingTimeFactor+r.fraction1*(1-i.vanishingTimeFactor)&&t.createPrism(r),t.onDecideSubrayCreation(r,t)))})}addNewSubray(){return this.subrays[this.numSubrays++]}initSubray(e,t){e.pos0.copy(t.sourceOffset),e.pos1.copy(t.destOffset),e.up0.copy(t.up0),e.up1.copy(t.up1),e.radius0=t.radius0,e.radius1=t.radius1,e.birthTime=t.birthTime,e.deathTime=t.deathTime,e.timeScale=t.timeScale,e.roughness=t.roughness,e.straightness=t.straightness,e.propagationTimeFactor=t.propagationTimeFactor,e.vanishingTimeFactor=t.vanishingTimeFactor,e.maxIterations=this.maxIterations,e.seed=void 0!==t.noiseSeed?t.noiseSeed:0,e.recursion=0}fractalRay(e,t){this.time=e,this.currentSegmentCallback=t,this.numSubrays=0,this.initSubray(this.addNewSubray(),this.rayParameters);for(let t=0;t<this.numSubrays;t++){let r=this.subrays[t];this.currentSubray=r,this.randomGenerator.setSeed(r.seed),r.endPropagationTime=P.MathUtils.lerp(r.birthTime,r.deathTime,r.propagationTimeFactor),r.beginVanishingTime=P.MathUtils.lerp(r.deathTime,r.birthTime,1-r.vanishingTimeFactor);let i=this.randomGenerator.random;r.linPos0.set(i(),i(),i()).multiplyScalar(1e3),r.linPos1.set(i(),i(),i()).multiplyScalar(1e3),this.timeFraction=(e-r.birthTime)/(r.deathTime-r.birthTime),this.currentSegmentIndex=0,this.isInitialSegment=!0;let a=this.getNewSegment();a.iteration=0,a.pos0.copy(r.pos0),a.pos1.copy(r.pos1),a.linPos0.copy(r.linPos0),a.linPos1.copy(r.linPos1),a.up0.copy(r.up0),a.up1.copy(r.up1),a.radius0=r.radius0,a.radius1=r.radius1,a.fraction0=0,a.fraction1=1,a.positionVariationFactor=1-r.straightness,this.subrayProbability=this.ramification*Math.pow(this.recursionProbability,r.recursion)/(1<<r.maxIterations),this.fractalRayRecursive(a)}this.currentSegmentCallback=null,this.currentSubray=null}fractalRayRecursive(e){if(e.iteration>=this.currentSubray.maxIterations){this.currentSegmentCallback(e);return}this.forwards.subVectors(e.pos1,e.pos0);let t=this.forwards.length();t<1e-6&&(this.forwards.set(0,0,.01),t=this.forwards.length());let r=(e.radius0+e.radius1)*.5,i=(e.fraction0+e.fraction1)*.5,a=this.time*this.currentSubray.timeScale*Math.pow(2,e.iteration);this.middlePos.lerpVectors(e.pos0,e.pos1,.5),this.middleLinPos.lerpVectors(e.linPos0,e.linPos1,.5);let n=this.middleLinPos;this.newPos.set(this.simplexX.noise4d(n.x,n.y,n.z,a),this.simplexY.noise4d(n.x,n.y,n.z,a),this.simplexZ.noise4d(n.x,n.y,n.z,a)),this.newPos.multiplyScalar(e.positionVariationFactor*t),this.newPos.add(this.middlePos);let s=this.getNewSegment();s.pos0.copy(e.pos0),s.pos1.copy(this.newPos),s.linPos0.copy(e.linPos0),s.linPos1.copy(this.middleLinPos),s.up0.copy(e.up0),s.up1.copy(e.up1),s.radius0=e.radius0,s.radius1=r,s.fraction0=e.fraction0,s.fraction1=i,s.positionVariationFactor=e.positionVariationFactor*this.currentSubray.roughness,s.iteration=e.iteration+1;let o=this.getNewSegment();o.pos0.copy(this.newPos),o.pos1.copy(e.pos1),o.linPos0.copy(this.middleLinPos),o.linPos1.copy(e.linPos1),this.cross1.crossVectors(e.up0,this.forwards.normalize()),o.up0.crossVectors(this.forwards,this.cross1).normalize(),o.up1.copy(e.up1),o.radius0=r,o.radius1=e.radius1,o.fraction0=i,o.fraction1=e.fraction1,o.positionVariationFactor=e.positionVariationFactor*this.currentSubray.roughness,o.iteration=e.iteration+1,this.fractalRayRecursive(s),this.fractalRayRecursive(o)}createPrism(e){this.forwardsFill.subVectors(e.pos1,e.pos0).normalize(),this.isInitialSegment&&(this.currentCreateTriangleVertices(e.pos0,e.up0,this.forwardsFill,e.radius0,0),this.isInitialSegment=!1),this.currentCreateTriangleVertices(e.pos1,e.up0,this.forwardsFill,e.radius1,e.fraction1),this.createPrismFaces()}createTriangleVerticesWithoutUVs(e,t,r,i){this.side.crossVectors(t,r).multiplyScalar(i*er.COS30DEG),this.down.copy(t).multiplyScalar(-i*er.SIN30DEG);let a=this.vPos,n=this.vertices;a.copy(e).sub(this.side).add(this.down),n[this.currentCoordinate++]=a.x,n[this.currentCoordinate++]=a.y,n[this.currentCoordinate++]=a.z,a.copy(e).add(this.side).add(this.down),n[this.currentCoordinate++]=a.x,n[this.currentCoordinate++]=a.y,n[this.currentCoordinate++]=a.z,a.copy(t).multiplyScalar(i).add(e),n[this.currentCoordinate++]=a.x,n[this.currentCoordinate++]=a.y,n[this.currentCoordinate++]=a.z,this.currentVertex+=3}createTriangleVerticesWithUVs(e,t,r,i,a){this.side.crossVectors(t,r).multiplyScalar(i*er.COS30DEG),this.down.copy(t).multiplyScalar(-i*er.SIN30DEG);let n=this.vPos,s=this.vertices,o=this.uvs;n.copy(e).sub(this.side).add(this.down),s[this.currentCoordinate++]=n.x,s[this.currentCoordinate++]=n.y,s[this.currentCoordinate++]=n.z,o[this.currentUVCoordinate++]=a,o[this.currentUVCoordinate++]=0,n.copy(e).add(this.side).add(this.down),s[this.currentCoordinate++]=n.x,s[this.currentCoordinate++]=n.y,s[this.currentCoordinate++]=n.z,o[this.currentUVCoordinate++]=a,o[this.currentUVCoordinate++]=.5,n.copy(t).multiplyScalar(i).add(e),s[this.currentCoordinate++]=n.x,s[this.currentCoordinate++]=n.y,s[this.currentCoordinate++]=n.z,o[this.currentUVCoordinate++]=a,o[this.currentUVCoordinate++]=1,this.currentVertex+=3}createPrismFaces(e){let t=this.indices;e=this.currentVertex-6,t[this.currentIndex++]=e+1,t[this.currentIndex++]=e+2,t[this.currentIndex++]=e+5,t[this.currentIndex++]=e+1,t[this.currentIndex++]=e+5,t[this.currentIndex++]=e+4,t[this.currentIndex++]=e+0,t[this.currentIndex++]=e+1,t[this.currentIndex++]=e+4,t[this.currentIndex++]=e+0,t[this.currentIndex++]=e+4,t[this.currentIndex++]=e+3,t[this.currentIndex++]=e+2,t[this.currentIndex++]=e+0,t[this.currentIndex++]=e+3,t[this.currentIndex++]=e+2,t[this.currentIndex++]=e+3,t[this.currentIndex++]=e+5}createDefaultSubrayCreationCallbacks(){let e=this.randomGenerator.random;this.onDecideSubrayCreation=function(t,r){let i=r.currentSubray,a=r.rayParameters.subrayPeriod,n=r.rayParameters.subrayDutyCycle,s=r.rayParameters.isEternal&&0==i.recursion?-e()*a:P.MathUtils.lerp(i.birthTime,i.endPropagationTime,t.fraction0)-e()*a,o=r.time-s,l=Math.floor(o/a),c=e()*(l+1),u=0;if(o%a<=n*a&&(u=r.subrayProbability),i.recursion<r.maxSubrayRecursion&&r.numSubrays<r.maxSubrays&&e()<u){let o=r.addNewSubray(),u=r.randomGenerator.getSeed();o.seed=c,r.randomGenerator.setSeed(c),o.recursion=i.recursion+1,o.maxIterations=Math.max(1,i.maxIterations-1),o.linPos0.set(e(),e(),e()).multiplyScalar(1e3),o.linPos1.set(e(),e(),e()).multiplyScalar(1e3),o.up0.copy(i.up0),o.up1.copy(i.up1),o.radius0=t.radius0*r.rayParameters.radius0Factor,o.radius1=Math.min(r.rayParameters.minRadius,t.radiu
207s1*r.rayParameters.radius1Factor),o.birthTime=s+l*a,o.deathTime=o.birthTime+a*n,r.rayParameters.isEternal||0!=i.recursion||(o.birthTime=Math.max(o.birthTime,i.birthTime),o.deathTime=Math.min(o.deathTime,i.deathTime)),o.timeScale=2*i.timeScale,o.roughness=i.roughness,o.straightness=i.straightness,o.propagationTimeFactor=i.propagationTimeFactor,o.vanishingTimeFactor=i.vanishingTimeFactor,r.onSubrayCreation(t,i,o,r),r.randomGenerator.setSeed(u)}};let t=new P.Vector3,r=new P.Vector3,i=new P.Vector3,a=new P.Vector3;this.onSubrayCreation=function(e,t,r,i){i.subrayCylinderPosition(e,t,r,.5,.6,.2)},this.subrayConePosition=function(n,s,o,l,c,u){o.pos0.copy(n.pos0),t.subVectors(s.pos1,s.pos0),r.copy(t).normalize(),t.multiplyScalar(n.fraction0+(1-n.fraction0)*(e()*l));let h=t.length();i.crossVectors(s.up0,r);let d=2*Math.PI*e();i.multiplyScalar(Math.cos(d)),a.copy(s.up0).multiplyScalar(Math.sin(d)),o.pos1.copy(i).add(a).multiplyScalar(h*c*(u+e()*(1-u))).add(t).add(s.pos0)},this.subrayCylinderPosition=function(n,s,o,l,c,u){o.pos0.copy(n.pos0),t.subVectors(s.pos1,s.pos0),r.copy(t).normalize(),t.multiplyScalar(n.fraction0+(1-n.fraction0)*((2*e()-1)*l));let h=t.length();i.crossVectors(s.up0,r);let d=2*Math.PI*e();i.multiplyScalar(Math.cos(d)),a.copy(s.up0).multiplyScalar(Math.sin(d)),o.pos1.copy(i).add(a).multiplyScalar(h*c*(u+e()*(1-u))).add(t).add(s.pos0)}}createSubray(){return{seed:0,maxIterations:0,recursion:0,pos0:new P.Vector3,pos1:new P.Vector3,linPos0:new P.Vector3,linPos1:new P.Vector3,up0:new P.Vector3,up1:new P.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 P.Vector3,pos1:new P.Vector3,linPos0:new P.Vector3,linPos1:new P.Vector3,up0:new P.Vector3,up1:new P.Vector3,radius0:0,radius1:0,fraction0:0,fraction1:0,positionVariationFactor:0}}getNewSegment(){return this.raySegments[this.currentSegmentIndex++]}copy(e){return super.copy(e),this.init(er.copyParameters({},e.rayParameters)),this}clone(){return new this.constructor(er.copyParameters({},this.rayParameters))}};__publicField(er,"RAY_INITIALIZED",0),__publicField(er,"RAY_UNBORN",1),__publicField(er,"RAY_PROPAGATING",2),__publicField(er,"RAY_STEADY",3),__publicField(er,"RAY_VANISHING",4),__publicField(er,"RAY_EXTINGUISHED",5),__publicField(er,"COS30DEG",Math.
207cos(30*Math.PI/180)),__publicField(er,"SIN30DEG",Math.sin(30*Math.PI/180));let ei=class extends P.Mesh{constructor(e,t={}){let r;super(e),this.isReflectorForSSRPass=!0,this.type="ReflectorForSSRPass";let i=this,a=new P.Color(void 0!==t.color?t.color:8355711),n=t.textureWidth||512,s=t.textureHeight||512,o=t.clipBias||0,l=t.shader||ei.ReflectorShader,c=!0===t.useDepthTexture,u=new P.Vector3(0,1,0),h=new P.Vector3,d=new P.Vector3;i.needsUpdate=!1,i.maxDistance=ei.ReflectorShader.uniforms.maxDistance.value,i.opacity=ei.ReflectorShader.uniforms.opacity.value,i.color=a,i.resolution=t.resolution||new P.Vector2(window.innerWidth,window.innerHeight),i._distanceAttenuation=ei.ReflectorShader.defines.DISTANCE_ATTENUATION,Object.defineProperty(i,"distanceAttenuation",{get:()=>i._distanceAttenuation,set(e){i._distanceAttenuation!==e&&(i._distanceAttenuation=e,i.material.defines.DISTANCE_ATTENUATION=e,i.material.needsUpdate=!0)}}),i._fresnel=ei.ReflectorShader.defines.FRESNEL,Object.defineProperty(i,"fresnel",{get:()=>i._fresnel,set(e){i._fresnel!==e&&(i._fresnel=e,i.material.defines.FRESNEL=e,i.material.needsUpdate=!0)}});let p=new P.Vector3,f=new P.Vector3,m=new P.Vector3,g=new P.Matrix4,v=new P.Vector3(0,0,-1),y=new P.Vector3,T=new P.Vector3,x=new P.Matrix4,S=new P.PerspectiveCamera;c&&((r=new P.DepthTexture).type=P.UnsignedShortType,r.minFilter=P.NearestFilter,r.magFilter=P.NearestFilter);let E={depthTexture:c?r:null,type:P.HalfFloatType},b=new P.WebGLRenderTarget(n,s,E),R=new P.ShaderMaterial({transparent:c,defines:Object.assign({},ei.ReflectorShader.defines,{useDepthTexture:c}),uniforms:P.UniformsUtils.clone(l.uniforms),fragmentShader:l.fragmentShader,vertexShader:l.vertexShader});R.uniforms.tDiffuse.value=b.texture,R.uniforms.color.value=i.color,R.uniforms.textureMatrix.value=x,c&&(R.uniforms.tDepth.value=b.depthTexture),this.material=R;let A=new P.Plane(new P.Vector3(0,1,0),o),_=[A];this.doRender=function(e,t,r){if(R.uniforms.maxDistance.value=i.maxDistance,R.uniforms.color.value=i.color,R.uniforms.opacity.value=i.opacity,h.copy(r.position).normalize(),d.copy(h).reflect(u),R.uniforms.fresnelCoe.value=(h.dot(d)+1)/2,f.setFromMatrixPosition(i.matrixWorld),m.setFromMatrixPosition(r.matrixWorld),g.extractRotation(i.matrixWorld),p.set(0,0,1),p.applyMatrix4(g),y.subVectors(f,m),y.dot(p)>0)return;y.reflect(p).negate(),y.add(f),g.extractRotation(r.matrixWorld),v.set(0,0,-1),v.applyMatrix4(g),v.add(m),T.subVectors(f,v),T.reflect(p).negate(),T.add(f),S.position.copy(y),S.up.set(0,1,0),S.up.applyMatrix4(g),S.up.reflect(p),S.lookAt(T),S.far=r.far,S.updateMatrixWorld(),S.projectionMatrix.copy(r.projectionMatrix),R.uniforms.virtualCameraNear.value=r.near,R.uniforms.virtualCameraFar.value=r.far,R.uniforms.virtualCameraMatrixWorld.value=S.matrixWorld,R.uniforms.virtualCameraProjectionMatrix.value=r.projectionMatrix,R.uniforms.virtualCameraProjectionMatrixInverse.value=r.projectionMatrixInverse,R.uniforms.resolution.value=i.resolution,x.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),x.multiply(S.projectionMatrix),x.multiply(S.matrixWorldInverse),x.multiply(i.matrixWorld);let a=e.getRenderTarget(),n=e.xr.enabled,s=e.shadowMap.autoUpdate,o=e.clippingPlanes;e.xr.enabled=!1,e.shadowMap.autoUpdate=!1,e.clippingPlanes=_,e.setRenderTarget(b),e.state.buffers.depth.setMask(!0),!1===e.autoClear&&e.clear(),e.render(t,S),e.xr.enabled=n,e.shadowMap.autoUpdate=s,e.clippingPlanes=o,e.setRenderTarget(a);let l=r.viewport;void 0!==l&&e.state.viewport(l)},this.getRenderTarget=function(){return b}}};__publicField(ei,"ReflectorShader",{defines:{DISTANCE_ATTENUATION:!0,FRESNEL:!0},uniforms:{color:{value:null},tDiffuse:{value:null},tDepth:{value:null},textureMatrix:{value:new P.Matrix4},maxDistance:{value:180},opacity:{value:.5},fresnelCoe:{value:null},virtualCameraNear:{value:null},virtualCameraFar:{value:null},virtualCameraProjectionMatrix:{value:new P.Matrix4},virtualCameraMatrixWorld:{value:new P.Matrix4},virtualCameraProjectionMatrixInverse:{value:new P.Matrix4},resolution:{value:new P.Vector2}},vertexShader:`
208		uniform mat4 textureMatrix;
209		varying vec4 vUv;
210
211		void main() {
212
213			vUv = textureMatrix * vec4( position, 1.0 );
214
215			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
216
217		}`,fragmentShader:`
218		uniform vec3 color;
219		uniform sampler2D tDiffuse;
220		uniform sampler2D tDepth;
221		uniform float maxDistance;
222		uniform float opacity;
223		uniform float fresnelCoe;
224		uniform float virtualCameraNear;
225		uniform float virtualCameraFar;
226		uniform mat4 virtualCameraProjectionMatrix;
227		uniform mat4 virtualCameraProjectionMatrixInverse;
228		uniform mat4 virtualCameraMatrixWorld;
229		uniform vec2 resolution;
230		varying vec4 vUv;
231		#include <packing>
232		float blendOverlay( float base, float blend ) {
233			return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
234		}
235		vec3 blendOverlay( vec3 base, vec3 blend ) {
236			return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
237		}
238		float getDepth( const in vec2 uv ) {
239			return texture2D( tDepth, uv ).x;
240		}
241		float getViewZ( const in float depth ) {
242			return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar );
243		}
244		vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
245			vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
246			clipPosition *= clipW; //clip
247			return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view
248		}
249		void main() {
250			vec4 base = texture2DProj( tDiffuse, vUv );
251			#ifdef useDepthTexture
252				vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy;
253				uv.x=1.-uv.x;
254				float depth = texture2DProj( tDepth, vUv ).r;
255				float viewZ = getViewZ( depth );
256				float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3];
257				vec3 viewPosition=getViewPosition( uv, depth, clipW );
258				vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz;
259				if(worldPosition.y>maxDistance) discard;
260				float op=opacity;
261				#ifdef DISTANCE_ATTENUATION
262					float ratio=1.-(worldPosition.y/maxDistance);
263					float attenuation=ratio*ratio;
264					op=opacity*attenuation;
265				#endif
266				#ifdef FRESNEL
267					op*=fresnelCoe;
268				#endif
269				gl_FragColor = vec4( blendOverlay( base.rgb, color ), op );
270			#else
271				gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
272			#endif
273		}
274	`});let ea={uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new P.Vector3},up:{value:new P.Vector3(0,1,0)}},vertexShader:`
275      uniform vec3 sunPosition;
276      uniform float rayleigh;
277      uniform float turbidity;
278      uniform float mieCoefficient;
279      uniform vec3 up;
280
281      varying vec3 vWorldPosition;
282      varying vec3 vSunDirection;
283      varying float vSunfade;
284      varying vec3 vBetaR;
285      varying vec3 vBetaM;
286      varying float vSunE;
287
288      // constants for atmospheric scattering
289      const float e = 2.71828182845904523536028747135266249775724709369995957;
290      const float pi = 3.141592653589793238462643383279502884197169;
291
292      // wavelength of used primaries, according to preetham
293      const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );
294      // this pre-calcuation replaces older TotalRayleigh(vec3 lambda) function:
295      // (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))
296      const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.02
29665902468824876E-5 );
297
298      // mie stuff
299      // K coefficient for the primaries
300      const float v = 4.0;
301      const vec3 K = vec3( 0.686, 0.678, 0.666 );
302      // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K
303      const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );
304
305      // earth shadow hack
306      // cutoffAngle = pi / 1.95;
307      const float cutoffAngle = 1.6110731556870734;
308      const float steepness = 1.5;
309      const float EE = 1000.0;
310
311      float sunIntensity( float zenithAngleCos ) {
312        zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );
313        return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );
314      }
315
316      vec3 totalMie( float T ) {
317        float c = ( 0.2 * T ) * 10E-18;
318        return 0.434 * c * MieConst;
319      }
320
321      void main() {
322
323        vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
324        vWorldPosition = worldPosition.xyz;
325
326        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
327        gl_Position.z = gl_Position.w; // set z to camera.far
328
329        vSunDirection = normalize( sunPosition );
330
331        vSunE = sunIntensity( dot( vSunDirection, up ) );
332
333        vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );
334
335        float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );
336
337      // extinction (absorbtion + out scattering)
338      // rayleigh coefficients
339        vBetaR = totalRayleigh * rayleighCoefficient;
340
341      // mie coefficients
342        vBetaM = totalMie( turbidity ) * mieCoefficient;
343
344      }
345    `,fragmentShader:`
346      varying vec3 vWorldPosition;
347      varying vec3 vSunDirection;
348      varying float vSunfade;
349      varying vec3 vBetaR;
350      varying vec3 vBetaM;
351      varying float vSunE;
352
353      uniform float mieDirectionalG;
354      uniform vec3 up;
355
356      const vec3 cameraPos = vec3( 0.0, 0.0, 0.0 );
357
358      // constants for atmospheric scattering
359      const float pi = 3.141592653589793238462643383279502884197169;
360
361      const float n = 1.0003; // refractive index of air
362      const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius)
363
364      // optical length at zenith for molecules
365      const float rayleighZenithLength = 8.4E3;
366      const float mieZenithLength = 1.25E3;
367      // 66 arc seconds -> degrees, and the cosine of that
368      const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;
369
370      // 3.0 / ( 16.0 * pi )
371      const float THREE_OVER_SIXTEENPI = 0.05968310365946075;
372      // 1.0 / ( 4.0 * pi )
373      const float ONE_OVER_FOURPI = 0.07957747154594767;
374
375      float rayleighPhase( float cosTheta ) {
376        return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );
377      }
378
379      float hgPhase( float cosTheta, float g ) {
380        float g2 = pow( g, 2.0 );
381        float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );
382        return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );
383      }
384
385      void main() {
386
387        vec3 direction = normalize( vWorldPosition - cameraPos );
388
389      // optical length
390      // cutoff angle at 90 to avoid singularity in next formula.
391        float zenithAngle = acos( max( 0.0, dot( up, direction ) ) );
392        float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );
393        float sR = rayleighZenithLength * inverse;
394        float sM = mieZenithLength * inverse;
395
396      // combined extinction factor
397        vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );
398
399      // in scattering
400        float cosTheta = dot( direction, vSunDirection );
401
402        float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );
403        vec3 betaRTheta = vBetaR * rPhase;
404
405        float mPhase = hgPhase( cosTheta, mieDirectionalG );
406        vec3 betaMTheta = vBetaM * mPhase;
407
408        vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );
409        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 ) );
410
411      // nightsky
412        float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]
413        float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]
414        vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );
415        vec3 L0 = vec3( 0.1 ) * Fex;
416
417      // composition + solar disc
418        float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta );
419        L0 += ( vSunE * 19000.0 * Fex ) * sundisk;
420
421        vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );
422
423        vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );
424
425        gl_FragColor = vec4( retColor, 1.0 );
426
427      #include <tonemapping_fragment>
428      #include <${parseInt(P.REVISION.replace(/\D+/g,""))>=154?"colorspace_fragment":"encodings_fragment"}>
429
430      }
431    `}
431,en=new P.ShaderMaterial({name:"SkyShader",fragmentShader:ea.fragmentShader,vertexShader:ea.vertexShader,uniforms:P.UniformsUtils.clone(ea.uniforms),side:P.BackSide,depthWrite:!1});let Sky=class Sky extends P.Mesh{constructor(){super(new P.BoxGeometry(1,1,1),en)}};__publicField(Sky,"SkyShader",ea),__publicField(Sky,"material",en);let es=class extends P.Mesh{constructor(e,t={}){super(e),this.isWater=!0,this.type="Water";let r=this,i=new P.Color(void 0!==t.color?t.color:16777215),a=t.textureWidth||512,n=t.textureHeight||512,s=t.clipBias||0,o=t.flowDirection||new P.Vector2(1,0),l=t.flowSpeed||.03,c=t.reflectivity||.02,u=t.scale||1,h=t.shader||es.WaterShader,d=void 0!==t.encoding?t.encoding:3e3,p=t.flowMap||void 0,f=t.normalMap0,m=t.normalMap1,g=new P.Matrix4,v=new P.Clock;if(void 0===Q){console.error("THREE.Water: Required component Reflector not found.");return}if(void 0===J){console.error("THREE.Water: Required component Refractor not found.");return}let y=new Q(e,{textureWidth:a,textureHeight:n,clipBias:s,encoding:d}),T=new J(e,{textureWidth:a,textureHeight:n,clipBias:s,encoding:d});y.matrixAutoUpdate=!1,T.matrixAutoUpdate=!1,this.material=new P.ShaderMaterial({uniforms:P.UniformsUtils.merge([P.UniformsLib.fog,h.uniforms]),vertexShader:h.vertexShader,fragmentShader:h.fragmentShader,transparent:!0,fog:!0}),void 0!==p?(this.material.defines.USE_FLOWMAP="",this.material.uniforms.tFlowMap={type:"t",value:p}):this.material.uniforms.flowDirection={type:"v2",value:o},f.wrapS=f.wrapT=P.RepeatWrapping,m.wrapS=m.wrapT=P.RepeatWrapping,this.material.uniforms.tReflectionMap.value=y.getRenderTarget().texture,this.material.uniforms.tRefractionMap.value=T.getRenderTarget().texture,this.material.uniforms.tNormalMap0.value=f,this.material.uniforms.tNormalMap1.value=m,this.material.uniforms.color.value=i,this.material.uniforms.reflectivity.value=c,this.material.uniforms.textureMatrix.value=g,this.material.uniforms.config.value.x=0,this.material.uniforms.config.value.y=.075,this.material.uniforms.config.value.z=.075,this.material.uniforms.config.value.w=u,this.onBeforeRender=function(e,t,i){g.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),g.multiply(i.projectionMatrix),g.multiply(i.matrixWorldInverse),g.multiply(r.matrixWorld),function(){let e=v.getDelta(),t=r.material.uniforms.config;t.value.x+=l*e,t.value.y=t.value.x+.075,t.value.x>=.15?(t.value.x=0,t.value.y=.075):t.value.y>=.15&&(t.value.y=t.value.y-.15)}(),r.visible=!1,y.matrixWorld.copy(r.matrixWorld),T.matrixWorld.copy(r.matrixWorld),y.onBeforeRender(e,t,i),T.onBeforeRender(e,t,i),r.visible=!0}}};__publicField(es,"WaterShader",{uniforms:{color:{value:null},reflectivity:{value:0},tReflectionMap:{value:null},tRefractionMap:{value:null},tNormalMap0:{value:null},tNormalMap1:{value:null},textureMatrix:{value:null},config:{value:new P.Vector4}},vertexShader:`
432
433		#include <common>
434		#include <fog_pars_vertex>
435		#include <logdepthbuf_pars_vertex>
436
437		uniform mat4 textureMatrix;
438
439		varying vec4 vCoord;
440		varying vec2 vUv;
441		varying vec3 vToEye;
442
443		void main() {
444
445			vUv = uv;
446			vCoord = textureMatrix * vec4( position, 1.0 );
447
448			vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
449			vToEye = cameraPosition - worldPosition.xyz;
450
451			vec4 mvPosition =  viewMatrix * worldPosition; // used in fog_vertex
452			gl_Position = projectionMatrix * mvPosition;
453
454			#include <logdepthbuf_vertex>
455			#include <fog_vertex>
456
457		}`,fragmentShader:`
458
459		#include <common>
460		#include <fog_pars_fragment>
461		#include <logdepthbuf_pars_fragment>
462
463		uniform sampler2D tReflectionMap;
464		uniform sampler2D tRefractionMap;
465		uniform sampler2D tNormalMap0;
466		uniform sampler2D tNormalMap1;
467
468		#ifdef USE_FLOWMAP
469			uniform sampler2D tFlowMap;
470		#else
471			uniform vec2 flowDirection;
472		#endif
473
474		uniform vec3 color;
475		uniform float reflectivity;
476		uniform vec4 config;
477
478		varying vec4 vCoord;
479		varying vec2 vUv;
480		varying vec3 vToEye;
481
482		void main() {
483
484			#include <logdepthbuf_fragment>
485
486			float flowMapOffset0 = config.x;
487			float flowMapOffset1 = config.y;
488			float halfCycle = config.z;
489			float scale = config.w;
490
491			vec3 toEye = normalize( vToEye );
492
493			// determine flow direction
494			vec2 flow;
495			#ifdef USE_FLOWMAP
496				flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0;
497			#else
498				flow = flowDirection;
499			#endif
500			flow.x *= - 1.0;
501
502			// sample normal maps (distort uvs with flowdata)
503			vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 );
504			vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 );
505
506			// linear interpolate to get the final normal color
507			float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle;
508			vec4 normalColor = mix( normalColor0, normalColor1, flowLerp );
509
510			// calculate normal vector
511			vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b,  normalColor.g * 2.0 - 1.0 ) );
512
513			// calculate the fresnel term to blend reflection and refraction maps
514			float theta = max( dot( toEye, normal ), 0.0 );
515			float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 );
516
517			// calculate final uv coords
518			vec3 coord = vCoord.xyz / vCoord.w;
519			vec2 uv = coord.xy + coord.z * normal.xz * 0.05;
520
521			vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) );
522			vec4 refractColor = texture2D( tRefractionMap, uv );
523
524			// multiply water color with the mix of both textures
525			gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance );
526
527			#include <tonemapping_fragment>
528			#include <${parseInt(P.REVISION.replace(/\D+/g,""))>=154?"colorspace_fragment":"encodings_fragment"}>
529			#include <fog_fragment>
530
531		}`});let eo={uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"varying vec2 vUv;\nvoid main() {\n	vUv = uv;\n	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"uniform float opacity;\nuniform sampler2D tDiffuse;\nvarying vec2 vUv;\n#include <packing>\nvoid main() {\n	float depth = 1.0 - unpackRGBAToDepth( texture2D( tDiffuse, vUv ) );\n	gl_FragColor = vec4( vec3( depth ), opacity );\n}"}
531,el={c:null,u:[new P.Vector3,new P.Vector3,new P.Vector3],e:[]},ec={c:null,u:[new P.Vector3,new P.Vector3,new P.Vector3],e:[]},eu=[[],[],[]],eh=[[],[],[]],ed=[],ep=new P.Vector3,ef=new P.Vector3,em=new P.Vector3,eg=new P.Vector3,ev=new P.Vector3,ey=new P.Vector3,eT=new P.Matrix3,ex=new P.Box3,eS=new P.Matrix4,eE=new P.Matrix4,eb=new P.Ray,eR=new class{constructor(e=new P.Vector3,t=new P.Vector3,r=new P.Matrix3){this.center=e,this.halfSize=t,this.rotation=r}set(e,t,r){return this.center=e,this.halfSize=t,this.rotation=r,this}copy(e){return this.center.copy(e.center),this.halfSize.copy(e.halfSize),this.rotation.copy(e.rotation),this}clone(){return new this.constructor().copy(this)}getSize(e){return e.copy(this.halfSize).multiplyScalar(2)}clampPoint(e,t){let r=this.halfSize;eg.subVectors(e,this.center),this.rotation.extractBasis(ep,ef,em),t.copy(this.center);let i=P.MathUtils.clamp(eg.dot(ep),-r.x,r.x);t.add(ep.multiplyScalar(i));let a=P.MathUtils.clamp(eg.dot(ef),-r.y,r.y);t.add(ef.multiplyScalar(a));let n=P.MathUtils.clamp(eg.dot(em),-r.z,r.z);return t.add(em.multiplyScalar(n)),t}containsPoint(e){return eg.subVectors(e,this.center),this.rotation.extractBasis(ep,ef,em),Math.abs(eg.dot(ep))<=this.halfSize.x&&Math.abs(eg.dot(ef))<=this.halfSize.y&&Math.abs(eg.dot(em))<=this.halfSize.z}intersectsBox3(e){return this.intersectsOBB(eR.fromBox3(e))}intersectsSphere(e){return this.clampPoint(e.center,ey),ey.distanceToSquared(e.center)<=e.radius*e.radius}intersectsOBB(e,t=Number.EPSILON){let r,i;el.c=this.center,el.e[0]=this.halfSize.x,el.e[1]=this.halfSize.y,el.e[2]=this.halfSize.z,this.rotation.extractBasis(el.u[0],el.u[1],el.u[2]),ec.c=e.center,ec.e[0]=e.halfSize.x,ec.e[1]=e.halfSize.y,ec.e[2]=e.halfSize.z,e.rotation.extractBasis(ec.u[0],ec.u[1],ec.u[2]);for(let e=0;e<3;e++)for(let t=0;t<3;t++)eu[e][t]=el.u[e].dot(ec.u[t]);eg.subVectors(ec.c,el.c),ed[0]=eg.dot(el.u[0]),ed[1]=eg.dot(el.u[1]),ed[2]=eg.dot(el.u[2]);for(let e=0;e<3;e++)for(let r=0;r<3;r++)eh[e][r]=Math.abs(eu[e][r])+t;for(let e=0;e<3;e++)if(r=el.e[e],i=ec.e[0]*eh[e][0]+ec.e[1]*eh[e][1]+ec.e[2]*eh[e][2],Math.abs(ed[e])>r+i)return!1;for(let e=0;e<3;e++)if(r=el.e[0]*eh[0][e]+el.e[1]*eh[1][e]+el.e[2]*eh[2][e],i=ec.e[e],Math.abs(ed[0]*eu[0][e]+ed[1]*eu[1][e]+ed[2]*eu[2][e])>r+i)return!1;return r=el.e[1]*eh[2][0]+el.e[2]*eh[1][0],i=ec.e[1]*eh[0][2]+ec.e[2]*eh[0][1],!(Math.abs(ed[2]*eu[1][0]-ed[1]*eu[2][0])>r+i)&&(r=el.e[1]*eh[2][1]+el.e[2]*eh[1][1],i=ec.e[0]*eh[0][2]+ec.e[2]*eh[0][0],!(Math.abs(ed[2]*eu[1][1]-ed[1]*eu[2][1])>r+i)&&(r=el.e[1]*eh[2][2]+el.e[2]*eh[1][2],i=ec.e[0]*eh[0][1]+ec.e[1]*eh[0][0],!(Math.abs(ed[2]*eu[1][2]-ed[1]*eu[2][2])>r+i)&&(r=el.e[0]*eh[2][0]+el.e[2]*eh[0][0],i=ec.e[1]*eh[1][2]+ec.e[2]*eh[1][1],!(Math.abs(ed[0]*eu[2][0]-ed[2]*eu[0][0])>r+i)&&(r=el.e[0]*eh[2][1]+el.e[2]*eh[0][1],i=ec.e[0]*eh[1][2]+ec.e[2]*eh[1][0],!(Math.abs(ed[0]*eu[2][1]-ed[2]*eu[0][1])>r+i)&&(r=el.e[0]*eh[2][2]+el.e[2]*eh[0][2],i=ec.e[0]*eh[1][1]+ec.e[1]*eh[1][0],!(Math.abs(ed[0]*eu[2][2]-ed[2]*eu[0][2])>r+i)&&(r=el.e[0]*eh[1][0]+el.e[1]*eh[0][0],i=ec.e[1]*eh[2][2]+ec.e[2]*eh[2][1],!(Math.abs(ed[1]*eu[0][0]-ed[0]*eu[1][0])>r+i)&&(r=el.e[0]*eh[1][1]+el.e[1]*eh[0][1],i=ec.e[0]*eh[2][2]+ec.e[2]*eh[2][0],!(Math.abs(ed[1]*eu[0][1]-ed[0]*eu[1][1])>r+i)&&(r=el.e[0]*eh[1][2]+el.e[1]*eh[0][2],i=ec.e[0]*eh[2][1]+ec.e[1]*eh[2][0],!(Math.abs(ed[1]*eu[0][2]-ed[0]*eu[1][2])>r+i)))))))))}intersectsPlane(e){this.rotation.extractBasis(ep,ef,em);let t=this.halfSize.x*Math.abs(e.normal.dot(ep))+this.halfSize.y*Math.abs(e.normal.dot(ef))+this.halfSize.z*Math.abs(e.normal.dot(em)),r=e.normal.dot(this.center)-e.constant;return Math.abs(r)<=t}intersectRay(e,t){return(this.getSize(ev),ex.setFromCenterAndSize(eg.set(0,0,0),ev),eS.setFromMatrix3(this.rotation),eS.setPosition(this.center),eE.copy(eS).invert(),eb.copy(e).applyMatrix4(eE),eb.intersectBox(ex,t))?t.applyMatrix4(eS):null}intersectsRay(e){return null!==this.intersectRay(e,eg)}fromBox3(e){return e.getCenter(this.center),e.getSize(this.halfSize).multiplyScalar(.5),this.rotation.identity(),this}equals(e){return e.center.equals(this.center)&&e.halfSize.equals(this.halfSize)&&e.rotation.equals(this.rotation)}applyMatrix4(e){let t=e.elements,r=eg.set(t[0],t[1],t[2]).length(),i=eg.set(t[4],t[5],t[6]).length(),a=eg.set(t[8],t[9],t[10]).length(),n=e.determinant();n<0&&(r=-r),eT.setFromMatrix4(e);let s=1/r,o=1/i,l=1/a;return eT.elements[0]*=s,eT.elements[1]*=s,eT.elements[2]*=s,eT.elements[3]*=o,eT.elements[4]*=o,eT.elements[5]*=o,eT.elements[6]*=l,eT.elements[7]*=l,eT.elements[8]*=l,this.rotation.multiply(eT),this.halfSize.x*=r,this.halfSize.y*=i,this.halfSize.z*=a,eg.setFromMatrixPosition(e),this.center.add(eg),this}},eA=new P.Vector3,e_=new P.Vector3,eM=new P.Vector3;
531let Capsule=class Capsule{constructor(e=new P.Vector3(0,0,0),t=new P.Vector3(0,1,0),r=1){this.start=e,this.end=t,this.radius=r}clone(){return new Capsule(this.start.clone(),this.end.clone(),this.radius)}set(e,t,r){this.start.copy(e),this.end.copy(t),this.radius=r}copy(e){this.start.copy(e.start),this.end.copy(e.end),this.radius=e.radius}getCenter(e){return e.copy(this.end).add(this.start).multiplyScalar(.5)}translate(e){this.start.add(e),this.end.add(e)}checkAABBAxis(e,t,r,i,a,n,s,o,l){return(a-e<l||a-r<l)&&(e-n<l||r-n<l)&&(s-t<l||s-i<l)&&(t-o<l||i-o<l)}intersectsBox(e){return this.checkAABBAxis(this.start.x,this.start.y,this.end.x,this.end.y,e.min.x,e.max.x,e.min.y,e.max.y,this.radius)&&this.checkAABBAxis(this.start.x,this.start.z,this.end.x,this.end.z,e.min.x,e.max.x,e.min.z,e.max.z,this.radius)&&this.checkAABBAxis(this.start.y,this.start.z,this.end.y,this.end.z,e.min.y,e.max.y,e.min.z,e.max.z,this.radius)}lineLineMinimumPoints(e,t){let r,i;let a=eA.copy(e.end).sub(e.start),n=e_.copy(t.end).sub(t.start),s=eM.copy(t.start).sub(e.start),o=a.dot(n),l=a.dot(a),c=n.dot(n),u=n.dot(s),h=a.dot(s),d=l*c-o*o;if(1e-10>Math.abs(d)){let e=-u/c,t=(o-u)/c;Math.abs(e-.5)<Math.abs(t-.5)?(r=0,i=e):(r=1,i=t)}else i=((r=(u*o+h*c)/d)*o-u)/c;i=Math.max(0,Math.min(1,i)),r=Math.max(0,Math.min(1,r));let p=a.multiplyScalar(r).add(e.start),f=n.multiplyScalar(i).add(t.start);return[p,f]}};var eC=((d=eC||{})[d.NONE=-1]="NONE",d[d.ROTATE=0]="ROTATE",d[d.DOLLY=1]="DOLLY",d[d.PAN=2]="PAN",d[d.TOUCH_ROTATE=3]="TOUCH_ROTATE",d[d.TOUCH_PAN=4]="TOUCH_PAN",d[d.TOUCH_DOLLY_PAN=5]="TOUCH_DOLLY_PAN",d[d.TOUCH_DOLLY_ROTATE=6]="TOUCH_DOLLY_ROTATE",d);Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol(),Symbol();let Pass=class Pass{constructor(){__publicField(this,"enabled",!0),__publicField(this,"needsSwap",!0),__publicField(this,"clear",!1),__publicField(this,"renderToScreen",!1)}setSize(e,t){}render(e,t,r,i,a){console.error("THREE.Pass: .render() must be implemented in derived pass.")}};let FullScreenQuad=class FullScreenQuad{constructor(e){__publicField(this,"camera",new P.OrthographicCamera(-1,1,1,-1,0,1)),__publicField(this,"geometry",new P.PlaneGeometry(2,2)),__publicField(this,"mesh"),this.mesh=new P.Mesh(this.geometry,e)}get material(){return this.mesh.material}set material(e){this.mesh.material=e}dispose(){this.mesh.geometry.dispose()}render(e){e.render(this.mesh,this.camera)}};let ew={uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"varying vec2 vUv;\nvoid main() {\n	vUv = uv;\n	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"uniform float opacity;\nuniform sampler2D tDiffuse;\nvarying vec2 vUv;\nvoid main() {\n	vec4 texel = texture2D( tDiffuse, vUv );\n	gl_FragColor = opacity * texel;\n}"},eI={defines:{PERSPECTIVE_CAMERA:1,KERNEL_SIZE:32},uniforms:{tDiffuse:{value:null},tNormal:{value:null},tDepth:{value:null},tNoise:{value:null},kernel:{value:null},cameraNear:{value:null},cameraFar:{value:null},resolution:{value:new P.Vector2},cameraProjectionMatrix:{value:new P.Matrix4},cameraInverseProjectionMatrix:{value:new P.Matrix4},kernelRadius:{value:8},minDistance:{value:.005},maxDistance:{value:.05}},vertexShader:"varying vec2 vUv;\nvoid main() {\n	vUv = uv;\n	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D tDiffuse;\nuniform sampler2D tNormal;\nuniform sampler2D tDepth;\nuniform sampler2D tNoise;\nuniform vec3 kernel[ KERNEL_SIZE ];\nuniform vec2 resolution;\nuniform float cameraNear;\nuniform float cameraFar;\nuniform mat4 cameraProjectionMatrix;\nuniform mat4 cameraInverseProjectionMatrix;\nuniform float kernelRadius;\nuniform float minDistance;\nuniform float maxDistance;\nvarying vec2 vUv;\n#include <packing>\nfloat getDepth( const in vec2 screenPosition ) {\n	return texture2D( tDepth, screenPosition ).x;\n}\nfloat getLinearDepth( const in vec2 screenPosition ) {\n	#if PERSPECTIVE_CAMERA == 1\n		float fragCoordZ = texture2D( tDepth, screenPosition ).x;\n		float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n		return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n	#else\n		return texture2D( tDepth, screenPosition ).x;\n	#endif\n}\nfloat getViewZ( const in float depth ) {\n	#if PERSPECTIVE_CAMERA == 1\n		return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );\n	#else\n		return orthographicDepthToViewZ( depth, cameraNear, cameraFar );\n	#endif\n}\nvec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {\n	float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];\n	vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );\n	clipPosition *= clipW; // unprojection.\n	return ( cameraInverseProjectionMatrix * clipPosition ).xyz;\n}\nvec3 getViewNormal( const in vec2 screenPosition ) {\n	return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );\n}\nvoid main() {\n	float depth = getDepth( vUv );\n	float viewZ = getViewZ( depth );\n	vec3 viewPosition = getViewPosition( vUv, depth, viewZ );\n	vec3 viewNormal = getViewNormal( vUv );\n vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 );\n	vec3 random = texture2D( tNoise, vUv * noiseScale ).xyz;\n	vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) );\n	vec3 bitangent = cross( viewNormal, tangent );\n	mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal );\n float occlusion = 0.0;\n for ( int i = 0; i < KERNEL_SIZE; i ++ ) {\n		vec3 sampleVector = kernelMatrix * kernel[ i ];\n		vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius );
531\n		vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 );\n		samplePointNDC /= samplePointNDC.w;\n		vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5;\n		float realDepth = getLinearDepth( samplePointUv );\n		float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar );\n		float delta = sampleDepth - realDepth;\n		if ( delta > minDistance && delta < maxDistance ) {\n			occlusion += 1.0;\n		}\n	}\n	occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 );\n	gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 );\n}"},eP={defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:"varying vec2 vUv;\nvoid main() {\n	vUv = uv;\n	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\nvarying vec2 vUv;\n#include <packing>\nfloat getLinearDepth( const in vec2 screenPosition ) {\n	#if PERSPECTIVE_CAMERA == 1\n		float fragCoordZ = texture2D( tDepth, screenPosition ).x;\n		float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n		return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n	#else\n		return texture2D( tDepth, screenPosition ).x;\n	#endif\n}\nvoid main() {\n	float depth = getLinearDepth( vUv );\n	gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );\n}"},eN={uniforms:{tDiffuse:{value:null},resolution:{value:new P.Vector2}},vertexShader:"varying vec2 vUv;\nvoid main() {\n	vUv = uv;\n	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D tDiffuse;\nuniform vec2 resolution;\nvarying vec2 vUv;\nvoid main() {\n	vec2 texelSize = ( 1.0 / resolution );\n	float result = 0.0;\n	for ( int i = - 2; i <= 2; i ++ ) {\n		for ( int j = - 2; j <= 2; j ++ ) {\n			vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize;\n			result += texture2D( tDiffuse, vUv + offset ).r;\n		}\n	}\n	gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 );\n}"}
531,eO=class extends Pass{constructor(e,t,r,i){super(),this.width=void 0!==r?r:512,this.height=void 0!==i?i:512,this.clear=!0,this.camera=t,this.scene=e,this.kernelRadius=8,this.kernelSize=32,this.kernel=[],this.noiseTexture=null,this.output=0,this.minDistance=.005,this.maxDistance=.1,this._visibilityCache=new Map,this.generateSampleKernel(),this.generateRandomKernelRotations();let a=new P.DepthTexture;a.format=P.DepthStencilFormat,a.type=P.UnsignedInt248Type,this.beautyRenderTarget=new P.WebGLRenderTarget(this.width,this.height),this.normalRenderTarget=new P.WebGLRenderTarget(this.width,this.height,{minFilter:P.NearestFilter,magFilter:P.NearestFilter,depthTexture:a}),this.ssaoRenderTarget=new P.WebGLRenderTarget(this.width,this.height),this.blurRenderTarget=this.ssaoRenderTarget.clone(),void 0===eI&&console.error("THREE.SSAOPass: The pass relies on SSAOShader."),this.ssaoMaterial=new P.ShaderMaterial({defines:Object.assign({},eI.defines),uniforms:P.UniformsUtils.clone(eI.uniforms),vertexShader:eI.vertexShader,fragmentShader:eI.fragmentShader,blending:P.NoBlending}),this.ssaoMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.ssaoMaterial.uniforms.tNormal.value=this.normalRenderTarget.texture,this.ssaoMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture,this.ssaoMaterial.uniforms.tNoise.value=this.noiseTexture,this.ssaoMaterial.uniforms.kernel.value=this.kernel,this.ssaoMaterial.uniforms.cameraNear.value=this.camera.near,this.ssaoMaterial.uniforms.cameraFar.value=this.camera.far,this.ssaoMaterial.uniforms.resolution.value.set(this.width,this.height),this.ssaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssaoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.normalMaterial=new P.MeshNormalMaterial,this.normalMaterial.blending=P.NoBlending,this.blurMaterial=new P.ShaderMaterial({defines:Object.assign({},eN.defines),uniforms:P.UniformsUtils.clone(eN.uniforms),vertexShader:eN.vertexShader,fragmentShader:eN.fragmentShader}),this.blurMaterial.uniforms.tDiffuse.value=this.ssaoRenderTarget.texture,this.blurMaterial.uniforms.resolution.value.set(this.width,this.height),this.depthRenderMaterial=new P.ShaderMaterial({defines:Object.assign({},eP.defines),uniforms:P.UniformsUtils.clone(eP.uniforms),vertexShader:eP.vertexShader,fragmentShader:eP.fragmentShader,blending:P.NoBlending}),this.depthRenderMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture,this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new P.ShaderMaterial({uniforms:P.UniformsUtils.clone(ew.uniforms),vertexShader:ew.vertexShader,fragmentShader:ew.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:P.DstColorFactor,blendDst:P.ZeroFactor,blendEquation:P.AddEquation,blendSrcAlpha:P.DstAlphaFactor,blendDstAlpha:P.ZeroFactor,blendEquationAlpha:P.AddEquation}),this.fsQuad=new FullScreenQuad(null),this.originalClearColor=new P.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(e,t){switch(!1===e.capabilities.isWebGL2&&(this.noiseTexture.format=P.LuminanceFormat),e.setRenderTarget(this.beautyRenderTarget),e.clear(),e.render(this.scene,this.camera),this.overrideVisibility(),this.renderOverride(e,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(e,this.ssaoMaterial,this.ssaoRenderTarget),this.renderPass(e,this.blurMaterial,this.blurRenderTarget),this.output){case eO.OUTPUT.SSAO:this.copyMaterial.uniforms.tDiffuse.value=this.ssaoRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case eO.OUTPUT.Blur:this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case eO.OUTPUT.Beauty:this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case eO.OUTPUT.Depth:this.renderPass(e,this.depthRenderMaterial,this.renderToScreen?null:t);break;case eO.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case eO.OUTPUT.Default:this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t),this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.copyMaterial.blending=P.CustomBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;default:console.warn("THREE.SSAOPass: Unknown output type.")}}renderPass(e,t,r,i,a){e.getClearColor(this.originalClearColor);let n=e.getClearAlpha(),s=e.autoClear;e.setRenderTarget(r),e.autoClear=!1,null!=i&&(e.setClearColor(i),e.setClearAlpha(a||0),e.clear()),this.fsQuad.material=t,this.fsQuad.render(e),e.autoClear=s,e.setClearColor(this.originalClearColor),e.setClearAlpha(n)}renderOverride(e,t,r,i,a){e.getClearColor(this.originalClearColor);let n=e.getClearAlpha(),s=e.autoClear;e.setRenderTarget(r),e.autoClear=!1,i=t.clearColor||i,a=t.clearAlpha||a,null!=i&&(e.setClearColor(i),e.setClearAlpha(a||0),e.clear()),this.scene.overrideMaterial=t,e.render(this.scene,this.camera),this.scene.overrideMaterial=null,e.autoClear=s,e.setClearColor(this.originalClearColor),e.setClearAlpha(n)}setSize(e,t){this.width=e,this.height=t,this.beautyRenderTarget.setSize(e,t),this.ssaoRenderTarget.setSize(e,t),this.normalRenderTarget.setSize(e,t),this.blurRenderTarget.setSize(e,t),this.ssaoMaterial.uniforms.resolution.value.set(e,t),this.ssaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssaoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.blurMaterial.uniforms.resolution.value.set(e,t)}generateSampleKernel(){let e=this.kernelSize,t=this.kernel;for(let r=0;r<e;r++){let i=new P.Vector3;i.x=2*Math.random()-1,i.y=2*Math.random()-1,i.z=Math.random(),i.normalize();let a=r/e;a=P.MathUtils.lerp(.1,1,a*a),i.multiplyScalar(a),t.push(i)}}generateRandomKernelRotations(){void 0===SimplexNoise&&console.error("THREE.SSAOPass: The pass relies on SimplexNoise.");let e=new SimplexNoise,t=new Float32Array(16);for(let r=0;r<16;r++){let i=2*Math.random()-1,a=2*Math.random()-1;
531t[r]=e.noise3d(i,a,0)}this.noiseTexture=new P.DataTexture(t,4,4,P.RedFormat,P.FloatType),this.noiseTexture.wrapS=P.RepeatWrapping,this.noiseTexture.wrapT=P.RepeatWrapping,this.noiseTexture.needsUpdate=!0}overrideVisibility(){let e=this.scene,t=this._visibilityCache;e.traverse(function(e){t.set(e,e.visible),(e.isPoints||e.isLine)&&(e.visible=!1)})}restoreVisibility(){let e=this.scene,t=this._visibilityCache;e.traverse(function(e){let r=t.get(e);e.visible=r}),t.clear()}};__publicField(eO,"OUTPUT",{Default:0,SSAO:1,Blur:2,Beauty:3,Depth:4,Normal:5});let eL={shaderID:"luminosityHighPass",uniforms:{tDiffuse:{value:null},luminosityThreshold:{value:1},smoothWidth:{value:1},defaultColor:{value:new P.Color(0)},defaultOpacity:{value:0}},vertexShader:"varying vec2 vUv;\nvoid main() {\n	vUv = uv;\n	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D tDiffuse;\nuniform vec3 defaultColor;\nuniform float defaultOpacity;\nuniform float luminosityThreshold;\nuniform float smoothWidth;\nvarying vec2 vUv;\nvoid main() {\n	vec4 texel = texture2D( tDiffuse, vUv );\n	vec3 luma = vec3( 0.299, 0.587, 0.114 );\n	float v = dot( texel.xyz, luma );\n	vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );\n	float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );\n	gl_FragColor = mix( outputColor, texel, alpha );\n}"}
531,ek=class extends Pass{constructor(e,t,r,i){super(),this.strength=void 0!==t?t:1,this.radius=r,this.threshold=i,this.resolution=void 0!==e?new P.Vector2(e.x,e.y):new P.Vector2(256,256),this.clearColor=new P.Color(0,0,0),this.renderTargetsHorizontal=[],this.renderTargetsVertical=[],this.nMips=5;let a=Math.round(this.resolution.x/2),n=Math.round(this.resolution.y/2);this.renderTargetBright=new P.WebGLRenderTarget(a,n,{type:P.HalfFloatType}),this.renderTargetBright.texture.name="UnrealBloomPass.bright",this.renderTargetBright.texture.generateMipmaps=!1;for(let e=0;e<this.nMips;e++){let t=new P.WebGLRenderTarget(a,n,{type:P.HalfFloatType});t.texture.name="UnrealBloomPass.h"+e,t.texture.generateMipmaps=!1,this.renderTargetsHorizontal.push(t);let r=new P.WebGLRenderTarget(a,n,{type:P.HalfFloatType});r.texture.name="UnrealBloomPass.v"+e,r.texture.generateMipmaps=!1,this.renderTargetsVertical.push(r),a=Math.round(a/2),n=Math.round(n/2)}this.highPassUniforms=P.UniformsUtils.clone(eL.uniforms),this.highPassUniforms.luminosityThreshold.value=i,this.highPassUniforms.smoothWidth.value=.01,this.materialHighPassFilter=new P.ShaderMaterial({uniforms:this.highPassUniforms,vertexShader:eL.vertexShader,fragmentShader:eL.fragmentShader,defines:{}}),this.separableBlurMaterials=[];let s=[3,5,7,9,11];a=Math.round(this.resolution.x/2),n=Math.round(this.resolution.y/2);for(let e=0;e<this.nMips;e++)this.separableBlurMaterials.push(this.getSeperableBlurMaterial(s[e])),this.separableBlurMaterials[e].uniforms.texSize.value=new P.Vector2(a,n),a=Math.round(a/2),n=Math.round(n/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=t,this.compositeMaterial.uniforms.bloomRadius.value=.1,this.compositeMaterial.needsUpdate=!0,this.compositeMaterial.uniforms.bloomFactors.value=[1,.8,.6,.4,.2],this.bloomTintColors=[new P.Vector3(1,1,1),new P.Vector3(1,1,1),new P.Vector3(1,1,1),new P.Vector3(1,1,1),new P.Vector3(1,1,1)],this.compositeMaterial.uniforms.bloomTintColors.value=this.bloomTintColors,this.copyUniforms=P.UniformsUtils.clone(ew.uniforms),this.copyUniforms.opacity.value=1,this.materialCopy=new P.ShaderMaterial({uniforms:this.copyUniforms,vertexShader:ew.vertexShader,fragmentShader:ew.fragmentShader,blending:P.AdditiveBlending,depthTest:!1,depthWrite:!1,transparent:!0}),this.enabled=!0,this.needsSwap=!1,this._oldClearColor=new P.Color,this.oldClearAlpha=1,this.basic=new P.MeshBasicMaterial,this.fsQuad=new FullScreenQuad(null)}dispose(){for(let e=0;e<this.renderTargetsHorizontal.length;e++)this.renderTargetsHorizontal[e].dispose();for(let e=0;e<this.renderTargetsVertical.length;e++)this.renderTargetsVertical[e].dispose();this.renderTargetBright.dispose();for(let e=0;e<this.separableBlurMaterials.length;e++)this.separableBlurMaterials[e].dispose();this.compositeMaterial.dispose(),this.materialCopy.dispose(),this.basic.dispose(),this.fsQuad.dispose()}setSize(e,t){let r=Math.round(e/2),i=Math.round(t/2);this.renderTargetBright.setSize(r,i);for(let e=0;e<this.nMips;e++)this.renderTargetsHorizontal[e].setSize(r,i),this.renderTargetsVertical[e].setSize(r,i),this.separableBlurMaterials[e].uniforms.texSize.value=new P.Vector2(r,i),r=Math.round(r/2),i=Math.round(i/2)}render(e,t,r,i,a){e.getClearColor(this._oldClearColor),this.oldClearAlpha=e.getClearAlpha();let n=e.autoClear;e.autoClear=!1,e.setClearColor(this.clearColor,0),a&&e.state.buffers.stencil.setTest(!1),this.renderToScreen&&(this.fsQuad.material=this.basic,this.basic.map=r.texture,e.setRenderTarget(null),e.clear(),this.fsQuad.render(e)),this.highPassUniforms.tDiffuse.value=r.texture,this.highPassUniforms.luminosityThreshold.value=this.threshold,this.fsQuad.material=this.materialHighPassFilter,e.setRenderTarget(this.renderTargetBright),e.clear(),this.fsQuad.render(e);let s=this.renderTargetBright;for(let t=0;t<this.nMips;t++)this.fsQuad.material=this.separableBlurMaterials[t],this.separableBlurMaterials[t].uniforms.colorTexture.value=s.texture,this.separableBlurMaterials[t].uniforms.direction.value=ek.BlurDirectionX,e.setRenderTarget(this.renderTargetsHorizontal[t]),e.clear(),this.fsQuad.render(e),this.separableBlurMaterials[t].uniforms.colorTexture.value=this.renderTargetsHorizontal[t].texture,this.separableBlurMaterials[t].uniforms.direction.value=ek.BlurDirectionY,e.setRenderTarget(this.renderTargetsVertical[t]),e.clear(),this.fsQuad.render(e),s=this.renderTargetsVertical[t];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,e.setRenderTarget(this.renderTargetsHorizontal[0]),e.clear(),this.fsQuad.render(e),this.fsQuad.material=this.materialCopy,this.copyUniforms.tDiffuse.value=this.renderTargetsHorizontal[0].texture,a&&e.state.buffers.stencil.setTest(!0),this.renderToScreen?e.setRenderTarget(null):e.setRenderTarget(r),this.fsQuad.render(e),e.setClearColor(this._oldClearColor,this.oldClearAlpha),e.autoClear=n}getSeperableBlurMaterial(e){return new P.ShaderMaterial({defines:{KERNEL_RADIUS:e,SIGMA:e},uniforms:{colorTexture:{value:null},texSize:{value:new P.Vector2(.5,.5)},direction:{value:new P.Vector2(.5,.5)}},vertexShader:`varying vec2 vUv;
532				void main() {
533					vUv = uv;
534					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
535				}`,fragmentShader:`#include <common>
536				varying vec2 vUv;
537				uniform sampler2D colorTexture;
538				uniform vec2 texSize;
539				uniform vec2 direction;
540
541				float gaussianPdf(in float x, in float sigma) {
542					return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;
543				}
544				void main() {
545					vec2 invSize = 1.0 / texSize;
546					float fSigma = float(SIGMA);
547					float weightSum = gaussianPdf(0.0, fSigma);
548					vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;
549					for( int i = 1; i < KERNEL_RADIUS; i ++ ) {
550						float x = float(i);
551						float w = gaussianPdf(x, fSigma);
552						vec2 uvOffset = direction * invSize * x;
553						vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;
554						vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;
555						diffuseSum += (sample1 + sample2) * w;
556						weightSum += 2.0 * w;
557					}
558					gl_FragColor = vec4(diffuseSum/weightSum, 1.0);
559				}`})}getCompositeMaterial(e){return new P.ShaderMaterial({defines:{NUM_MIPS:e},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;
560				void main() {
561					vUv = uv;
562					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
563				}`,fragmentShader:`varying vec2 vUv;
564				uniform sampler2D blurTexture1;
565				uniform sampler2D blurTexture2;
566				uniform sampler2D blurTexture3;
567				uniform sampler2D blurTexture4;
568				uniform sampler2D blurTexture5;
569				uniform float bloomStrength;
570				uniform float bloomRadius;
571				uniform float bloomFactors[NUM_MIPS];
572				uniform vec3 bloomTintColors[NUM_MIPS];
573
574				float lerpBloomFactor(const in float factor) {
575					float mirrorFactor = 1.2 - factor;
576					return mix(factor, mirrorFactor, bloomRadius);
577				}
578
579				void main() {
580					gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) +
581						lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) +
582						lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) +
583						lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) +
584						lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0
584) * texture2D(blurTexture5, vUv) );
585				}`})}};__publicField(ek,"BlurDirectionX",new P.Vector2(1,0)),__publicField(ek,"BlurDirectionY",new P.Vector2(0,1));let eF={defines:{NUM_SAMPLES:7,NUM_RINGS:4,NORMAL_TEXTURE:0,DIFFUSE_TEXTURE:0,DEPTH_PACKING:1,PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},tDiffuse:{value:null},tNormal:{value:null},size:{value:new P.Vector2(512,512)},cameraNear:{value:1},cameraFar:{value:100},cameraProjectionMatrix:{value:new P.Matrix4},cameraInverseProjectionMatrix:{value:new P.Matrix4},scale:{value:1},intensity:{value:.1},bias:{value:.5},minResolution:{value:0},kernelRadius:{value:100},randomSeed:{value:0}},vertexShader:"varying vec2 vUv;\nvoid main() {\n	vUv = uv;\n	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"#include <common>\nvarying vec2 vUv;\n#if DIFFUSE_TEXTURE == 1\nuniform sampler2D tDiffuse;\n#endif\nuniform sampler2D tDepth;\n#if NORMAL_TEXTURE == 1\nuniform sampler2D tNormal;\n#endif\nuniform float cameraNear;\nuniform float cameraFar;\nuniform mat4 cameraProjectionMatrix;\nuniform mat4 cameraInverseProjectionMatrix;\nuniform float scale;\nuniform float intensity;\nuniform float bias;\nuniform float kernelRadius;\nuniform float minResolution;\nuniform vec2 size;\nuniform float randomSeed;\n// RGBA depth\n#include <packing>\nvec4 getDefaultColor( const in vec2 screenPosition ) {\n	#if DIFFUSE_TEXTURE == 1\n	return texture2D( tDiffuse, vUv );\n	#else\n	return vec4( 1.0 );\n	#endif\n}\nfloat getDepth( const in vec2 screenPosition ) {\n	#if DEPTH_PACKING == 1\n	return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );\n	#else\n	return texture2D( tDepth, screenPosition ).x;\n	#endif\n}\nfloat getViewZ( const in float depth ) {\n	#if PERSPECTIVE_CAMERA == 1\n	return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );\n	#else\n	return orthographicDepthToViewZ( depth, cameraNear, cameraFar );\n	#endif\n}\nvec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {\n	float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];\n	vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );\n	clipPosition *= clipW; // unprojection.\n	return ( cameraInverseProjectionMatrix * clipPosition ).xyz;\n}\nvec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) {\n	#if NORMAL_TEXTURE == 1\n	return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );\n	#else\n	return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n	#endif\n}\nfloat scaleDividedByCameraFar;\nfloat minResolutionMultipliedByCameraFar;\nfloat getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n	vec3 viewDelta = sampleViewPosition - centerViewPosition;\n	float viewDistance = length( viewDelta );\n	float scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n	return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) );\n}\n// moving costly divides into consts\nconst float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\nconst float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\nfloat getAmbientOcclusion( const in vec3 centerViewPosition ) {\n	// precompute some variables require in getOcclusion.\n	scaleDividedByCameraFar = scale / cameraFar;\n	minResolutionMultipliedByCameraFar = minResolution * cameraFar;\n	vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv );\n	// jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/\n	float angle = rand( vUv + randomSeed ) * PI2;\n	vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size;\n	vec2 radiusStep = radius;\n	float occlusionSum = 0.0;\n	float weightSum = 0.0;\n	for( int i = 0; i < NUM_SAMPLES; i ++ ) {\n		vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius;\n		radius += radiusStep;\n		angle += ANGLE_STEP;\n		float sampleDepth = getDepth( sampleUv );\n		if( sampleDepth >= ( 1.0 - EPSILON ) ) {\n			continue;\n		}\n		float sampleViewZ = getViewZ( sampleDepth );\n		vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ );\n		occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n		weightSum += 1.0;\n	}\n	if( weightSum == 0.0 ) discard;\n	return occlusionSum * ( intensity / weightSum );\n}\nvoid main() {\n	float centerDepth = getDepth( vUv );\n	if( centerDepth >= ( 1.0 - EPSILON ) ) {\n		discard;\n	}\n	float centerViewZ = getViewZ( centerDepth );\n	vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ );\n	float ambientOcclusion = getAmbientOcclusion( viewPosition );\n	gl_FragColor = getDefaultColor( vUv );\n	gl_FragColor.xyz *=  1.0 - ambientOcclusion;\n}"},eD={defines:{KERNEL_RADIUS:4,DEPTH_PACKING:1,PERSPECTIVE_CAMERA:1},uniforms:{tDiffuse:{value:null},size:{value:new P.Vector2(512,512)},sampleUvOffsets:{value:[new P.Vector2(0,0)]},sampleWeights:{value:[1]},tDepth:{value:null},cameraNear:{value:10},cameraFar:{value:1e3},depthCutoff:{value:10}},vertexShader:"#include <common>\nuniform vec2 size;\nvarying vec2 vUv;\nvarying vec2 vInvSize;\nvoid main() {\n	vUv = uv;\n	vInvSize = 1.0 / size;\n	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"#include <common>\n#include <packing>\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\nuniform float depthCutoff;\nuniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ];\nuniform float sampleWeights[ KERNEL_RADIUS + 1 ];\nvarying vec2 vUv;\nvarying vec2 vInvSize;\nfloat getDepth( const in vec2 screenPosition ) {\n	#if DEPTH_PACKING == 1\n	return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );\n	#else\n	return texture2D( tDepth, screenPosition ).x;\n	#endif\n}\nfloat getViewZ( const in float depth ) {\n	#if PERSPECTIVE_CAMERA == 1\n	return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );\n	#else\n	return orthographicDepthToViewZ( depth, cameraNear, cameraFar );\n	#endif\n}\nvoid main() {\n	float depth = getDepth( vUv );\n	if( depth >= ( 1.0 - EPSILON ) ) {\n		discard;\n	}\n	float centerViewZ = -getViewZ( depth );\n	bool rBreak = false, lBreak = false;\n	float weightSum = sampleWeights[0];\n	vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum;\n	for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n		float sampleWeight = sampleWeights[i];\n		vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize;\n		vec2 sampleUv = vUv + sampleUvOffset;\n		float viewZ = -getViewZ( getDepth( sampleUv ) );\n		if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true;\n		if( ! rBreak ) {\n			diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;\n			weightSum += sampleWeight;\n		}\n		sampleUv = vUv - sampleUvOffset;\n		viewZ = -getViewZ( getDepth( sampleUv ) );\n		if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true;\n		if( ! lBreak ) {\n			diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;\n			weightSum += sampleWeight;\n		}\n	}\n	gl_FragColor = diffuseSum / weightSum;\n}"},eU={createSampleWeights:(e,t)=>{let gaussian=(e,t)=>Math.exp(-(e*e)/(2*(t*t)))/(Math.sqrt(2*Math.PI)*t),r=[];for(let i=0;i<=e;i++)r.push(gaussian(i,t));return r},createSampleOffsets:(e,t)=>{let r=[];for(let i=0;i<=e;i++)r.push(t.clone().multiplyScalar(i));return r},configure:(e,t,r,i)=>{e.defines.KERNEL_RADIUS=t,e.uniforms.sampleUvOffsets.value=eU.createSampleOffsets(t,i),e.uniforms.sampleWeights.value=eU.createSampleWeights(t,r),e.needsUpdate=!0}};__publicField(class extends Pass{constructor(e,t,r=!1,i=!1,a=new P.Vector2(256,256)){let n;super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.supportsDepthTextureExtension=r,this.supportsNormalTexture=i,this.originalClearColor=new P.Color,this._oldClearColor=new P.Color,this.oldClearAlpha=1,this.params={output:0,saoBias:.5,saoIntensity:.18,saoScale:1,saoKernelRadius:100,saoMinResolution:0,saoBlur:!0,saoBlurRadius:8,saoBlurStdDev:4,saoBlurDepthCutoff:.01},this.resolution=new P.Vector2(a.x,a.y),this.saoRenderTarget=new P.WebGLRenderTarget(this.resolution.x,this.resolution.y,{type:P.HalfFloatType}),this.blurIntermediateRenderTarget=this.saoRenderTarget.clone(),this.beautyRenderTarget=this.saoRenderTarget.clone(),this.normalRenderTarget=new P.WebGLRenderTarget(this.resolution.x,this.resolution.y,{minFilter:P.NearestFilter,magFilter:P.NearestFilter,type:P.HalfFloatType}),this.depthRenderTarget=this.normalRenderTarget.clone(),this.supportsDepthTextureExtension&&((n=new P.DepthTexture).type=P.UnsignedShortType,this.beautyRenderTarget.depthTexture=n,this.beautyRenderTarget.depthBuffer=!0),this.depthMaterial=new P.MeshDepthMaterial,this.depthMaterial.depthPacking=P.RGBADepthPacking,this.depthMaterial.blending=P.NoBlending,this.normalMaterial=new P.MeshNormalMaterial,this.normalMaterial.blending=P.NoBlending,this.saoMaterial=new P.ShaderMaterial({defines:Object.assign({},eF.defines),fragmentShader:eF.fragmentShader,vertexShader:eF.vertexShader,uniforms:P.UniformsUtils.clone(eF.uniforms)}),this.saoMaterial.extensions.derivatives=!0,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?n: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=P.NoBlending,this.vBlurMaterial=new P.ShaderMaterial({uniforms:P.UniformsUtils.clone(eD.uniforms),defines:Object.assign({},eD.defines),vertexShader:eD.vertexShader,fragmentShader:eD.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?n:this.depthRenderTarget.texture,this.vBlurMaterial.uniforms.size.value.set(this.resolution.x,this.resolution.y),this.vBlurMaterial.blending=P.NoBlending,this.hBlurMaterial=new P.ShaderMaterial({uniforms:P.UniformsUtils.clone(eD.uniforms),defines:Object.assign({},eD.defines),vertexShader:eD.vertexShader,fragmentShader:eD.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?n:this.depthRenderTarget.texture,this.hBlurMaterial.uniforms.size.value.set(this.resolution.x,this.resolution.y),this.hBlurMaterial.blending=P.NoBlending,this.materialCopy=new P.ShaderMaterial({uniforms:P.UniformsUtils.clone(ew.uniforms),vertexShader:ew.vertexShader,fragmentShader:ew.fragmentShader,blending:P.NoBlending}),this.materialCopy.transparent=!0,this.materialCopy.depthTest=!1,this.materialCopy.depthWrite=!1,this.materialCopy.blending=P.CustomBlending,this.materialCopy.blendSrc=P.DstColorFactor,this.materialCopy.blendDst=P.ZeroFactor,this.materialCopy.blendEquation=P.AddEquation,this.materialCopy.blendSrcAlpha=P.DstAlphaFactor,this.materialCopy.blendDstAlpha=P.ZeroFactor,this.materialCopy.blendEquationAlpha=P.AddEquation,this.depthCopy=new P.ShaderMaterial({uniforms:P.UniformsUtils.clone(eo.uniforms),vertexShader:eo.vertexShader,fragmentShader:eo.fragmentShader,blending:P.NoBlending}),this.fsQuad=new FullScreenQuad(null)}render(e,t,r){if(this.renderToScreen&&(this.materialCopy.blending=P.NoBlending,this.materialCopy.uniforms.tDiffuse.value=r.texture,this.materialCopy.needsUpdate=!0,this.renderPass(e,this.materialCopy,null)),1===this.params.output)return;e.getClearColor(this._oldClearColor),this.oldClearAlpha=e.getClearAlpha();let i=e.autoClear;e.autoClear=!1,e.setRenderTarget(this.depthRenderTarget),e.clear(),this.saoMaterial.uniforms.bi
585as.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;let a=this.params.saoBlurDepthCutoff*(this.camera.far-this.camera.near);this.vBlurMaterial.uniforms.depthCutoff.value=a,this.hBlurMaterial.uniforms.depthCutoff.value=a,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),(this.prevStdDev!==this.params.saoBlurStdDev||this.prevNumSamples!==this.params.saoBlurRadius)&&(eU.configure(this.vBlurMaterial,this.params.saoBlurRadius,this.params.saoBlurStdDev,new P.Vector2(0,1)),eU.configure(this.hBlurMaterial,this.params.saoBlurRadius,this.params.saoBlurStdDev,new P.Vector2(1,0)),this.prevStdDev=this.params.saoBlurStdDev,this.prevNumSamples=this.params.saoBlurRadius),e.setClearColor(0),e.setRenderTarget(this.beautyRenderTarget),e.clear(),e.render(this.scene,this.camera),this.supportsDepthTextureExtension||this.renderOverride(e,this.depthMaterial,this.depthRenderTarget,0,1),this.supportsNormalTexture&&this.renderOverride(e,this.normalMaterial,this.normalRenderTarget,7829503,1),this.renderPass(e,this.saoMaterial,this.saoRenderTarget,16777215,1),this.params.saoBlur&&(this.renderPass(e,this.vBlurMaterial,this.blurIntermediateRenderTarget,16777215,1),this.renderPass(e,this.hBlurMaterial,this.saoRenderTarget,16777215,1));let n=this.materialCopy;3===this.params.output?this.supportsDepthTextureExtension?(this.materialCopy.uniforms.tDiffuse.value=this.beautyRenderTarget.depthTexture,this.materialCopy.needsUpdate=!0):(this.depthCopy.uniforms.tDiffuse.value=this.depthRenderTarget.texture,this.depthCopy.needsUpdate=!0,n=this.depthCopy):(4===this.params.output?this.materialCopy.uniforms.tDiffuse.value=this.normalRenderTarget.texture:this.materialCopy.uniforms.tDiffuse.value=this.saoRenderTarget.texture,this.materialCopy.needsUpdate=!0),0===this.params.output?n.blending=P.CustomBlending:n.blending=P.NoBlending,this.renderPass(e,n,this.renderToScreen?null:r),e.setClearColor(this._oldClearColor,this.oldClearAlpha),e.autoClear=i}renderPass(e,t,r,i,a){e.getClearColor(this.originalClearColor);let n=e.getClearAlpha(),s=e.autoClear;e.setRenderTarget(r),e.autoClear=!1,null!=i&&(e.setClearColor(i),e.setClearAlpha(a||0),e.clear()),this.fsQuad.material=t,this.fsQuad.render(e),e.autoClear=s,e.setClearColor(this.originalClearColor),e.setClearAlpha(n)}renderOverride(e,t,r,i,a){e.getClearColor(this.originalClearColor);let n=e.getClearAlpha(),s=e.autoClear;e.setRenderTarget(r),e.autoClear=!1,i=t.clearColor||i,a=t.clearAlpha||a,null!=i&&(e.setClearColor(i),e.setClearAlpha(a||0),e.clear()),this.scene.overrideMaterial=t,e.render(this.scene,this.camera),this.scene.overrideMaterial=null,e.autoClear=s,e.setClearColor(this.originalClearColor),e.setClearAlpha(n)}setSize(e,t){this.beautyRenderTarget.setSize(e,t),this.saoRenderTarget.setSize(e,t),this.blurIntermediateRenderTarget.setSize(e,t),this.normalRenderTarget.setSize(e,t),this.depthRenderTarget.setSize(e,t),this.saoMaterial.uniforms.size.value.set(e,t),this.saoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.saoMaterial.uniforms.cameraProjectionMatrix.value=this.camera.projectionMatrix,this.saoMaterial.needsUpdate=!0,this.vBlurMaterial.uniforms.size.value.set(e,t),this.vBlurMaterial.needsUpdate=!0,this.hBlurMaterial.uniforms.size.value.set(e,t),this.hBlurMaterial.needsUpdate=!0}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()}},"OUTPUT",{Beauty:1,Default:0,SAO:2,Depth:3,Normal:4});let eB={defines:{MAX_STEP:0,isPerspectiveCamera:!0,isDistanceAttenuation:!0,isFresnel:!0,isInfiniteThick:!1,isSelective:!1},uniforms:{tDiffuse:{value:null},tNormal:{value:null},tMetalness:{value:null},tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null},resolution:{value:new P.Vector2},cameraProjectionMatrix:{value:new P.Matrix4},cameraInverseProjectionMatrix:{value:new P.Matrix4},opacity:{value:.5},maxDistance:{value:180},cameraRange:{value:0},surfDist:{value:.007},thickTolerance:{value:.03}}
585,vertexShader:`
586
587    varying vec2 vUv;
588
589    void main() {
590
591			vUv = uv;
592
593			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
594
595    }
596
597  `,fragmentShader:`
598		// precision highp float;
599		precision highp sampler2D;
600		varying vec2 vUv;
601		uniform sampler2D tDepth;
602		uniform sampler2D tNormal;
603		uniform sampler2D tMetalness;
604		uniform sampler2D tDiffuse;
605		uniform float cameraRange;
606		uniform vec2 resolution;
607		uniform float opacity;
608		uniform float cameraNear;
609		uniform float cameraFar;
610		uniform float maxDistance;
611		uniform float surfDist;
612		uniform mat4 cameraProjectionMatrix;
613		uniform mat4 cameraInverseProjectionMatrix;
614		uniform float thickTolerance;
615		#include <packing>
616		float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) {
617			//x0: point, x1: linePointA, x2: linePointB
618			//https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
619			return length(cross(x0-x1,x0-x2))/length(x2-x1);
620		}
621		float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){
622			// https://mathworld.wolfram.com/Point-PlaneDistance.html
623			//// https://en.wikipedia.org/wiki/Plane_(geometry)
624			//// http://paulbourke.net/geometry/pointlineplane/
625			float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z;
626			float x0=point.x,y0=point.y,z0=point.z;
627			float x=planePoint.x,y=planePoint.y,z=planePoint.z;
628			float d=-(a*x+b*y+c*z);
629			float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c);
630			return distance;
631		}
632		float getDepth( const in vec2 uv ) {
633			return texture2D( tDepth, uv ).x;
634		}
635		float getViewZ( const in float depth ) {
636			#ifdef isPerspectiveCamera
637				return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
638			#else
639				return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
640			#endif
641		}
642		vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
643			vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
644			clipPosition *= clipW; //clip
645			return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view
646		}
647		vec3 getViewNormal( const in vec2 uv ) {
648			return unpackRGBToNormal( texture2D( tNormal, uv ).xyz );
649		}
650		vec2 viewPositionToXY(vec3 viewPosition){
651			vec2 xy;
652			vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1);
653			xy=clip.xy;//clip
654			float clipW=clip.w;
655			xy/=clipW;//NDC
656			xy=(xy+1.)/2.;//uv
657			xy*=resolution;//screen
658			return xy;
659		}
660		void main(){
661			#ifdef isSelective
662				float metalness=texture2D(tMetalness,vUv).r;
663				if(metalness==0.) return;
664			#endif
665
666			float depth = getDepth( vUv );
667			float viewZ = getViewZ( depth );
668			if(-viewZ>=cameraFar) return;
669
670			float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3];
671			vec3 viewPosition=getViewPosition( vUv, depth, clipW );
672
673			vec2 d0=gl_FragCoord.xy;
674			vec2 d1;
675
676			vec3 viewNormal=getViewNormal( vUv );
677
678			#ifdef isPerspectiveCamera
679				vec3 viewIncidenceDir=normalize(viewPosition);
680				vec3 viewReflectDir=reflect(viewIncidenceDir,viewNormal);
681			#else
682				vec3 viewIncidenceDir=vec3(0,0,-1);
683				vec3 viewReflectDir=reflect(viewIncidenceDir,viewNormal);
684			#endif
685
686			float maxReflectRayLen=maxDistance/dot(-viewIncidenceDir,viewNormal);
687			// dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html
688			// if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta)
689			// maxDistance/maxReflectRayLen=cos(theta)
690			// maxDistance/maxReflectRayLen==dot(a,b)
691			// maxReflectRayLen==maxDistance/dot(a,b)
692
693			vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen;
694			#ifdef isPerspectiveCamera
695				if(d1viewPosition.z>-cameraNear){
696					//https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx
697					float t=(-cameraNear-viewPosition.z)/viewReflectDir.z;
698					d1viewPosition=viewPosition+viewReflectDir*t;
699				}
700			#endif
701			d1=viewPositionToXY(d1viewPosition);
702
703			float totalLen=length(d1-d0);
704			float xLen=d1.x-d0.x;
705			float yLen=d1.y-d0.y;
706			float totalStep=max(abs(xLen),abs(yLen));
707			float xSpan=xLen/totalStep;
708			float ySpan=yLen/totalStep;
709			for(float i=0.;i<MAX_STEP;i++){
710				if(i>=totalStep) break;
711				vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan);
712				if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break;
713				float s=length(xy-d0)/totalLen;
714				vec2 uv=xy/resolution;
715
716				float d = getDepth(uv);
717				float vZ = getViewZ( d );
718				if(-vZ>=cameraFar) continue;
719				float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3];
720				vec3 vP=getViewPosition( uv, d, cW );
721
722				#ifdef isPerspectiveCamera
723					// https://www.comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf
724					float recipVPZ=1./viewPosition.z;
725					float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ));
726					float sD=surfDist*cW;
727				#else
728					float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z);
729					float sD=surfDist;
730				#endif
731				if(viewReflectRayZ-sD>vZ) continue;
732
733				#ifdef isInfiniteThick
734					if(viewReflectRayZ+thickTolerance*clipW<vP.z) break;
735				#endif
736				float away=pointToLineDistance(vP,viewPosition,d1viewPosition);
737
738				float op=opacity;
739
740				if(away<sD){
741					vec3 vN=getViewNormal( uv );
742					if(dot(viewReflectDir,vN)>=0.) continue;
743					float distance=pointPlaneDistance(vP,viewPosition,viewNormal);
744					if(distance>maxDistance) break;
745					#ifdef isDistanceAttenuation
746						float ratio=1.-(distance/maxDistance);
747						float attenuation=ratio*ratio;
748						op=opacity*attenuation;
749					#endif
750					#ifdef isFresnel
751						float fresnel=(dot(viewIncidenceDir,viewReflectDir)+1.)/2.;
752						op*=fresnel;
753					#endif
754					vec4 reflectColor=texture2D(tDiffuse,uv);
755					gl_FragColor.xyz=reflectColor.xyz;
756					gl_FragColor.a=op;
757					break;
758				}
759			}
760		}
761	`},eV={defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:`
762
763    varying vec2 vUv;
764
765    void main() {
766
767    	vUv = uv;
768    	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
769
770    }
771
772  `,fragmentShader:`
773
774    uniform sampler2D tDepth;
775
776    uniform float cameraNear;
777    uniform float cameraFar;
778
779    varying vec2 vUv;
780
781    #include <packing>
782
783		float getLinearDepth( const in vec2 uv ) {
784
785			#if PERSPECTIVE_CAMERA == 1
786
787				float fragCoordZ = texture2D( tDepth, uv ).x;
788				float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
789				return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
790
791			#else
792
793				return texture2D( tDepth, uv ).x;
794
795			#endif
796
797		}
798
799    void main() {
800
801    	float depth = getLinearDepth( vUv );
802			float d = 1.0 - depth;
803			// d=(d-.999)*1000.;
804    	gl_FragColor = vec4( vec3( d ), 1.0 );
805
806    }
807
808  `},ez={uniforms:{tDiffuse:{value:null},resolution:{value:new P.Vector2},opacity:{value:.5}},vertexShader:`
809
810    varying vec2 vUv;
811
812    void main() {
813
814    	vUv = uv;
815    	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
816
817    }
818
819  `,fragmentShader:`
820
821    uniform sampler2D tDiffuse;
822    uniform vec2 resolution;
823    varying vec2 vUv;
824    void main() {
825			//reverse engineering from PhotoShop blur filter, then change coefficient
826
827    	vec2 texelSize = ( 1.0 / resolution );
828
829			vec4 c=texture2D(tDiffuse,vUv);
830
831			vec2 offset;
832
833			offset=(vec2(-1,0))*texelSize;
834			vec4 cl=texture2D(tDiffuse,vUv+offset);
835
836			offset=(vec2(1,0))*texelSize;
837			vec4 cr=texture2D(tDiffuse,vUv+offset);
838
839			offset=(vec2(0,-1))*texelSize;
840			vec4 cb=texture2D(tDiffuse,vUv+offset);
841
842			offset=(vec2(0,1))*texelSize;
843			vec4 ct=texture2D(tDiffuse,vUv+offset);
844
845			// float coeCenter=.5;
846			// float coeSide=.125;
847			float coeCenter=.2;
848			float coeSide=.2;
849			float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide;
850			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;
851			gl_FragColor=vec4(rgb,a);
852
853		}
854	`},ej=class extends Pass{constructor({renderer:e,scene:t,camera:r,width:i,height:a,selects:n,bouncing:s=!1,groundReflector:o}){super(),this.width=void 0!==i?i:512,this.height=void 0!==a?a:512,this.clear=!0,this.renderer=e,this.scene=t,this.camera=r,this.groundReflector=o,this.opacity=eB.uniforms.opacity.value,this.output=0,this.maxDistance=eB.uniforms.maxDistance.value,this.thickness=eB.uniforms.thickness.value,this.tempColor=new P.Color,this._selects=n,this.selective=Array.isArray(this._selects),Object.defineProperty(this,"selects",{get(){return this._selects},set(e){this._selects!==e&&(this._selects=e,Array.isArray(e)?(this.selective=!0,this.ssrMaterial.defines.SELECTIVE=!0):(this.selective=!1,this.ssrMaterial.defines.SELECTIVE=!1),this.ssrMaterial.needsUpdate=!0)}}),this._bouncing=s,Object.defineProperty(this,"bouncing",{get(){return this._bouncing},set(e){this._bouncing!==e&&(this._bouncing=e,e?this.ssrMaterial.uniforms.tDiffuse.value=this.prevRenderTarget.texture:this.ssrMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture)}}),this.blur=!0,this._distanceAttenuation=eB.defines.DISTANCE_ATTENUATION,Object.defineProperty(this,"distanceAttenuation",{get(){return this._distanceAttenuation},set(e){this._distanceAttenuation!==e&&(this._distanceAttenuation=e,this.ssrMaterial.defines.DISTANCE_ATTENUATION=e,this.ssrMaterial.needsUpdate=!0)}}),this._fresnel=eB.defines.FRESNEL,Object.defineProperty(this,"fresnel",{get(){return this._fresnel},set(e){this._fresnel!==e&&(this._fresnel=e,this.ssrMaterial.defines.FRESNEL=e,this.ssrMaterial.needsUpdate=!0)}}),this._infiniteThick=eB.defines.INFINITE_THICK,Object.defineProperty(this,"infiniteThick",{get(){return this._infiniteThick},set(e){this._infiniteThick!==e&&(this._infiniteThick=e,this.ssrMaterial.defines.INFINITE_THICK=e,this.ssrMaterial.needsUpdate=!0)}});let l=new P.DepthTexture;l.type=P.UnsignedShortType,l.minFilter=P.NearestFilter,l.magFilter=P.NearestFilter,this.beautyRenderTarget=new P.WebGLRenderTarget(this.width,this.height,{minFilter:P.NearestFilter,magFilter:P.NearestFilter,type:P.HalfFloatType,depthTexture:l,depthBuffer:!0}),this.prevRenderTarget=new P.WebGLRenderTarget(this.width,this.height,{minFilter:P.NearestFilter,magFilter:P.NearestFilter}),this.normalRenderTarget=new P.WebGLRenderTarget(this.width,this.height,{minFilter:P.NearestFilter,magFilter:P.NearestFilter,type:P.HalfFloatType}),this.metalnessRenderTarget=new P.WebGLRenderTarget(this.width,this.height,{minFilter:P.NearestFilter,magFilter:P.NearestFilter,type:P.HalfFloatType}),this.ssrRenderTarget=new P.WebGLRenderTarget(this.width,this.height,{minFilter:P.NearestFilter,magFilter:P.NearestFilter}),this.blurRenderTarget=this.ssrRenderTarget.clone(),this.blurRenderTarget2=this.ssrRenderTarget.clone(),this.ssrMaterial=new P.ShaderMaterial({defines:Object.assign({}
854,eB.defines,{MAX_STEP:Math.sqrt(this.width*this.width+this.height*this.height)}),uniforms:P.UniformsUtils.clone(eB.uniforms),vertexShader:eB.vertexShader,fragmentShader:eB.fragmentShader,blending:P.NoBlending}),this.ssrMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.ssrMaterial.uniforms.tNormal.value=this.normalRenderTarget.texture,this.ssrMaterial.defines.SELECTIVE=this.selective,this.ssrMaterial.needsUpdate=!0,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 P.MeshNormalMaterial,this.normalMaterial.blending=P.NoBlending,this.metalnessOnMaterial=new P.MeshBasicMaterial({color:"white"}),this.metalnessOffMaterial=new P.MeshBasicMaterial({color:"black"}),this.blurMaterial=new P.ShaderMaterial({defines:Object.assign({},ez.defines),uniforms:P.UniformsUtils.clone(ez.uniforms),vertexShader:ez.vertexShader,fragmentShader:ez.fragmentShader}),this.blurMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture,this.blurMaterial.uniforms.resolution.value.set(this.width,this.height),this.blurMaterial2=new P.ShaderMaterial({defines:Object.assign({},ez.defines),uniforms:P.UniformsUtils.clone(ez.uniforms),vertexShader:ez.vertexShader,fragmentShader:ez.fragmentShader}),this.blurMaterial2.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.blurMaterial2.uniforms.resolution.value.set(this.width,this.height),this.depthRenderMaterial=new P.ShaderMaterial({defines:Object.assign({},eV.defines),uniforms:P.UniformsUtils.clone(eV.uniforms),vertexShader:eV.vertexShader,fragmentShader:eV.fragmentShader,blending:P.NoBlending}),this.depthRenderMaterial.uniforms.tDepth.value=this.beautyRenderTarget.depthTexture,this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new P.ShaderMaterial({uniforms:P.UniformsUtils.clone(ew.uniforms),vertexShader:ew.vertexShader,fragmentShader:ew.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:P.SrcAlphaFactor,blendDst:P.OneMinusSrcAlphaFactor,blendEquation:P.AddEquation,blendSrcAlpha:P.SrcAlphaFactor,blendDstAlpha:P.OneMinusSrcAlphaFactor,blendEquationAlpha:P.AddEquation}),this.fsQuad=new FullScreenQuad(null),this.originalClearColor=new P.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(e,t){switch(e.setRenderTarget(this.beautyRenderTarget),e.clear(),this.groundReflector&&(this.groundReflector.visible=!1,this.groundReflector.doRender(this.renderer,this.scene,this.camera),this.groundReflector.visible=!0),e.render(this.scene,this.camera),this.groundReflector&&(this.groundReflector.visible=!1),this.renderOverride(e,this.normalMaterial,this.normalRenderTarget,0,0),this.selective&&this.renderMetalness(e,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(e,this.ssrMaterial,this.ssrRenderTarget),this.blur&&(this.renderPass(e,this.blurMaterial,this.blurRenderTarget),this.renderPass(e,this.blurMaterial2,this.blurRenderTarget2)),this.output){case ej.OUTPUT.Default:this.bouncing?(this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.prevRenderTarget),this.blur?this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture:this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture,this.copyMaterial.blending=P.NormalBlending,this.renderPass(e,this.copyMaterial,this.prevRenderTarget),this.copyMaterial.uniforms.tDiffuse.value=this.prevRenderTarget.texture,this.copyMaterial.blending=P.NoBlending):(this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t),this.blur?this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture:this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture,this.copyMaterial.blending=P.NormalBlending),this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case ej.OUTPUT.SSR:this.blur?this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture:this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t),this.bouncing&&(this.blur?this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture:this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.prevRenderTarget),this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture,this.copyMaterial.blending=P.NormalBlending,this.renderPass(e,this.copyMaterial,this.prevRenderTarget));break;case ej.OUTPUT.Beauty:this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case ej.OUTPUT.Depth:this.renderPass(e,this.depthRenderMaterial,this.renderToScreen?null:t);break;case ej.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;case ej.OUTPUT.Metalness:this.copyMaterial.uniforms.tDiffuse.value=this.metalnessRenderTarget.texture,this.copyMaterial.blending=P.NoBlending,this.renderPass(e,this.copyMaterial,this.renderToScreen?null:t);break;default:console.warn("THREE.SSRPass: Unknown output type.")}}renderPass(e,t,r,i,a){this.originalClearColor.copy(e.getClearColor(this.tempColor));let n=e.getClearAlpha(this.tempColor),s=e.autoClear;e.setRenderTarget(r),e.autoClear=!1,null!=i&&(e.setClearColor(i),e.setClearAlpha(a||0),e.clear()),this.fsQuad.material=t,this.fsQuad.render(e),e.autoClear=s,e.setClearColor(this.originalClearColor),e.setClearAlpha(n)}renderOverride(e,t,r,i,a){this.originalClearColor.copy(e.getClearColor(this.tempColor));let n=e.getClearAlpha(this.tempColor),s=e.autoClear;e.setRenderTarget(r),e.autoClear=!1,i=t.clearColor||i,a=t.clearAlpha||a,null!=i&&(e.setClearColor(i),e.setClearAlpha(a||0),e.clear()),this.scene.overrideMaterial=t,e.render(this.scene,this.camera),this.scene.overrideMaterial=null,e.autoClear=s,e.setClearColor(this.originalClearColor),e.setClearAlpha(n)}renderMetalness(e,t,r,i,a){this.originalClearColor.copy(e.getClearColor(this.tempColor));let n=e.getClearAlpha(this.tempColor),s=e.autoClear;e.setRenderTarget(r),e.autoClear=!1,i=t.clearColor||i,a=t.clearAlpha||a,null!=i&&(e.setClearColor(i),e.setClearAlpha(a||0),e.clear()),this.scene.traverseVisible(e=>{e._SSRPassBackupMaterial=e.material,this._selects.includes(e)?e.material=this.metalnessOnMaterial:e.material=this.metalnessOffMaterial}),e.render(this.scene,this.camera),this.scene.traverseVisible(e=>{e.material=e._SSRPassBackupMaterial}),e.autoClear=s,e.setClearColor(this.originalClearColor),e.setClearAlpha(n)}setSize(e,t){this.width=e,this.height=t,this.ssrMaterial.defines.MAX_STEP=Math.sqrt(e*e+t*t),this.ssrMaterial.needsUpdate=!0,this.beautyRenderTarget.setSize(e,t),this.prevRenderTarget.setSize(e,t),this.ssrRenderTarget.setSize(e,t),this.normalRenderTarget.setSize(e,t),this.metalnessRenderTarget.setSize(e,t),this.blurRenderTarget.setSize(e,t),this.blurRenderTarget2.setSize(e,t),this.ssrMaterial.uniforms.resolution.value.set(e,t),this.ssrMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssrMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.blurMaterial.uniforms.resolution.value.set(e,t),this.blurMaterial2.uniforms.resolution.value.set(e,t)}};__publicField(ej,"OUTPUT",{Default:0,SSR:1,Beauty:3,Depth:4,Normal:5,Metalness:7}),Int8Array,Uint8Array,Int16Array,Uint16Array,Uint32Array,Float32Array,P.NearestFilter,P.LinearFilter,P.NearestMipmapNearestFilter,P.LinearMipmapNearestFilter,P.NearestMipmapLinearFilter,P.LinearMipmapLinearFilter,P.ClampToEdgeWrapping,P.MirroredRepeatWrapping,P.RepeatWrapping,P.REVISION.replace(/\D+/g,""),P.InterpolateLinear,P.InterpolateDiscrete;let eG=class{static createButton(e,t={}){let r=document.createElement("button");function stylizeElement(e){e.style.position="absolute",e.style.bottom="20px",e.style.padding="12px 6px",e.style.border="1px solid #fff",e.style.borderRadius="4px",e.style.background="rgba(0,0,0,0.1)",e.style.color="#fff",e.style.font="normal 13px sans-serif",e.style.textAlign="center",e.style.opacity="0.5",e.style.outline="none",e.style.zIndex="999"}if("xr"in navigator)return stylizeElement(r),r.id="VRButton",r.style.display="none",navigator.xr.isSessionSupported("immersive-vr").then(i=>{i?function(){let i=null;async function onSessionStarted(t){t.addEventListener("end",onSessionEnded),await e.xr.setSession(t),r.textContent="EXIT VR",i=t}function onSessionEnded(){i.removeEventListener("end",onSessionEnded),r.textContent="ENTER VR",i=null}r.style.display="",r.style.cursor="pointer",r.style.left="calc(50% - 50px)",r.style.width="100px",r.textContent="ENTER VR",r.onmouseenter=()=>{r.style.opacity="1.0"},r.onmouseleave=()=>{r.style.opacity="0.5"}
854,r.onclick=()=>{var e;if(null===i){let r=[t.optionalFeatures,"local-floor","bounded-floor","hand-tracking"].flat().filter(Boolean);null==(e=navigator.xr)||e.requestSession("immersive-vr",{...t,optionalFeatures:r}).then(onSessionStarted)}else i.end()}}():(r.style.display="",r.style.cursor="auto",r.style.left="calc(50% - 75px)",r.style.width="150px",r.onmouseenter=null,r.onmouseleave=null,r.onclick=null,r.textContent="VR NOT SUPPORTED"),i&&eG.xrSessionIsGranted&&r.click()}),r;{let e=document.createElement("a");return!1===window.isSecureContext?(e.href=document.location.href.replace(/^http:/,"https:"),e.innerHTML="WEBXR NEEDS HTTPS"):(e.href="https://immersiveweb.dev/",e.innerHTML="WEBXR NOT AVAILABLE"),e.style.left="calc(50% - 90px)",e.style.width="180px",e.style.textDecoration="none",stylizeElement(e),e}}static registerSessionGrantedListener(){"xr"in navigator&&navigator.xr.addEventListener("sessiongranted",()=>{eG.xrSessionIsGranted=!0})}};__publicField(eG,"xrSessionIsGranted",!1);let eW=new P.Matrix4;let CSMFrustum=class CSMFrustum{constructor(e){e=e||{},this.vertices={near:[new P.Vector3,new P.Vector3,new P.Vector3,new P.Vector3],far:[new P.Vector3,new P.Vector3,new P.Vector3,new P.Vector3]},void 0!==e.projectionMatrix&&this.setFromProjectionMatrix(e.projectionMatrix,e.maxFar||1e4)}setFromProjectionMatrix(e,t){let r=0===e.elements[11];return eW.copy(e).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(e){e.applyMatrix4(eW)}),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(e){e.applyMatrix4(eW);let i=Math.abs(e.z);r?e.z*=Math.min(t/i,1):e.multiplyScalar(Math.min(t/i,1))}),this.vertices}split(e,t){for(;e.length>t.length;)t.push(new CSMFrustum);t.length=e.length;for(let r=0;r<e.length;r++){let i=t[r];if(0===r)for(let e=0;e<4;e++)i.vertices.near[e].copy(this.vertices.near[e]);else for(let t=0;t<4;t++)i.vertices.near[t].lerpVectors(this.vertices.near[t],this.vertices.far[t],e[r-1]);if(r===e.length-1)for(let e=0;e<4;e++)i.vertices.far[e].copy(this.vertices.far[e]);else for(let t=0;t<4;t++)i.vertices.far[t].lerpVectors(this.vertices.near[t],this.vertices.far[t],e[r])}}toSpace(e,t){for(let r=0;r<4;r++)t.vertices.near[r].copy(this.vertices.near[r]).applyMatrix4(e),t.vertices.far[r].copy(this.vertices.far[r]).applyMatrix4(e)}};let Font=class Font{constructor(e){__publicField(this,"data"),this.data=e}generateShapes(e,t=100,r){let i=[],a={letterSpacing:0,lineHeight:1,...r},n=function(e,t,r,i){let a=Array.from(e),n=t/r.resolution,s=(r.boundingBox.yMax-r.boundingBox.yMin+r.underlineThickness)*n,o=[],l=0,c=0;for(let e=0;e<a.length;e++){let t=a[e];if("\n"===t)l=0,c-=s*i.lineHeight;else{let e=function(e,t,r,i,a){let n,s,o,l,c,u,h,d;let p=a.glyphs[e]||a.glyphs["?"];if(!p){console.error('THREE.Font: character "'+e+'" does not exists in font family '+a.familyName+".");return}let f=new P.ShapePath;if(p.o){let e=p._cachedOutline||(p._cachedOutline=p.o.split(" "));for(let a=0,p=e.length;a<p;){let p=e[a++];switch(p){case"m":n=parseInt(e[a++])*t+r,s=parseInt(e[a++])*t+i,f.moveTo(n,s);break;case"l":n=parseInt(e[a++])*t+r,s=parseInt(e[a++])*t+i,f.lineTo(n,s);break;case"q":o=parseInt(e[a++])*t+r,l=parseInt(e[a++])*t+i,c=parseInt(e[a++])*t+r,u=parseInt(e[a++])*t+i,f.quadraticCurveTo(c,u,o,l);break;case"b":o=parseInt(e[a++])*t+r,l=parseInt(e[a++])*t+i,c=parseInt(e[a++])*t+r,u=parseInt(e[a++])*t+i,h=parseInt(e[a++])*t+r,d=parseInt(e[a++])*t+i,f.bezierCurveTo(c,u,h,d,o,l)}}}return{offsetX:p.ha*t,path:f}}(t,n,l,c,r);e&&(l+=e.offsetX+i.letterSpacing,o.push(e.path))}}return o}(e,t,this.data,a);for(let e=0,t=n.length;e<t;e++)Array.prototype.push.apply(i,n[e].toShapes(!1));return i}};__publicField(Font,"isFont"),__publicField(Font,"type");let Data3DTexture=class Data3DTexture extends P.Texture{constructor(e=null,t=1,r=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:r,depth:i},this.magFilter=P.NearestFilter,this.minFilter=P.NearestFilter,this.wrapR=P.ClampToEdgeWrapping,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};var eH="object"==typeof global&&global&&global.Object===Object&&global,eK="object"==typeof self&&self&&self.Object===Object&&self,e$=eH||eK||Function("return this")(),eY=e$.
854Symbol,eX=Object.prototype,eZ=eX.hasOwnProperty,eQ=eX.toString,eJ=eY?eY.toStringTag:void 0,e1=Object.prototype.toString,e0=eY?eY.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":e0&&e0 in Object(e)?function(e){var t=eZ.call(e,eJ),r=e[eJ];try{e[eJ]=void 0;var i=!0}catch(e){}var a=eQ.call(e);return i&&(t?e[eJ]=r:delete e[eJ]),a}(e):e1.call(e)}function isObjectLike(e){return null!=e&&"object"==typeof e}function isSymbol(e){return"symbol"==typeof e||isObjectLike(e)&&"[object Symbol]"==baseGetTag(e)}function arrayMap(e,t){for(var r=-1,i=null==e?0:e.length,a=Array(i);++r<i;)a[r]=t(e[r],r,e);return a}var e2=Array.isArray,e3=1/0,e4=eY?eY.prototype:void 0,e5=e4?e4.toString:void 0,e6=/\s/,e8=/^\s+/;function isObject(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var e9=0/0,e7=/^[-+]0x[0-9a-f]+$/i,te=/^0b[01]+$/i,tt=/^0o[0-7]+$/i,tr=parseInt,ti=1/0;function toInteger(e){var t,r=(t=e)?(t=function(e){if("number"==typeof e)return e;if(isSymbol(e))return e9;if(isObject(e)){var t,r="function"==typeof e.valueOf?e.valueOf():e;e=isObject(r)?r+"":r}if("string"!=typeof e)return 0===e?e:+e;e=(t=e)?t.slice(0,function(e){for(var t=e.length;t--&&e6.test(e.charAt(t)););return t}(t)+1).replace(e8,""):t;var i=te.test(e);return i||tt.test(e)?tr(e.slice(2),i?2:8):e7.test(e)?e9:+e}(t))===ti||t===-ti?(t<0?-1:1)*17976931348623157e292:t==t?t:0:0===t?t:0,i=r%1;return r==r?i?r-i:r:0}function identity(e){return e}function isFunction(e){if(!isObject(e))return!1;var t=baseGetTag(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}var ta=e$["__core-js_shared__"],tn=(p=/[^.]+$/.exec(ta&&ta.keys&&ta.keys.IE_PROTO||""))?"Symbol(src)_1."+p:"",ts=Function.prototype.toString;function toSource(e){if(null!=e){try{return ts.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var to=/^\[object .+?Constructor\]$/,tl=Object.prototype,tc=Function.prototype.toString,tu=tl.hasOwnProperty,th=RegExp("^"+tc.call(tu).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function getNative(e,t){var r=null==e?void 0:e[t];return isObject(r)&&(!tn||!(tn in r))&&(isFunction(r)?th:to).test(toSource(r))?r:void 0}var td=getNative(e$,"WeakMap"),tp=Object.create,tf=function(){function object(){}return function(e){if(!isObject(e))return{};if(tp)return tp(e);object.prototype=e;var t=new object;return object.prototype=void 0,t}}();function noop(){}var tm=Date.now,tg=function(){try{var e=getNative(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),tv=tg?function(e,t){return tg(e,"toString",{configurable:!0,enumerable:!1,value:function(){return t},writable:!0})}:identity,ty=(f=0,m=0,function(){var e=tm(),t=16-(e-m);if(m=e,t>0){if(++f>=800)return arguments[0]}else f=0;return tv.apply(void 0,arguments)});function arrayEach(e,t){for(var r=-1,i=null==e?0:e.length;++r<i&&!1!==t(e[r],r,e););return e}function baseFindIndex(e,t,r,i){for(var a=e.length,n=r+(i?1:-1);i?n--:++n<a;)if(t(e[n],n,e))return n;return -1}function baseIsNaN(e){return e!=e}function baseIndexOf(e,t,r){return t==t?function(e,t,r){for(var i=r-1,a=e.length;++i<a;)if(e[i]===t)return i;return -1}(e,t,r):baseFindIndex(e,baseIsNaN,r)}function arrayIncludes(e,t){return!!(null==e?0:e.length)&&baseIndexOf(e,t,0)>-1}var tT=/^(?:0|[1-9]\d*)$/;function isIndex(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&tT.test(e))&&e>-1&&e%1==0&&e<t}function baseAssignValue(e,t,r){"__proto__"==t&&tg?tg(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}function eq(e,t){return e===t||e!=e&&t!=t}var tx=Object.prototype.hasOwnProperty;function assignValue(e,t,r){var i=e[t];tx.call(e,t)&&eq(i,r)&&(void 0!==r||t in e)||baseAssignValue(e,t,r)}function copyObject(e,t,r,i){var a=!r;r||(r={});for(var n=-1,s=t.length;++n<s;){var o=t[n],l=i?i(r[o],e[o],o,r,e):void 0;void 0===l&&(l=e[o]),a?baseAssignValue(r,o,l):assignValue(r,o,l)}return r}var tS=Math.max;function baseRest(e,t){var r;return ty((r=tS(void 0===(r=t)?e.length-1:r,0),function(){for(var t=arguments,i=-1,a=tS(t.length-r,0),n=Array(a);++i<a;)n[i]=t[r+i];i=-1;for(var s=Array(r+1);++i<r;)s[i]=t[i];return s[r]=identity(n),function(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}(e,this,s)}),e+"")}function isLength(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}function isArrayLike(e){return null!=e&&isLength(e.length)&&!isFunction(e)}function isIterateeCall(e,t,r){if(!isObject(r))return!1;var i=typeof t;return("number"==i?!!(isArrayLike(r)&&isIndex(t,r.length)):"string"==i&&t in r)&&eq(r[t],e)}var tE=Object.prototype;function isPrototype(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||tE)}function baseIsArguments(e){return isObjectLike(e)&&"[object Arguments]"==baseGetTag(e)}var tb=Object.prototype,tR=tb.hasOwnProperty,tA=tb.propertyIsEnumerable,t_=baseIsArguments(function(){return arguments}())?baseIsArguments:function(e){return isObjectLike(e)&&tR.call(e,"callee")&&!tA.call(e,"callee")},tM="object"==typeof exports&&exports&&!exports.nodeType&&exports,tC=tM&&"object"==typeof module&&module&&!module.nodeType&&module,tw=tC&&tC.exports===tM?e$.Buffer:void 0,tI=tw?tw.isBuffer:void 0;let tP=tI||function(){return!1};var tN={};function baseUnary(e){return function(t){return e(t)}}
854tN["[object Float32Array]"]=tN["[object Float64Array]"]=tN["[object Int8Array]"]=tN["[object Int16Array]"]=tN["[object Int32Array]"]=tN["[object Uint8Array]"]=tN["[object Uint8ClampedArray]"]=tN["[object Uint16Array]"]=tN["[object Uint32Array]"]=!0,tN["[object Arguments]"]=tN["[object Array]"]=tN["[object ArrayBuffer]"]=tN["[object Boolean]"]=tN["[object DataView]"]=tN["[object Date]"]=tN["[object Error]"]=tN["[object Function]"]=tN["[object Map]"]=tN["[object Number]"]=tN["[object Object]"]=tN["[object RegExp]"]=tN["[object Set]"]=tN["[object String]"]=tN["[object WeakMap]"]=!1;var tO="object"==typeof exports&&exports&&!exports.nodeType&&exports,tL=tO&&"object"==typeof module&&module&&!module.nodeType&&module,tk=tL&&tL.exports===tO&&eH.process,tF=function(){try{var e=tL&&tL.require&&tL.require("util").types;if(e)return e;return tk&&tk.binding&&tk.binding("util")}catch(e){}}(),tD=tF&&tF.isTypedArray,tU=tD?baseUnary(tD):function(e){return isObjectLike(e)&&isLength(e.length)&&!!tN[baseGetTag(e)]},tB=Object.prototype.hasOwnProperty;function arrayLikeKeys(e,t){var r=e2(e),i=!r&&t_(e),a=!r&&!i&&tP(e),n=!r&&!i&&!a&&tU(e),s=r||i||a||n,o=s?function(e,t){for(var r=-1,i=Array(e);++r<e;)i[r]=t(r);return i}(e.length,String):[],l=o.length;for(var c in e)(t||tB.call(e,c))&&!(s&&("length"==c||a&&("offset"==c||"parent"==c)||n&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||isIndex(c,l)))&&o.push(c);return o}function overArg(e,t){return function(r){return e(t(r))}}var tV=overArg(Object.keys,Object),tz=Object.prototype.hasOwnProperty;function baseKeys(e){if(!isPrototype(e))return tV(e);var t=[];for(var r in Object(e))tz.call(e,r)&&"constructor"!=r&&t.push(r);return t}function keys(e){return isArrayLike(e)?arrayLikeKeys(e):baseKeys(e)}var tj=Object.prototype.hasOwnProperty,tG=(g=function(e,t){if(isPrototype(t)||isArrayLike(t)){copyObject(t,keys(t),e);return}for(var r in t)tj.call(t,r)&&assignValue(e,r,t[r])},baseRest(function(e,t){var r=-1,i=t.length,a=i>1?t[i-1]:void 0,n=i>2?t[2]:void 0;for(a=g.length>3&&"function"==typeof a?(i--,a):void 0,n&&isIterateeCall(t[0],t[1],n)&&(a=i<3?void 0:a,i=1),e=Object(e);++r<i;){var s=t[r];s&&g(e,s,r,a)}return e})),tW=Object.prototype.hasOwnProperty;function keysIn(e){return isArrayLike(e)?arrayLikeKeys(e,!0):function(e){if(!isObject(e))return function(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}(e);var t=isPrototype(e),r=[];for(var i in e)"constructor"==i&&(t||!tW.call(e,i))||r.push(i);return r}(e)}var tH=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,tK=/^\w*$/;function isKey(e,t){if(e2(e))return!1;var r=typeof e;return!!("number"==r||"symbol"==r||"boolean"==r||null==e||isSymbol(e))||tK.test(e)||!tH.test(e)||null!=t&&e in Object(t)}var t$=getNative(Object,"create"),tY=Object.prototype.hasOwnProperty,tX=Object.prototype.hasOwnProperty;function Hash(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}function assocIndexOf(e,t){for(var r=e.length;r--;)if(eq(e[r][0],t))return r;return -1}Hash.prototype.clear=function(){this.__data__=t$?t$(null):{},this.size=0},Hash.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Hash.prototype.get=function(e){var t=this.__data__;if(t$){var r=t[e];return"__lodash_hash_undefined__"===r?void 0:r}return tY.call(t,e)?t[e]:void 0},Hash.prototype.has=function(e){var t=this.__data__;return t$?void 0!==t[e]:tX.call(t,e)},Hash.prototype.set=function(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=t$&&void 0===t?"__lodash_hash_undefined__":t,this};var tZ=Array.prototype.splice;function ListCache(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}ListCache.prototype.clear=function(){this.__data__=[],this.size=0},ListCache.prototype.delete=function(e){var t=this.__data__,r=assocIndexOf(t,e);return!(r<0)&&(r==t.length-1?t.pop():tZ.call(t,r,1),--this.size,!0)},ListCache.prototype.get=function(e){var t=this.__data__,r=assocIndexOf(t,e);return r<0?void 0:t[r][1]},ListCache.prototype.has=function(e){return assocIndexOf(this.__data__,e)>-1},ListCache.prototype.set=function(e,t){var r=this.__data__,i=assocIndexOf(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this};var tq=getNative(e$,"Map");function getMapData(e,t){var r,i=e.__data__;return("string"==(r=typeof t)||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==t:null===t)?i["string"==typeof t?"string":"hash"]:i.map}function MapCache(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}function memoize(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw TypeError("Expected a function");var memoized=function(){var r=arguments,i=t?t.apply(this,r):r[0],a=memoized.cache;if(a.has(i))return a.get(i);var n=e.apply(this,r);return memoized.cache=a.set(i,n)||a,n};return memoized.cache=new(memoize.Cache||MapCache),memoized}MapCache.prototype.clear=function(){this.size=0,this.__data__={hash:new Hash,map:new(tq||ListCache),string:new Hash}},MapCache.prototype.delete=function(e){var t=getMapData(this,e).delete(e);return this.size-=t?1:0,t},MapCache.prototype.get=function(e){return getMapData(this,e).get(e)},MapCache.prototype.has=function(e){return getMapData(this,e).has(e)},MapCache.prototype.set=function(e,t){var r=getMapData(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this},memoize.Cache=MapCache;var tQ=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,tJ=/\\(\\)?/g,t1=(y=(v=memoize(function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(tQ,function(e,r,i,a){t.push(i?a.replace(tJ,"$1"):r||e)}),t},function(e){return 500===y.size&&y.clear(),e})).cache,v);function castPath(e,t){return e2(e)?e:isKey(e,t)?[e]:t1(null==e?"":function baseToString(e){if("string"==typeof e)return e;if(e2(e))return arrayMap(e,baseToString)+"";if(isSymbol(e))return e5?e5.call(e):"";var t=e+"";return"0"==t&&1/e==-e3?"-0":t}(e))}var t0=1/0;function toKey(e){if("string"==typeof e||isSymbol(e))return e;var t=e+"";return"0"==t&&1/e==-t0?"-0":t}function baseGet(e,t){t=castPath(t,e);for(var r=0,i=t.length;null!=e&&r<i;)e=e[toKey(t[r++])];return r&&r==i?e:void 0}function arrayPush(e,t){for(var r=-1,i=t.length,a=e.length;++r<i;)e[a+r]=t[r];return e}var t2=eY?eY.isConcatSpreadable:void 0;function isFlattenable(e){return e2(e)||t_(e)||!!(t2&&e&&e[t2])}function baseFlatten(e,t,r,i,a){var n=-1,s=e.length;for(r||(r=isFlattenable),a||(a=[]);++n<s;){var o=e[n];t>0&&r(o)?t>1?baseFlatten(o,t-1,r,i,a):arrayPush(a,o):i||(a[a.length]=o)}return a}function flatten(e){return(null==e?0:e.length)?baseFlatten(e,1):[]}var t3=overArg(Object.getPrototypeOf,Object);function baseSlice(e,t,r){var i=-1,a=e.length;t<0&&(t=-t>a?0:a+t),(r=r>a?a:r)<0&&(r+=a),a=t>r?0:r-t>>>0,t>>>=0;for(var n=Array(a);++i<a;)n[i]=e[i+t];return n}
854function arrayReduce(e,t,r,i){var a=-1,n=null==e?0:e.length;for(i&&n&&(r=e[++a]);++a<n;)r=t(r,e[a],a,e);return r}function Stack(e){var t=this.__data__=new ListCache(e);this.size=t.size}Stack.prototype.clear=function(){this.__data__=new ListCache,this.size=0},Stack.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Stack.prototype.get=function(e){return this.__data__.get(e)},Stack.prototype.has=function(e){return this.__data__.has(e)},Stack.prototype.set=function(e,t){var r=this.__data__;if(r instanceof ListCache){var i=r.__data__;if(!tq||i.length<199)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new MapCache(i)}return r.set(e,t),this.size=r.size,this};var t4="object"==typeof exports&&exports&&!exports.nodeType&&exports,t5=t4&&"object"==typeof module&&module&&!module.nodeType&&module,t6=t5&&t5.exports===t4?e$.Buffer:void 0,t8=t6?t6.allocUnsafe:void 0;function arrayFilter(e,t){for(var r=-1,i=null==e?0:e.length,a=0,n=[];++r<i;){var s=e[r];t(s,r,e)&&(n[a++]=s)}return n}function stubArray(){return[]}var t9=Object.prototype.propertyIsEnumerable,t7=Object.getOwnPropertySymbols,re=t7?function(e){return null==e?[]:arrayFilter(t7(e=Object(e)),function(t){return t9.call(e,t)})}:stubArray,rt=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)arrayPush(t,re(e)),e=t3(e);return t}:stubArray;function baseGetAllKeys(e,t,r){var i=t(e);return e2(e)?i:arrayPush(i,r(e))}function getAllKeys(e){return baseGetAllKeys(e,keys,re)}function getAllKeysIn(e){return baseGetAllKeys(e,keysIn,rt)}var rr=getNative(e$,"DataView"),ri=getNative(e$,"Promise"),ra=getNative(e$,"Set"),rn="[object Map]",rs="[object Promise]",ro="[object Set]",rl="[object WeakMap]",rc="[object DataView]",ru=toSource(rr),rh=toSource(tq),rd=toSource(ri),rp=toSource(ra),rf=toSource(td),rm=baseGetTag;(rr&&rm(new rr(new ArrayBuffer(1)))!=rc||tq&&rm(new tq)!=rn||ri&&rm(ri.resolve())!=rs||ra&&rm(new ra)!=ro||td&&rm(new td)!=rl)&&(rm=function(e){var t=baseGetTag(e),r="[object Object]"==t?e.constructor:void 0,i=r?toSource(r):"";if(i)switch(i){case ru:return rc;case rh:return rn;case rd:return rs;case rp:return ro;case rf:return rl}return t});let rg=rm;var rv=Object.prototype.hasOwnProperty,ry=e$.Uint8Array;function cloneArrayBuffer(e){var t=new e.constructor(e.byteLength);return new ry(t).set(new ry(e)),t}var rT=/\w*$/,rx=eY?eY.prototype:void 0,rS=rx?rx.valueOf:void 0,rE=tF&&tF.isMap,rb=rE?baseUnary(rE):function(e){return isObjectLike(e)&&"[object Map]"==rg(e)},rR=tF&&tF.isSet,rA=rR?baseUnary(rR):function(e){return isObjectLike(e)&&"[object Set]"==rg(e)},r_="[object Arguments]",rM="[object Function]",rC="[object Object]",rw={};function clone(e){return function baseClone(e,t,r,i,a,n){var s,o=1&t,l=2&t,c=4&t;if(r&&(s=a?r(e,i,a,n):r(e)),void 0!==s)return s;if(!isObject(e))return e;var u=e2(e);if(u){if(h=e.length,d=new e.constructor(h),h&&"string"==typeof e[0]&&rv.call(e,"index")&&(d.index=e.index,d.input=e.input),s=d,!o)return function(e,t){var r=-1,i=e.length;for(t||(t=Array(i));++r<i;)t[r]=e[r];return t}(e,s)}else{var h,d,p,f,m,g,v=rg(e),y=v==rM||"[object GeneratorFunction]"==v;if(tP(e))return function(e,t){if(t)return e.slice();var r=e.length,i=t8?t8(r):new e.constructor(r);return e.copy(i),i}(e,o);if(v==rC||v==r_||y&&!a){if(s=l||y?{}:"function"!=typeof e.constructor||isPrototype(e)?{}:tf(t3(e)),!o)return l?(f=(p=s)&&copyObject(e,keysIn(e),p),copyObject(e,rt(e),f)):(g=(m=s)&&copyObject(e,keys(e),m),copyObject(e,re(e),g))}else{if(!rw[v])return a?e:{};s=function(e,t,r){var i,a,n,s=e.constructor;switch(t){case"[object ArrayBuffer]":return cloneArrayBuffer(e);case"[object Boolean]":case"[object Date]":return new s(+e);case"[object DataView]":return i=r?cloneArrayBuffer(e.buffer):e.buffer,new e.constructor(i,e.byteOffset,e.byteLength);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return a=r?cloneArrayBuffer(e.buffer):e.buffer,new e.constructor(a,e.byteOffset,e.length);case"[object Map]":case"[object Set]":return new s;case"[object Number]":case"[object String]":return new s(e);case"[object RegExp]":return(n=new e.constructor(e.source,rT.exec(e))).lastIndex=e.lastIndex,n;case"[object Symbol]":return rS?Object(rS.call(e)):{}}}(e,v,o)}}n||(n=new Stack);var T=n.get(e);if(T)return T;n.set(e,s),rA(e)?e.forEach(function(i){s.add(baseClone(i,t,r,i,e,n))}):rb(e)&&e.forEach(function(i,a){s.set(a,baseClone(i,t,r,a,e,n))});var x=c?l?getAllKeysIn:getAllKeys:l?keysIn:keys,S=u?void 0:x(e);return arrayEach(S||e,function(i,a){S&&(i=e[a=i]),assignValue(s,a,baseClone(i,t,r,a,e,n))}),s}(e,4)}function compact(e){for(var t=-1,r=null==e?0:e.length,i=0,a=[];++t<r;){var n=e[t];n&&(a[i++]=n)}return a}function SetCache(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new MapCache;++t<r;)this.add(e[t])}function arraySome(e,t){for(var r=-1,i=null==e?0:e.length;++r<i;)if(t(e[r],r,e))return!0;return!1}function cacheHas(e,t){return e.has(t)}function equalArrays(e,t,r,i,a,n){var s=1&r,o=e.length,l=t.length;if(o!=l&&!(s&&l>o))return!1;var c=n.get(e),u=n.get(t);if(c&&u)return c==t&&u==e;
854var h=-1,d=!0,p=2&r?new SetCache:void 0;for(n.set(e,t),n.set(t,e);++h<o;){var f=e[h],m=t[h];if(i)var g=s?i(m,f,h,t,e,n):i(f,m,h,e,t,n);if(void 0!==g){if(g)continue;d=!1;break}if(p){if(!arraySome(t,function(e,t){if(!cacheHas(p,t)&&(f===e||a(f,e,r,i,n)))return p.push(t)})){d=!1;break}}else if(!(f===m||a(f,m,r,i,n))){d=!1;break}}return n.delete(e),n.delete(t),d}function mapToArray(e){var t=-1,r=Array(e.size);return e.forEach(function(e,i){r[++t]=[i,e]}),r}function setToArray(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r}rw[r_]=rw["[object Array]"]=rw["[object ArrayBuffer]"]=rw["[object DataView]"]=rw["[object Boolean]"]=rw["[object Date]"]=rw["[object Float32Array]"]=rw["[object Float64Array]"]=rw["[object Int8Array]"]=rw["[object Int16Array]"]=rw["[object Int32Array]"]=rw["[object Map]"]=rw["[object Number]"]=rw[rC]=rw["[object RegExp]"]=rw["[object Set]"]=rw["[object String]"]=rw["[object Symbol]"]=rw["[object Uint8Array]"]=rw["[object Uint8ClampedArray]"]=rw["[object Uint16Array]"]=rw["[object Uint32Array]"]=!0,rw["[object Error]"]=rw[rM]=rw["[object WeakMap]"]=!1,SetCache.prototype.add=SetCache.prototype.push=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},SetCache.prototype.has=function(e){return this.__data__.has(e)};var rI=eY?eY.prototype:void 0,rP=rI?rI.valueOf:void 0,rN=Object.prototype.hasOwnProperty,rO="[object Arguments]",rL="[object Array]",rk="[object Object]",rF=Object.prototype.hasOwnProperty;function baseIsEqual(e,t,r,i,a){return e===t||(null!=e&&null!=t&&(isObjectLike(e)||isObjectLike(t))?function(e,t,r,i,a,n){var s=e2(e),o=e2(t),l=s?rL:rg(e),c=o?rL:rg(t);l=l==rO?rk:l,c=c==rO?rk:c;var u=l==rk,h=c==rk,d=l==c;if(d&&tP(e)){if(!tP(t))return!1;s=!0,u=!1}if(d&&!u)return n||(n=new Stack),s||tU(e)?equalArrays(e,t,r,i,a,n):function(e,t,r,i,a,n,s){switch(r){case"[object DataView]":if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)break;e=e.buffer,t=t.buffer;case"[object ArrayBuffer]":if(e.byteLength!=t.byteLength||!n(new ry(e),new ry(t)))break;return!0;case"[object Boolean]":case"[object Date]":case"[object Number]":return eq(+e,+t);case"[object Error]":return e.name==t.name&&e.message==t.message;case"[object RegExp]":case"[object String]":return e==t+"";case"[object Map]":var o=mapToArray;case"[object Set]":var l=1&i;if(o||(o=setToArray),e.size!=t.size&&!l)break;var c=s.get(e);if(c)return c==t;i|=2,s.set(e,t);var u=equalArrays(o(e),o(t),i,a,n,s);return s.delete(e),u;case"[object Symbol]":if(rP)return rP.call(e)==rP.call(t)}return!1}(e,t,l,r,i,a,n);if(!(1&r)){var p=u&&rF.call(e,"__wrapped__"),f=h&&rF.call(t,"__wrapped__");
854if(p||f){var m=p?e.value():e,g=f?t.value():t;return n||(n=new Stack),a(m,g,r,i,n)}}return!!d&&(n||(n=new Stack),function(e,t,r,i,a,n){var s=1&r,o=getAllKeys(e),l=o.length;if(l!=getAllKeys(t).length&&!s)return!1;for(var c=l;c--;){var u=o[c];if(!(s?u in t:rN.call(t,u)))return!1}var h=n.get(e),d=n.get(t);if(h&&d)return h==t&&d==e;var p=!0;n.set(e,t),n.set(t,e);for(var f=s;++c<l;){var m=e[u=o[c]],g=t[u];if(i)var v=s?i(g,m,u,t,e,n):i(m,g,u,e,t,n);if(!(void 0===v?m===g||a(m,g,r,i,n):v)){p=!1;break}f||(f="constructor"==u)}if(p&&!f){var y=e.constructor,T=t.constructor;y!=T&&"constructor"in e&&"constructor"in t&&!("function"==typeof y&&y instanceof y&&"function"==typeof T&&T instanceof T)&&(p=!1)}return n.delete(e),n.delete(t),p}(e,t,r,i,a,n))}(e,t,r,i,baseIsEqual,a):e!=e&&t!=t)}function matchesStrictComparable(e,t){return function(r){return null!=r&&r[e]===t&&(void 0!==t||e in Object(r))}}function baseHasIn(e,t){return null!=e&&t in Object(e)}function hasPath(e,t,r){t=castPath(t,e);for(var i=-1,a=t.length,n=!1;++i<a;){var s=toKey(t[i]);if(!(n=null!=e&&r(e,s)))break;e=e[s]}return n||++i!=a?n:!!(a=null==e?0:e.length)&&isLength(a)&&isIndex(s,a)&&(e2(e)||t_(e))}function baseIteratee(e){var t,r,i,a,n;return"function"==typeof e?e:null==e?identity:"object"==typeof e?e2(e)?(t=e[0],r=e[1],isKey(t)&&(i=r)==i&&!isObject(i)?matchesStrictComparable(toKey(t),r):function(e){var i,a=void 0===(i=null==e?void 0:baseGet(e,t))?void 0:i;return void 0===a&&a===r?null!=e&&hasPath(e,t,baseHasIn):baseIsEqual(r,a,3)}):1==(a=function(e){for(var t=keys(e),r=t.length;r--;){var i=t[r],a=e[i];t[r]=[i,a,a==a&&!isObject(a)]}return t}(e)).length&&a[0][2]?matchesStrictComparable(a[0][0],a[0][1]):function(t){return t===e||function(e,t,r,i){var a=r.length,n=a,s=!i;if(null==e)return!n;for(e=Object(e);a--;){var o=r[a];if(s&&o[2]?o[1]!==e[o[0]]:!(o[0]in e))return!1}for(;++a<n;){var l=(o=r[a])[0],c=e[l],u=o[1];if(s&&o[2]){if(void 0===c&&!(l in e))return!1}else{var h=new Stack;if(i)var d=i(c,u,l,e,t,h);if(!(void 0===d?baseIsEqual(u,c,3,i,h):d))return!1}}return!0}(t,e,a)}:isKey(e)?(n=toKey(e),function(e){return null==e?void 0:e[n]}):function(t){return baseGet(t,e)}}function arrayAggregator(e,t,r,i){for(var a=-1,n=null==e?0:e.length;++a<n;){var s=e[a];t(i,s,r(s),e)}return i}let baseFor$1=function(e,t,r){for(var i=-1,a=Object(e),n=r(e),s=n.length;s--;){var o=n[++i];if(!1===t(a[o],o,a))break}return e};var baseEach=function(e,t){if(null==e)return e;if(!isArrayLike(e))return e&&baseFor$1(e,t,keys);for(var r=e.length,i=T?r:-1,a=Object(e);(T?i--:++i<r)&&!1!==t(a[i],i,a););return e};function baseAggregator(e,t,r,i){return baseEach(e,function(e,a,n){t(i,e,r(e),n)}),i}var rD=Object.prototype,rU=rD.hasOwnProperty,rB=baseRest(function(e,t){e=Object(e);var r=-1,i=t.length,a=i>2?t[2]:void 0;for(a&&isIterateeCall(t[0],t[1],a)&&(i=1);++r<i;)for(var n=t[r],s=keysIn(n),o=-1,l=s.length;++o<l;){var c=s[o],u=e[c];(void 0===u||eq(u,rD[c])&&!rU.call(e,c))&&(e[c]=n[c])}return e});function isArrayLikeObject(e){return isObjectLike(e)&&isArrayLike(e)}function arrayIncludesWith(e,t,r){for(var i=-1,a=null==e?0:e.length;++i<a;)if(r(t,e[i]))return!0;return!1}var rV=baseRest(function(e,t){return isArrayLikeObject(e)?function(e,t,r,i){var a=-1,n=arrayIncludes,s=!0,o=e.length,l=[],c=t.length;if(!o)return l;r&&(t=arrayMap(t,baseUnary(r))),i?(n=arrayIncludesWith,s=!1):t.length>=200&&(n=cacheHas,s=!1,t=new SetCache(t));e:for(;++a<o;){var u=e[a],h=null==r?u:r(u);if(u=i||0!==u?u:0,s&&h==h){for(var d=c;d--;
854)if(t[d]===h)continue e;l.push(u)}else n(t,h,i)||l.push(u)}return l}(e,baseFlatten(t,1,isArrayLikeObject,!0)):[]});function last(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}function drop(e,t,r){var i=null==e?0:e.length;return i?baseSlice(e,(t=r||void 0===t?1:toInteger(t))<0?0:t,i):[]}function dropRight(e,t,r){var i=null==e?0:e.length;return i?baseSlice(e,0,(t=i-(t=r||void 0===t?1:toInteger(t)))<0?0:t):[]}function forEach(e,t){return(e2(e)?arrayEach:baseEach)(e,"function"==typeof t?t:identity)}function arrayEvery(e,t){for(var r=-1,i=null==e?0:e.length;++r<i;)if(!t(e[r],r,e))return!1;return!0}function baseEvery(e,t){var r=!0;return baseEach(e,function(e,i,a){return r=!!t(e,i,a)}),r}function every(e,t,r){var i=e2(e)?arrayEvery:baseEvery;return r&&isIterateeCall(e,t,r)&&(t=void 0),i(e,baseIteratee(t))}function baseFilter(e,t){var r=[];return baseEach(e,function(e,i,a){t(e,i,a)&&r.push(e)}),r}function filter(e,t){return(e2(e)?arrayFilter:baseFilter)(e,baseIteratee(t))}var rz=Math.max,rj=(x=function(e,t,r){var i=null==e?0:e.length;if(!i)return -1;var a=null==r?0:toInteger(r);return a<0&&(a=rz(i+a,0)),baseFindIndex(e,baseIteratee(t),a)},function(e,t,r){var i=Object(e);if(!isArrayLike(e)){var a=baseIteratee(t);e=keys(e),t=function(e){return a(i[e],e,i)}}var n=x(e,t,r);return n>-1?i[a?e[n]:n]:void 0});function head(e){return e&&e.length?e[0]:void 0}function map(e,t){return(e2(e)?arrayMap:function(e,t){var r=-1,i=isArrayLike(e)?Array(e.length):[];return baseEach(e,function(e,a,n){i[++r]=t(e,a,n)}),i})(e,baseIteratee(t))}function flatMap(e,t){return baseFlatten(map(e,t),1)}var rG=Object.prototype.hasOwnProperty,rW=(S=function(e,t,r){rG.call(e,r)?e[r].push(t):baseAssignValue(e,r,[t])},function(e,t){var r=e2(e)?arrayAggregator:baseAggregator,i=E?E():{};return r(e,S,baseIteratee(t),i)}),rH=Object.prototype.hasOwnProperty;function baseHas(e,t){return null!=e&&rH.call(e,t)}function has(e,t){return null!=e&&hasPath(e,t,baseHas)}function isString(e){return"string"==typeof e||!e2(e)&&isObjectLike(e)&&"[object String]"==baseGetTag(e)}function values(e){return null==e?[]:arrayMap(keys(e),function(t){return e[t]})}var rK=Math.max;function includes(e,t,r,i){e=isArrayLike(e)?e:values(e),r=r&&!i?toInteger(r):0;var a=e.length;return r<0&&(r=rK(a+r,0)),isString(e)?r<=a&&e.indexOf(t,r)>-1:!!a&&baseIndexOf(e,t,r)>-1}var r$=Math.max;function indexOf(e,t,r){var i=null==e?0:e.length;if(!i)return -1;var a=null==r?0:toInteger(r);return a<0&&(a=r$(i+a,0)),baseIndexOf(e,t,a)}var rY=Object.prototype.hasOwnProperty;function isEmpty(e){if(null==e)return!0;if(isArrayLike(e)&&(e2(e)||"string"==typeof e||"function"==typeof e.splice||tP(e)||tU(e)||t_(e)))return!e.length;var t=rg(e);if("[object Map]"==t||"[object Set]"==t)return!e.size;if(isPrototype(e))return!baseKeys(e).length;for(var r in e)if(rY.call(e,r))return!1;return!0}var rX=tF&&tF.isRegExp,rZ=rX?baseUnary(rX):function(e){return isObjectLike(e)&&"[object RegExp]"==baseGetTag(e)};function isUndefined(e){return void 0===e}function pickBy(e,t){if(null==e)return{};var r=arrayMap(getAllKeysIn(e),function(e){return[e]});return t=baseIteratee(t),function(e,t,r){for(var i=-1,a=t.length,n={};++i<a;){var s=t[i],o=baseGet(e,s);r(o,s)&&function(e,t,r,i){if(isObject(e)){t=castPath(t,e);for(var a=-1,n=t.length,s=n-1,o=e;null!=o&&++a<n;){var l=toKey(t[a]),c=r;if("__proto__"===l||"constructor"===l||"prototype"===l)break;if(a!=s){var u=o[l];void 0===(c=i?i(u,l,o):void 0)&&(c=isObject(u)?u:isIndex(t[a+1])?[]:{})}assignValue(o,l,c),o=o[l]}}}(n,castPath(s,e),o)}return n}(e,r,function(e,r){return t(e,r[0])})}function baseReduce(e,t,r,i,a){return a(e,function(e,a,n){r=i?(i=!1,e):t(r,e,a,n)}),r}function reduce(e,t,r){var i=e2(e)?arrayReduce:baseReduce,a=arguments.length<3;return i(e,baseIteratee(t),r,a,baseEach)}function reject(e,t){return(e2(e)?arrayFilter:baseFilter)(e,function(e){if("function"!=typeof e)throw TypeError("Expected a function");return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}(baseIteratee(t)))}function baseSome(e,t){var r;return baseEach(e,function(e,i,a){return!(r=t(e,i,a))}),!!r}function some(e,t,r){var i=e2(e)?arraySome:baseSome;return r&&isIterateeCall(e,t,r)&&(t=void 0),i(e,baseIteratee(t))}var rq=ra&&1/setToArray(new ra([,-0]))[1]==1/0?function(e){return new ra(e)}:noop;function uniq(e){return e&&e.length?function(e,t,r){var i=-1,a=arrayIncludes,n=e.length,s=!0,o=[],l=o;if(r)s=!1,a=arrayIncludesWith;else if(n>=200){var c=t?null:rq(e);
854if(c)return setToArray(c);s=!1,a=cacheHas,l=new SetCache}else l=t?[]:o;e:for(;++i<n;){var u=e[i],h=t?t(u):u;if(u=r||0!==u?u:0,s&&h==h){for(var d=l.length;d--;)if(l[d]===h)continue e;t&&l.push(h),o.push(u)}else a(l,h,r)||(l!==o&&l.push(h),o.push(u))}return o}(e):[]}function PRINT_ERROR(e){console&&console.error&&console.error(`Error: ${e}`)}function PRINT_WARNING(e){console&&console.warn&&console.warn(`Warning: ${e}`)}function timer(e){let t=new Date().getTime(),r=e(),i=new Date().getTime();return{time:i-t,value:r}}function toFastProperties(e){function FakeConstructor(){}FakeConstructor.prototype=e;let t=new FakeConstructor;function fakeAccess(){return typeof t.bar}return fakeAccess(),fakeAccess(),e}let AbstractProduction=class AbstractProduction{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){this._definition=e}accept(e){e.visit(this),forEach(this.definition,t=>{t.accept(e)})}};let NonTerminal=class NonTerminal extends AbstractProduction{constructor(e){super([]),this.idx=1,tG(this,pickBy(e,e=>void 0!==e))}set definition(e){}get definition(){return void 0!==this.referencedRule?this.referencedRule.definition:[]}accept(e){e.visit(this)}};let Rule=class Rule extends AbstractProduction{constructor(e){super(e.definition),this.orgText="",tG(this,pickBy(e,e=>void 0!==e))}};let Alternative=class Alternative extends AbstractProduction{constructor(e){super(e.definition),this.ignoreAmbiguities=!1,tG(this,pickBy(e,e=>void 0!==e))}};let Option=class Option extends AbstractProduction{constructor(e){super(e.definition),this.idx=1,tG(this,pickBy(e,e=>void 0!==e))}};let RepetitionMandatory=class RepetitionMandatory extends AbstractProduction{constructor(e){super(e.definition),this.idx=1,tG(this,pickBy(e,e=>void 0!==e))}};let RepetitionMandatoryWithSeparator=class RepetitionMandatoryWithSeparator extends AbstractProduction{constructor(e){super(e.definition),this.idx=1,tG(this,pickBy(e,e=>void 0!==e))}};let Repetition=class Repetition extends AbstractProduction{constructor(e){super(e.definition),this.idx=1,tG(this,pickBy(e,e=>void 0!==e))}};let RepetitionWithSeparator=class RepetitionWithSeparator extends AbstractProduction{constructor(e){super(e.definition),this.idx=1,tG(this,pickBy(e,e=>void 0!==e))}};let Alternation=class Alternation extends AbstractProduction{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,tG(this,pickBy(e,e=>void 0!==e))}};let Terminal=class Terminal{constructor(e){this.idx=1,tG(this,pickBy(e,e=>void 0!==e))}accept(e){e.visit(this)}};let GAstVisitor=class GAstVisitor{visit(e){switch(e.constructor){case NonTerminal:return this.visitNonTerminal(e);case Alternative:return this.visitAlternative(e);case Option:return this.visitOption(e);case RepetitionMandatory:return this.visitRepetitionMandatory(e);case RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(e);case RepetitionWithSeparator:return this.visitRepetitionWithSeparator(e);case Repetition:return this.visitRepetition(e);case Alternation:return this.visitAlternation(e);case Terminal:return this.visitTerminal(e);case Rule:return this.visitRule(e);default:throw Error("non exhaustive match")}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}};function isOptionalProd(e,t=[]){let r=e instanceof Option||e instanceof Repetition||e instanceof RepetitionWithSeparator;return!!r||(e instanceof Alternation?some(e.definition,e=>isOptionalProd(e,t)):!(e instanceof NonTerminal&&includes(t,e))&&e instanceof AbstractProduction&&(e instanceof NonTerminal&&t.push(e),every(e.definition,e=>isOptionalProd(e,t))))}function getProductionDslName(e){if(e instanceof NonTerminal)return"SUBRULE";if(e instanceof Option)return"OPTION";if(e instanceof Alternation)return"OR";if(e instanceof RepetitionMandatory)return"AT_LEAST_ONE";if(e instanceof RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(e instanceof RepetitionWithSeparator)return"MANY_SEP";if(e instanceof Repetition)return"MANY";else if(e instanceof Terminal)return"CONSUME";else throw Error("non exhaustive match")}let RestWalker=class RestWalker{walk(e,t=[]){forEach(e.definition,(r,i)=>{let a=drop(e.definition,i+1);if(r instanceof NonTerminal)this.walkProdRef(r,a,t);else if(r instanceof Terminal)this.walkTerminal(r,a,t);else if(r instanceof Alternative)this.walkFlat(r,a,t);else if(r instanceof Option)this.walkOption(r,a,t);else if(r instanceof RepetitionMandatory)this.walkAtLeastOne(r,a,t);else if(r instanceof RepetitionMandatoryWithSeparator)this.walkAtLeastOneSep(r,a,t);else if(r instanceof RepetitionWithSeparator)this.walkManySep(r,a,t);else if(r instanceof Repetition)this.walkMany(r,a,t);else if(r instanceof Alternation)this.walkOr(r,a,t);else throw Error("non exhaustive match")})}walkTerminal(e,t,r){}walkProdRef(e,t,r){}walkFlat(e,t,r){let i=t.concat(r);this.walk(e,i)}walkOption(e,t,r){let i=t.concat(r);this.walk(e,i)}walkAtLeastOne(e,t,r){let i=[new Option({definition:e.definition})].concat(t,r);this.walk(e,i)}walkAtLeastOneSep(e,t,r){let i=restForRepetitionWithSeparator(e,t,r);this.walk(e,i)}walkMany(e,t,r){let i=[new Option({definition:e.definition})].concat(t,r);this.walk(e,i)}walkManySep(e,t,r){let i=restForRepetitionWithSeparator(e,t,r);this.walk(e,i)}walkOr(e,t,r){let i=t.concat(r);forEach(e.definition,e=>{let t=new Alternative({definition:[e]});this.walk(t,i)})}};function restForRepetitionWithSeparator(e,t,r){let i=[new Option({definition:[new Terminal({terminalType:e.separator})].concat(e.definition)})],a=i.concat(t,r);return a}function first(e){if(e instanceof NonTerminal)return first(e.referencedRule);if(e instanceof Terminal)return[e.terminalType];if(e instanceof Alternative||e instanceof Option||e instanceof Repetition||e instanceof RepetitionMandatory||e instanceof RepetitionMandatoryWithSeparator||e instanceof RepetitionWithSeparator||e instanceof Terminal||e instanceof Rule)return function(e){let t,r=[],i=e.definition,a=0,n=i.length>a,s=!0;for(;n&&s;)s=isOptionalProd(t=i[a]),r=r.concat(first(t)),a+=1,n=i.length>a;return uniq(r)}(e);if(e instanceof Alternation)return function(e){let t=map(e.definition,e=>first(e));return uniq(flatten(t))}(e);throw Error("non exhaustive match")}let rQ="_~IN~_";let ResyncFollowsWalker=class ResyncFollowsWalker extends RestWalker{constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,t,r){}walkProdRef(e,t,r){var i,a;let n=(i=e.referencedRule,a=e.idx,i.name+a+rQ+this.topProd.name),s=t.concat(r),o=new Alternative({definition:s}),l=first(o);this.follows[n]=l}};function cc(e){return e.charCodeAt(0)}function insertToSet(e,t){Array.isArray(e)?e.forEach(function(e){t.push(e)}):t.push(e)}function addFlag(e,t){if(!0===e[t])throw"duplicate flag "+t;e[t],e[t]=!0}
854function ASSERT_EXISTS(e){if(void 0===e)throw Error("Internal Error - Should never get here!");return!0}function isCharacter(e){return"Character"===e.type}let rJ=[];for(let e=cc("0");e<=cc("9");e++)rJ.push(e);let r1=[cc("_")].concat(rJ);for(let e=cc("a");e<=cc("z");e++)r1.push(e);for(let e=cc("A");e<=cc("Z");e++)r1.push(e);let r0=[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("\uFEFF")],r2=/[0-9a-fA-F]/,r3=/[0-9]/,r4=/[1-9]/;let BaseRegExpVisitor=class BaseRegExpVisitor{visitChildren(e){for(let t in e){let r=e[t];e.hasOwnProperty(t)&&(void 0!==r.type?this.visit(r):Array.isArray(r)&&r.forEach(e=>{this.visit(e)},this))}}visit(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e)}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}};let r5={},r6=new class{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar("/");let t=this.disjunction();this.consumeChar("/");let r={type:"Flags",loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":addFlag(r,"global");break;case"i":addFlag(r,"ignoreCase");break;case"m":addFlag(r,"multiLine");break;case"u":addFlag(r,"unicode");break;case"y":addFlag(r,"sticky")}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:t,loc:this.loc(0)}}disjunction(){let e=[],t=this.idx;for(e.push(this.alternative());"|"===this.peekChar();)this.consumeChar("|"),e.push(this.alternative());return{type:"Disjunction",value:e,loc:this.loc(t)}}alternative(){let e=[],t=this.idx;for(;this.isTerm();)e.push(this.term());return{type:"Alternative",value:e,loc:this.loc(t)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){let e=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(e)};case"$":return{type:"EndAnchor",loc:this.loc(e)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(e)};case"B":return{type:"NonWordBoundary",loc:this.loc(e)}}throw Error("Invalid Assertion Escape");case"(":let t;switch(this.consumeChar("?"),this.popChar()){case"=":t="Lookahead";break;case"!":t="NegativeLookahead"}ASSERT_EXISTS(t);let r=this.disjunction();return this.consumeChar(")"),{type:t,value:r,loc:this.loc(e)}}return function(){throw Error("Internal Error - Should never get here!")}()}quantifier(e=!1){let t;let r=this.idx;switch(this.popChar()){case"*":t={atLeast:0,atMost:1/0};break;case"+":t={atLeast:1,atMost:1/0};break;case"?":t={atLeast:0,atMost:1};break;case"{":let i=this.integerIncludingZero();switch(this.popChar()){case"}":t={atLeast:i,atMost:i};break;case",":t=this.isDigit()?{atLeast:i,atMost:this.integerIncludingZero()}:{atLeast:i,atMost:1/0},this.consumeChar("}")}if(!0===e&&void 0===t)return;ASSERT_EXISTS(t)}if((!0!==e||void 0!==t)&&ASSERT_EXISTS(t))return"?"===this.peekChar(0)?(this.consumeChar("?"),t.greedy=!1):t.greedy=!0,t.type="Quantifier",t.loc=this.loc(r),t}atom(){let e;let t=this.idx;switch(this.peekChar()){case".":e=this.dotAll();break;case"\\":e=this.atomEscape();break;case"[":e=this.characterClass();break;case"(":e=this.group()}if(void 0===e&&this.isPatternCharacter()&&(e=this.patternCharacter()),ASSERT_EXISTS(e))return e.loc=this.loc(t),this.isQuantifier()&&(e.quantifier=this.quantifier()),e}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[cc("\n"),cc("\r"),cc("\u2028"),cc("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();
854case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){let e=this.positiveInteger();return{type:"GroupBackReference",value:e}}characterClassEscape(){let e;let t=!1;switch(this.popChar()){case"d":e=rJ;break;case"D":e=rJ,t=!0;break;case"s":e=r0;break;case"S":e=r0,t=!0;break;case"w":e=r1;break;case"W":e=r1,t=!0}if(ASSERT_EXISTS(e))return{type:"Set",value:e,complement:t}}controlEscapeAtom(){let e;switch(this.popChar()){case"f":e=cc("\f");break;case"n":e=cc("\n");break;case"r":e=cc("\r");break;case"t":e=cc("	");break;case"v":e=cc("\v")}if(ASSERT_EXISTS(e))return{type:"Character",value:e}}controlLetterEscapeAtom(){this.consumeChar("c");let e=this.popChar();if(!1===/[a-zA-Z]/.test(e))throw Error("Invalid ");let t=e.toUpperCase().charCodeAt(0)-64;return{type:"Character",value:t}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:cc("\x00")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){let e=this.popChar();return{type:"Character",value:cc(e)}}classPatternCharacterAtom(){switch(this.peekChar()){case"\n":case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:let e=this.popChar();return{type:"Character",value:cc(e)}}}characterClass(){let e=[],t=!1;for(this.consumeChar("["),"^"===this.peekChar(0)&&(this.consumeChar("^"),t=!0);this.isClassAtom();){let t=this.classAtom();if(t.type,isCharacter(t)&&this.isRangeDash()){this.consumeChar("-");let r=this.classAtom();if(r.type,isCharacter(r)){if(r.value<t.value)throw Error("Range out of order in character class");e.push({from:t.value,to:r.value})}else insertToSet(t.value,e),e.push(cc("-")),insertToSet(r.value,e)}else insertToSet(t.value,e)}return this.consumeChar("]"),{type:"Set",complement:t,value:e}}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(){switch(this.consumeChar("\\"),this.peekChar()){case"b":return this.consumeChar("b"),{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 e=!0;(this.consumeChar("("),"?"===this.peekChar(0))?(this.consumeChar("?"),this.consumeChar(":"),e=!1):this.groupIdx++;let t=this.disjunction();this.consumeChar(")");let r={type:"Group",capturing:e,value:t};return e&&(r.idx=this.groupIdx),r}positiveInteger(){let e=this.popChar();if(!1===r4.test(e))throw Error("Expecting a positive integer");for(;r3.test(this.peekChar(0));)e+=this.popChar();return parseInt(e,10)}integerIncludingZero(){let e=this.popChar();if(!1===r3.test(e))throw Error("Expecting an integer");for(;r3.test(this.peekChar(0));)e+=this.popChar();return parseInt(e,10)}patternCharacter(){let e=this.popChar();switch(e){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(e)}}}isRegExpFlag(){switch(this.peekChar(0)){case"g":case"i":case"m":case"u":case"y":return!0;default:return!1}}isRangeDash(){return"-"===this.peekChar()&&this.isClassAtom(1)}isDigit(){return r3.test(this.peekChar(0))}isClassAtom(e=0){switch(this.peekChar(e)){case"]":case"\n":case"\r":case"\u2028":case"\u2029":return!1;default:return!0}}isTerm(){return this.isAtom()||this.isAssertion()}isAtom(){if(this.isPatternCharacter())return!0;switch(this.peekChar(0)){case".":case"\\":case"[":case"(":return!0;default:return!1}}isAssertion(){switch(this.peekChar(0)){case"^":case"$":return!0;case"\\":switch(this.peekChar(1)){case"b":case"B":return!0;default:return!1}case"(":return"?"===this.peekChar(1)&&("="===this.peekChar(2)||"!"===this.peekChar(2));default:return!1}}isQuantifier(){let e=this.saveState();try{return void 0!==this.quantifier(!0)}catch(e){return!1}finally{this.restoreState(e)}}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!1;default:return!0}}parseHexDigits(e){let t="";for(let r=0;r<e;r++){let e=this.popChar();if(!1===r2.test(e))throw Error("Expecting a HexDecimal digits");t+=e}let r=parseInt(t,16);return{type:"Character",value:r}}peekChar(e=0){return this.input[this.idx+e]}popChar(){let e=this.peekChar(0);return this.consumeChar(void 0),e}consumeChar(e){if(void 0!==e&&this.input[this.idx]!==e)throw Error("Expected: '"+e+"' 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(e){return{begin:e,end:this.idx}}};function getRegExpAst(e){let t=e.toString();if(r5.hasOwnProperty(t))return r5[t];{let e=r6.pattern(t);return r5[t]=e,e}}let r8="Complement Sets are not supported for first char optimization",r9='Unable to use "first char" lexer optimizations:\n';function addOptimizedIdxToResult(e,t,r){let i=charCodeToOptimizedIndex(e);t[i]=i,!0===r&&function(e,t){let r=String.fromCharCode(e),i=r.toUpperCase();
854if(i!==r){let e=charCodeToOptimizedIndex(i.charCodeAt(0));t[e]=e}else{let e=r.toLowerCase();if(e!==r){let r=charCodeToOptimizedIndex(e.charCodeAt(0));t[r]=r}}}(e,t)}function findCode(e,t){return rj(e.value,e=>"number"==typeof e?includes(t,e):void 0!==rj(t,t=>e.from<=t&&t<=e.to))}let CharCodeFinder=class CharCodeFinder extends BaseRegExpVisitor{constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(!0!==this.found){switch(e.type){case"Lookahead":this.visitLookahead(e);return;case"NegativeLookahead":this.visitNegativeLookahead(e);return}super.visitChildren(e)}}visitCharacter(e){includes(this.targetCharCodes,e.value)&&(this.found=!0)}visitSet(e){e.complement?void 0===findCode(e,this.targetCharCodes)&&(this.found=!0):void 0!==findCode(e,this.targetCharCodes)&&(this.found=!0)}};function canMatchCharCode(e,t){if(!(t instanceof RegExp))return void 0!==rj(t,t=>includes(e,t.charCodeAt(0)));{let r=getRegExpAst(t),i=new CharCodeFinder(e);return i.visit(r),i.found}}let r7="PATTERN",ie="defaultMode",it="modes",ir="boolean"==typeof RegExp("(?:)").sticky,ii=/[^\\][$]/,ia=/[^\\[][\^]|^\^/;function addStartOfInput(e){let t=e.ignoreCase?"i":"";return RegExp(`^(?:${e.source})`,t)}function addStickyFlag(e){let t=e.ignoreCase?"iy":"y";return RegExp(`${e.source}`,t)}function isCustomPattern(e){let t=e.PATTERN;if(rZ(t))return!1;if(isFunction(t)||has(t,"exec"))return!0;if(isString(t))return!1;throw Error("non exhaustive match")}function isShortPattern(e){return!!isString(e)&&1===e.length&&e.charCodeAt(0)}let is={test:function(e){let t=e.length;for(let r=this.lastIndex;r<t;r++){let t=e.charCodeAt(r);if(10===t)return this.lastIndex=r+1,!0;if(13===t)return 10===e.charCodeAt(r+1)?this.lastIndex=r+2:this.lastIndex=r+1,!0}return!1},lastIndex:0};function checkLineBreaksIssues(e,t){if(has(e,"LINE_BREAKS"))return!1;if(rZ(e.PATTERN)){try{canMatchCharCode(t,e.PATTERN)}catch(e){return{issue:M.IDENTIFY_TERMINATOR,errMsg:e.message}}return!1}if(isString(e.PATTERN))return!1;if(isCustomPattern(e))return{issue:M.CUSTOM_LINE_BREAK};throw Error("non exhaustive match")}function getCharCodes(e){let t=map(e,e=>isString(e)?e.charCodeAt(0):e);return t}function addToMapOfArrays(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}let io=[];function charCodeToOptimizedIndex(e){return e<256?e:io[e]}function tokenStructuredMatcher(e,t){let r=e.tokenTypeIdx;return r===t.tokenTypeIdx||!0===t.isParent&&!0===t.categoryMatchesMap[r]}function tokenStructuredMatcherNoCategories(e,t){return e.tokenTypeIdx===t.tokenTypeIdx}let il=1,ic={};function augmentTokenTypes(e){let t=function(e){let t=clone(e),r=e,i=!0;for(;i;){r=compact(flatten(map(r,e=>e.CATEGORIES)));let e=rV(r,t);t=t.concat(e),isEmpty(e)?i=!1:r=e}return t}(e);forEach(t,e=>{hasShortKeyProperty(e)||(ic[il]=e,e.tokenTypeIdx=il++),hasCategoriesProperty(e)&&!e2(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),hasCategoriesProperty(e)||(e.CATEGORIES=[]),has(e,"categoryMatches")||(e.categoryMatches=[]),has(e,"categoryMatchesMap")||(e.categoryMatchesMap={})}),forEach(t,e=>{(function singleAssignCategoriesToksMap(e,t){forEach(e,e=>{t.categoryMatchesMap[e.tokenTypeIdx]=!0}
854),forEach(t.CATEGORIES,r=>{let i=e.concat(t);includes(i,r)||singleAssignCategoriesToksMap(i,r)})})([],e)}),forEach(t,e=>{e.categoryMatches=[],forEach(e.categoryMatchesMap,(t,r)=>{e.categoryMatches.push(ic[r].tokenTypeIdx)})}),forEach(t,e=>{e.isParent=e.categoryMatches.length>0})}function hasShortKeyProperty(e){return has(e,"tokenTypeIdx")}function hasCategoriesProperty(e){return has(e,"CATEGORIES")}function isTokenType(e){return has(e,"tokenTypeIdx")}(b=M||(M={}))[b.MISSING_PATTERN=0]="MISSING_PATTERN",b[b.INVALID_PATTERN=1]="INVALID_PATTERN",b[b.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",b[b.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",b[b.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",b[b.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",b[b.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",b[b.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",b[b.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",b[b.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",b[b.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",b[b.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",b[b.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",b[b.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",b[b.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",b[b.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",b[b.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",b[b.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE";let iu={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:["\n","\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:{buildUnableToPopLexerModeMessage:e=>`Unable to pop Lexer Mode after encountering Token ->${e.image}<- The Mode Stack is empty`,buildUnexpectedCharactersMessage:(e,t,r,i,a)=>`unexpected character: ->${e.charAt(t)}<- at offset: ${t}, skipped ${r} characters.`},traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(iu);let Lexer=class Lexer{constructor(e,t=iu){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(e,t)=>{if(!0!==this.traceInitPerf)return t();{this.traceInitIndent++;let r=Array(this.traceInitIndent+1).join("	");this.traceInitIndent<this.traceInitMaxIdent&&console.log(`${r}--> <${e}>`);let{time:i,value:a}=timer(t),n=i>10?console.warn:console.log;return this.traceInitIndent<this.traceInitMaxIdent&&n(`${r}<-- <${e}> time: ${i}ms`),this.traceInitIndent--,a}},"boolean"==typeof t)throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\na boolean 2nd argument is no longer supported");this.config=tG({},iu,t);let r=this.config.traceInitPerf;!0===r?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):"number"==typeof r&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let r;let i=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===iu.lineTerminatorsPattern)this.config.lineTerminatorsPattern=is;else if(this.config.lineTerminatorCharacters===iu.lineTerminatorCharacters)throw Error("Error: Missing <lineTerminatorCharacters> property on the Lexer config.\n	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS");if(t.safeMode&&t.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),e2(e)?r={modes:{defaultMode:clone(e)},defaultMode:ie}:(i=!1,r=clone(e))}),!1===this.config.skipValidations&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(function(e,t,r){let i=[];return has(e,ie)||i.push({message:"A MultiMode Lexer cannot be initialized without a <"+ie+"> property in its definition\n",type:M.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),has(e,it)||i.push({message:"A MultiMode Lexer cannot be initialized without a <"+it+"> property in its definition\n",type:M.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),has(e,it)&&has(e,ie)&&!has(e.modes,e.defaultMode)&&i.push({message:`A MultiMode Lexer cannot be initialized with a ${ie}: <${e.defaultMode}>which does not exist
855`,type:M.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),has(e,it)&&forEach(e.modes,(e,t)=>{forEach(e,(r,a)=>{if(isUndefined(r))i.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${t}> at index: <${a}>
856`,type:M.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if(has(r,"LONGER_ALT")){let a=e2(r.LONGER_ALT)?r.LONGER_ALT:[r.LONGER_ALT];forEach(a,a=>{isUndefined(a)||includes(e,a)||i.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${a.name}> on token <${r.name}> outside of mode <${t}>
857`,type:M.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),i}(r,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(function(e,t,r){let i=[],a=!1,n=compact(flatten(values(e.modes))),s=reject(n,e=>e[r7]===Lexer.NA),o=getCharCodes(r);
857return t&&forEach(s,e=>{let t=checkLineBreaksIssues(e,o);if(!1!==t){let r=function(e,t){if(t.issue===M.IDENTIFY_TERMINATOR)return`Warning: unable to identify line terminator usage in pattern.
858	The problem is in the <${e.name}> Token Type
859	 Root cause: ${t.errMsg}.
860	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(t.issue===M.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the <line_breaks> option.
861	The problem is in the <${e.name}> Token Type
862	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}(e,t),a={message:r,type:t.issue,tokenType:e};i.push(a)}else has(e,"LINE_BREAKS")?!0===e.LINE_BREAKS&&(a=!0):canMatchCharCode(o,e.PATTERN)&&(a=!0)}),t&&!a&&i.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:M.NO_LINE_BREAKS_FLAGS}),i}(r,this.trackStartLines,this.config.lineTerminatorCharacters))}
862)),r.modes=r.modes?r.modes:{},forEach(r.modes,(e,t)=>{r.modes[t]=reject(e,e=>isUndefined(e))});let a=keys(r.modes);if(forEach(r.modes,(e,r)=>{this.TRACE_INIT(`Mode: <${r}> processing`,()=>{if(this.modes.push(r),!1===this.config.skipValidations&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(function(e,t){let r=[],i=function(e){let t=filter(e,e=>!has(e,r7)),r=map(t,e=>({message:"Token Type: ->"+e.name+"<- missing static 'PATTERN' property",type:M.MISSING_PATTERN,tokenTypes:[e]})),i=rV(e,t);return{errors:r,valid:i}}(e);r=r.concat(i.errors);let a=function(e){let t=filter(e,e=>{let t=e[r7];return!rZ(t)&&!isFunction(t)&&!has(t,"exec")&&!isString(t)}),r=map(t,e=>({message:"Token Type: ->"+e.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:M.INVALID_PATTERN,tokenTypes:[e]})),i=rV(e,t);return{errors:r,valid:i}}(i.valid),n=a.valid;return(r=(r=(r=(r=r.concat(a.errors)).concat(function(e){let t=[],r=filter(e,e=>rZ(e[r7]));return(t=(t=(t=(t=t.concat(function(e){let EndAnchorFinder=class EndAnchorFinder extends BaseRegExpVisitor{constructor(){super(...arguments),this.found=!1}visitEndAnchor(e){this.found=!0}};let t=filter(e,e=>{let t=e.PATTERN;try{let e=getRegExpAst(t),r=new EndAnchorFinder;return r.visit(e),r.found}catch(e){return ii.test(t.source)}}),r=map(t,e=>({message:"Unexpected RegExp Anchor Error:\n	Token Type: ->"+e.name+"<- static 'PATTERN' cannot contain end of input anchor '$'\n	See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.",type:M.EOI_ANCHOR_FOUND,tokenTypes:[e]}));return r}(r))).concat(function(e){let StartAnchorFinder=class StartAnchorFinder extends BaseRegExpVisitor{constructor(){super(...arguments),this.found=!1}visitStartAnchor(e){this.found=!0}};let t=filter(e,e=>{let t=e.PATTERN;try{let e=getRegExpAst(t),r=new StartAnchorFinder;return r.visit(e),r.found}catch(e){return ia.test(t.source)}}),r=map(t,e=>({message:"Unexpected RegExp Anchor Error:\n	Token Type: ->"+e.name+"<- static 'PATTERN' cannot contain start of input anchor '^'\n	See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.",type:M.SOI_ANCHOR_FOUND,tokenTypes:[e]}));return r}(r))).concat(function(e){let t=filter(e,e=>{let t=e[r7];return t instanceof RegExp&&(t.multiline||t.global)}),r=map(t,e=>({message:"Token Type: ->"+e.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:M.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[e]}));return r}(r))).concat(function(e){let t=[],r=map(e,r=>reduce(e,(e,i)=>(r.PATTERN.source!==i.PATTERN.source||includes(t,i)||i.PATTERN===Lexer.NA||(t.push(i),e.push(i)),e),[]));r=compact(r);let i=filter(r,e=>e.length>1),a=map(i,e=>{let t=map(e,e=>e.name),r=head(e).PATTERN;return{message:`The same RegExp pattern ->${r}<-has been used in all of the following Token Types: ${t.join(", ")} <-`,type:M.DUPLICATE_PATTERNS_FOUND,tokenTypes:e}});return a}(r))).concat(function(e){let t=filter(e,e=>{let t=e.PATTERN;return t.test("")}),r=map(t,e=>({message:"Token Type: ->"+e.name+"<- static 'PATTERN' must not match an empty string",type:M.EMPTY_MATCH_PATTERN,tokenTypes:[e]}));return r}(r))}(n))).concat(function(e){let t=filter(e,e=>{if(!has(e,"GROUP"))return!1;let t=e.GROUP;return t!==Lexer.SKIPPED&&t!==Lexer.NA&&!isString(t)}),r=map(t,e=>({message:"Token Type: ->"+e.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:M.INVALID_GROUP_TYPE_FOUND,tokenTypes:[e]}));return r}(n))).concat(function(e,t){let r=filter(e,e=>void 0!==e.PUSH_MODE&&!includes(t,e.PUSH_MODE)),i=map(r,e=>{let t=`Token Type: ->${e.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${e.PUSH_MODE}<-which does not exist`;return{message:t,type:M.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[e]}});return i}(n,t))).concat(function(e){let t=[],r=reduce(e,(e,t,r)=>{let i=t.PATTERN;return i===Lexer.NA||(isString(i)?e.push({str:i,idx:r,tokenType:t}):rZ(i)&&void 0===rj([".","\\","[","]","|","^","$","(",")","?","*","+","{"],e=>-1!==i.source.indexOf(e))&&e.push({str:i.source,idx:r,tokenType:t})),e},[]);return forEach(e,(e,i)=>
862{forEach(r,({str:r,idx:a,tokenType:n})=>{if(i<a&&function(e,t){if(rZ(t)){let r=t.exec(e);return null!==r&&0===r.index}if(isFunction(t))return t(e,0,[],{});if(has(t,"exec"))return t.exec(e,0,[],{});if("string"==typeof t)return t===e;throw Error("non exhaustive match")}(r,e.PATTERN)){let r=`Token: ->${n.name}<- can never be matched.
863Because it appears AFTER the Token Type ->${e.name}<-in the lexer's definition.
864See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;t.push({message:r,type:M.UNREACHABLE_PATTERN,tokenTypes:[e,n]})}})}),t}(n))}(e,a))}),isEmpty(this.lexerDefinitionErrors)){let i;augmentTokenTypes(e),this.TRACE_INIT("analyzeTokenTypes",()=>{i=function(e,t){let r,i,a,n,s,o,l,c,u,h,d,p;t=rB(t,{useSticky:ir,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r","\n"],tracer:(e,t)=>t()});let f=t.tracer;f("initCharCodeToOptimizedIndexMap",()=>{(function(){if(isEmpty(io)){io=Array(65536);for(let e=0;e<65536;e++)io[e]=e>255?255+~~(e/255):e}})()}),f("Reject Lexer.NA",()=>{r=reject(e,e=>e[r7]===Lexer.NA)});let m=!1;f("Transform Patterns",()=>{m=!1,i=map(r,e=>{let r=e[r7];if(rZ(r)){let e=r.source;return 1!==e.length||"^"===e||"$"===e||"."===e||r.ignoreCase?2!==e.length||"\\"!==e[0]||includes(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],e[1])?t.useSticky?addStickyFlag(r):addStartOfInput(r):e[1]:e}if(isFunction(r))return m=!0,{exec:r};if("object"==typeof r)return m=!0,r;if("string"==typeof r){if(1===r.length)return r;{let e=r.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),i=new RegExp(e);return t.useSticky?addStickyFlag(i):addStartOfInput(i)}}throw Error("non exhaustive match")})}),f("misc mapping",()=>{a=map(r,e=>e.tokenTypeIdx),n=map(r,e=>{let t=e.GROUP;if(t!==Lexer.SKIPPED){if(isString(t))return t;if(isUndefined(t))return!1;throw Error("non exhaustive match")}}),s=map(r,e=>{let t=e.LONGER_ALT;if(t){let e=e2(t)?map(t,e=>indexOf(r,e)):[indexOf(r,t)];return e}}),o=map(r,e=>e.PUSH_MODE),l=map(r,e=>has(e,"POP_MODE"))}),f("Line Terminator Handling",()=>{let e=getCharCodes(t.lineTerminatorCharacters);c=map(r,e=>!1),"onlyOffset"!==t.positionTracking&&(c=map(r,t=>has(t,"LINE_BREAKS")?!!t.LINE_BREAKS:!1===checkLineBreaksIssues(t,e)&&canMatchCharCode(e,t.PATTERN)))}),f("Misc Mapping #2",()=>{u=map(r,isCustomPattern),h=map(i,isShortPattern),d=reduce(r,(e,t)=>{let r=t.GROUP;return isString(r)&&r!==Lexer.SKIPPED&&(e[r]=[]),e},{}),p=map(i,(e,t)=>({pattern:i[t],longerAlt:s[t],canLineTerminator:c[t],isCustom:u[t],short:h[t],group:n[t],push:o[t],pop:l[t],tokenTypeIdx:a[t],tokenType:r[t]}))});let g=!0,v=[];return t.safeMode||f("First Char Optimization",()=>{v=reduce(r,(e,r,i)=>{if("string"==typeof r.PATTERN){let t=r.PATTERN.charCodeAt(0),a=charCodeToOptimizedIndex(t);addToMapOfArrays(e,a,p[i])}else if(e2(r.START_CHARS_HINT)){let t;forEach(r.START_CHARS_HINT,r=>{let a="string"==typeof r?r.charCodeAt(0):r,n=charCodeToOptimizedIndex(a);t!==n&&(t=n,addToMapOfArrays(e,n,p[i]))})}else if(rZ(r.PATTERN)){if(r.PATTERN.unicode)g=!1,t.ensureOptimizations&&PRINT_ERROR(`${r9}	Unable to analyze < ${r.PATTERN.toString()} > pattern.
865	The regexp unicode flag is not currently supported by the regexp-to-ast library.
866	This will disable the lexer's first char optimizations.
867	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{let a=function(e,t=!1){try{let t=getRegExpAst(e),r=function firstCharOptimizedIndices(e,t,r){switch(e.type){case"Disjunction":for(let i=0;i<e.value.length;i++)firstCharOptimizedIndices(e.value[i],t,r);break;case"Alternative":let i=e.value;for(let e=0;e<i.length;e++){let a=i[e];switch(a.type){case"EndAnchor":case"GroupBackReference":case"Lookahead":case"NegativeLookahead":case"StartAnchor":case"WordBoundary":case"NonWordBoundary":continue}switch(a.type){case"Character":addOptimizedIdxToResult(a.value,t,r);break;case"Set":if(!0===a.complement)throw Error(r8);forEach(a.value,e=>{if("number"==typeof e)addOptimizedIdxToResult(e,t,r);else if(!0===r)for(let i=e.from;i<=e.to;i++)addOptimizedIdxToResult(i,t,r);else{for(let i=e.from;i<=e.to&&i<256;i++)addOptimizedIdxToResult(i,t,r);if(e.to>=256){let r=e.from>=256?e.from:256,i=e.to,a=charCodeToOptimizedIndex(r),n=charCodeToOptimizedIndex(i);for(let e=a;
867e<=n;e++)t[e]=e}}});break;case"Group":firstCharOptimizedIndices(a.value,t,r);break;default:throw Error("Non Exhaustive Match")}let n=void 0!==a.quantifier&&0===a.quantifier.atLeast;if("Group"===a.type&&!1===function isWholeOptional(e){let t=e.quantifier;return!!t&&0===t.atLeast||!!e.value&&(e2(e.value)?every(e.value,isWholeOptional):isWholeOptional(e.value))}(a)||"Group"!==a.type&&!1===n)break}break;default:throw Error("non exhaustive match!")}return values(t)}(t.value,{},t.flags.ignoreCase);return r}catch(r){if(r.message===r8)t&&PRINT_WARNING(`${r9}	Unable to optimize: < ${e.toString()} >
868	Complement Sets cannot be automatically optimized.
869	This will disable the lexer's first char optimizations.
870	See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let r="";t&&(r="\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(`${r9}
871	Failed parsing: < ${e.toString()} >
872	Using the @chevrotain/regexp-to-ast library
873	Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}(r.PATTERN,t.ensureOptimizations);isEmpty(a)&&(g=!1),forEach(a,t=>{addToMapOfArrays(e,t,p[i])})}}else t.ensureOptimizations&&PRINT_ERROR(`${r9}	TokenType: <${r.name}> is using a custom token pattern without providing <start_chars_hint> parameter.
874	This will disable the lexer's first char optimizations.
875	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),g=!1;return e},[])}),{emptyGroups:d,patternIdxToConfig:p,charCodeToPatternIdxToConfig:v,hasCustom:m,canBeOptimized:g}}(e,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:t.positionTracking,ensureOptimizations:t.ensureOptimizations,safeMode:t.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[r]=i.patternIdxToConfig,this.charCodeToPatternIdxToConfig[r]=i.charCodeToPatternIdxToConfig,this.emptyGroups=tG({},this.emptyGroups,i.emptyGroups),this.hasCustom=i.hasCustom||this.hasCustom,this.canModeBeOptimized[r]=i.canBeOptimized}})}),this.defaultMode=r.defaultMode,!isEmpty(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){let e=map(this.lexerDefinitionErrors,e=>e.message),t=e.join("-----------------------\n");throw Error("Errors detected in definition of Lexer:\n"+t)}forEach(this.lexerDefinitionWarning,e=>{PRINT_WARNING(e.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(ir?(this.chopInput=identity,this.match=this.matchWithTest):(this.updateLastIndex=noop,this.match=this.matchWithExec),i&&(this.handleModes=noop),!1===this.trackStartLines&&(this.computeNewColumn=identity),!1===this.trackEndLines&&(this.updateTokenEndLineColumnLocation=noop),/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 <positionTracking> config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{let e=reduce(this.canModeBeOptimized,(e,t,r)=>(!1===t&&e.push(r),e),[]);if(t.ensureOptimizations&&!isEmpty(e))throw Error(`Lexer Modes: < ${e.join(", ")} > cannot be optimized.
876	 Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.
877	 Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{r5={}}),this.TRACE_INIT("toFastProperties",()=>{toFastProperties(this)})})}tokenize(e,t=this.defaultMode){if(!isEmpty(this.lexerDefinitionErrors)){let e=map(this.lexerDefinitionErrors,e=>e.message),t=e.join("-----------------------\n");throw Error("Unable to Tokenize because Errors detected in definition of Lexer:\n"+t)}return this.tokenizeInternal(e,t)}tokenizeInternal(e,t){let r,i,a,n,s,o,l,c,u,h,d,p,f,m,g,v,y;let T=e,x=T.length,S=0,E=0,b=this.hasCustom?0:Math.floor(e.length/10),R=Array(b),A=[],_=this.trackStartLines?1:void 0,M=this.trackStartLines?1:void 0,C=function(e){let t={},r=keys(e);return forEach(r,r=>{let i=e[r];if(e2(i))t[r]=[];else throw Error("non exhaustive match")}),t}(this.emptyGroups),w=this.trackStartLines,I=this.config.lineTerminatorsPattern,P=0,N=[],O=[],L=[],k=[];function getPossiblePatternsSlow(){return N}function getPossiblePatternsOptimized(e){let t=charCodeToOptimizedIndex(e),r=O[t];return void 0===r?k:r}Object.freeze(k);let pop_mode=e=>{if(1===L.length&&void 0===e.tokenType.PUSH_MODE){let t=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(e);A.push({offset:e.startOffset,line:e.startLine,column:e.startColumn,length:e.image.length,message:t})}else{L.pop();let e=last(L);N=this.patternIdxToConfig[e],O=this.charCodeToPatternIdxToConfig[e],P=N.length;let t=this.canModeBeOptimized[e]&&!1===this.config.safeMode;v=O&&t?getPossiblePatternsOptimized:getPossiblePatternsSlow}};function push_mode(e){L.push(e),O=this.charCodeToPatternIdxToConfig[e],P=(N=this.patternIdxToConfig[e]).length,P=N.length;let t=this.canModeBeOptimized[e]&&!1===this.config.safeMode;v=O&&t?getPossiblePatternsOptimized:getPossiblePatternsSlow}push_mode.call(this,t);let F=this.config.recoveryEnabled;for(;S<x;){o=null;let t=T.charCodeAt(S),b=v(t),O=b.length;for(r=0;r<O;r++){y=b[r];let i=y.pattern;l=null;let u=y.short;
877if(!1!==u?t===u&&(o=i):!0===y.isCustom?null!==(g=i.exec(T,S,R,C))?(o=g[0],void 0!==g.payload&&(l=g.payload)):o=null:(this.updateLastIndex(i,S),o=this.match(i,e,S)),null!==o){if(void 0!==(s=y.longerAlt)){let t=s.length;for(a=0;a<t;a++){let t=N[s[a]],r=t.pattern;if(c=null,!0===t.isCustom?null!==(g=r.exec(T,S,R,C))?(n=g[0],void 0!==g.payload&&(c=g.payload)):n=null:(this.updateLastIndex(r,S),n=this.match(r,e,S)),n&&n.length>o.length){o=n,l=c,y=t;break}}}break}}if(null!==o){if(u=o.length,void 0!==(h=y.group)&&(d=y.tokenTypeIdx,p=this.createTokenInstance(o,S,d,y.tokenType,_,M,u),this.handlePayload(p,l),!1===h?E=this.addToken(R,E,p):C[h].push(p)),e=this.chopInput(e,u),S+=u,M=this.computeNewColumn(M,u),!0===w&&!0===y.canLineTerminator){let e,t,r=0;I.lastIndex=0;do!0===(e=I.test(o))&&(t=I.lastIndex-1,r++);while(!0===e);0!==r&&(_+=r,M=u-t,this.updateTokenEndLineColumnLocation(p,h,t,r,_,M,u))}this.handleModes(y,pop_mode,push_mode,p)}else{let t=S,r=_,a=M,n=!1===F;for(;!1===n&&S<x;)for(e=this.chopInput(e,1),S++,i=0;i<P;i++){let t=N[i],r=t.pattern,a=t.short;if(!1!==a?T.charCodeAt(S)===a&&(n=!0):!0===t.isCustom?n=null!==r.exec(T,S,R,C):(this.updateLastIndex(r,S),n=null!==r.exec(e)),!0===n)break}if(f=S-t,M=this.computeNewColumn(M,f),m=this.config.errorMessageProvider.buildUnexpectedCharactersMessage(T,t,f,r,a),A.push({offset:t,line:r,column:a,length:f,message:m}),!1===F)break}}return this.hasCustom||(R.length=E),{tokens:R,groups:C,errors:A}}handleModes(e,t,r,i){if(!0===e.pop){let a=e.push;t(i),void 0!==a&&r.call(this,a)}else void 0!==e.push&&r.call(this,e.push)}chopInput(e,t){return e.substring(t)}updateLastIndex(e,t){e.lastIndex=t}updateTokenEndLineColumnLocation(e,t,r,i,a,n,s){let o,l;void 0===t||(l=(o=r===s-1)?-1:0,1===i&&!0===o||(e.endLine=a+l,e.endColumn=n-1+-l))}computeNewColumn(e,t){return e+t}createOffsetOnlyToken(e,t,r,i){return{image:e,startOffset:t,tokenTypeIdx:r,tokenType:i}}createStartOnlyToken(e,t,r,i,a,n){return{image:e,startOffset:t,startLine:a,startColumn:n,tokenTypeIdx:r,tokenType:i}}createFullToken(e,t,r,i,a,n,s){return{image:e,startOffset:t,endOffset:t+s-1,startLine:a,endLine:a,startColumn:n,endColumn:n+s-1,tokenTypeIdx:r,tokenType:i}}addTokenUsingPush(e,t,r){return e.push(r),t}addTokenUsingMemberAccess(e,t,r){return e[t]=r,++t}handlePayloadNoCustom(e,t){}handlePayloadWithCustom(e,t){null!==t&&(e.payload=t)}matchWithTest(e,t,r){let i=e.test(t);return!0===i?t.substring(r,e.lastIndex):null}matchWithExec(e,t){let r=e.exec(t);return null!==r?r[0]:null}};function tokenLabel(e){return hasTokenLabel(e)?e.LABEL:e.name}function hasTokenLabel(e){return isString(e.LABEL)&&""!==e.LABEL}Lexer.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.",Lexer.NA=/NOT_APPLICABLE/;let ih="categories",id="label",ip="group",im="push_mode",ig="pop_mode",iv="longer_alt",iy="line_breaks",iT="start_chars_hint";function createTokenInternal(e){let t=e.pattern,r={};if(r.name=e.name,isUndefined(t)||(r.PATTERN=t),has(e,"parent"))throw"The parent property is no longer supported.\nSee: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.";return has(e,ih)&&(r.CATEGORIES=e[ih]),augmentTokenTypes([r]),has(e,id)&&(r.LABEL=e[id]),has(e,ip)&&(r.GROUP=e[ip]),has(e,ig)&&(r.POP_MODE=e[ig]),has(e,im)&&(r.PUSH_MODE=e[im]),has(e,iv)&&(r.LONGER_ALT=e[iv]),has(e,iy)&&(r.LINE_BREAKS=e[iy]),has(e,iT)&&(r.START_CHARS_HINT=e[iT]),r}let ix=createTokenInternal({name:"EOF",pattern:Lexer.NA});function createTokenInstance(e,t,r,i,a,n,s,o){return{image:t,startOffset:r,endOffset:i,startLine:a,endLine:n,startColumn:s,endColumn:o,tokenTypeIdx:e.tokenTypeIdx,tokenType:e}}augmentTokenTypes([ix]);let iS={buildMismatchTokenMessage({expected:e,actual:t,previous:r,ruleName:i}){let a=hasTokenLabel(e),n=a?`--> ${tokenLabel(e)} <--`:`token of type --> ${e.name} <--`,s=`Expecting ${n} but found --> '${t.image}' <--`;return s},buildNotAllInputParsedMessage:({firstRedundant:e,ruleName:t})=>"Redundant input, expecting EOF but found: "+e.image,buildNoViableAltMessage({expectedPathsPerAlt:e,actual:t,previous:r,customUserDescription:i,ruleName:a}){let n="Expecting: ",s=head(t).image,o="\nbut found: '"+s+"'";if(i)return n+i+o;{let t=reduce(e,(e,t)=>e.concat(t),[]),r=map(t,e=>`[${map(e,e=>tokenLabel(e)).join(", ")}]`),i=map(r,(e,t)=>`  ${t+1}. ${e}`),a=`one of these possible Token sequences:
878${i.join("\n")}`;return n+a+o}},buildEarlyExitMessage({expectedIterationPaths:e,actual:t,customUserDescription:r,ruleName:i}){let a="Expecting: ",n=head(t).image,s="\nbut found: '"+n+"'";if(r)return a+r+s;{let t=map(e,e=>`[${map(e,e=>tokenLabel(e)).join(",")}]`),r=`expecting at least one iteration which starts with one of these possible Token sequences::
879  <${t.join(" ,")}>`;return a+r+s}}};Object.freeze(iS);let iE={buildRuleNotFoundError(e,t){let r="Invalid grammar, reference to a rule which is not defined: ->"+t.nonTerminalName+"<-\ninside top level rule: ->"+e.name+"<-";return r}},ib={buildDuplicateFoundError(e,t){let r=e.name,i=head(t),a=i.idx,n=getProductionDslName(i),s=i instanceof Terminal?i.terminalType.name:i instanceof NonTerminal?i.nonTerminalName:"",o=`->${n}${a>0?a:""}<- ${s?`with argument: ->${s}<-`:""}
880                  appears more than once (${t.length} times) in the top level rule: ->${r}<-.                  
881                  For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES 
882                  `;return(o=o.replace(/[ \t]+/g," ")).replace(/\s\s+/g,"\n")},buildNamespaceConflictError(e){let t=`Namespace conflict found in grammar.
883The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${e.name}>.
884To resolve this make sure each Terminal and Non-Terminal names are unique
885This is easy to accomplish by using the convention that Terminal names start with an uppercase letter
886and Non-Terminal names start with a lower case letter.`;return t},buildAlternationPrefixAmbiguityError(e){let t=map(e.prefixPath,e=>tokenLabel(e)).join(", "),r=0===e.alternation.idx?"":e.alternation.idx,i=`Ambiguous alternatives: <${e.ambiguityIndices.join(" ,")}> due to common lookahead prefix
887in <OR${r}> inside <${e.topLevelRule.name}> Rule,
888<${t}> may appears as a prefix path in all these alternatives.
889See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX
890For Further details.`;return i},buildAlternationAmbiguityError(e){let t=map(e.prefixPath,e=>tokenLabel(e)).join(", "),r=0===e.alternation.idx?"":e.alternation.idx;return`Ambiguous Alternatives Detected: <${e.ambiguityIndices.join(" ,")}> in <OR${r}> inside <${e.topLevelRule.name}> Rule,
891<${t}> may appears as a prefix path in all these alternatives.
892See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
893For Further details.`},buildEmptyRepetitionError(e){let t=getProductionDslName(e.repetition);0!==e.repetition.idx&&(t+=e.repetition.idx);let r=`The repetition <${t}> within Rule <${e.topLevelRule.name}> can never consume any tokens.
894This could lead to an infinite loop.`;return r},buildTokenNameError:e=>"deprecated",buildEmptyAlternationError(e){let t=`Ambiguous empty alternative: <${e.emptyChoiceIdx+1}> in <OR${e.alternation.idx}> inside <${e.topLevelRule.name}> Rule.
895Only the last alternative may be an empty alternative.`;return t},buildTooManyAlternativesError(e){let t=`An Alternation cannot have more than 256 alternatives:
896<OR${e.alternation.idx}> inside <${e.topLevelRule.name}> Rule.
897 has ${e.alternation.definition.length+1} alternatives.`;return t},buildLeftRecursionError(e){let t=e.topLevelRule.name,r=map(e.leftRecursionPath,e=>e.name),i=`${t} --> ${r.concat([t]).join(" --> ")}`,a=`Left Recursion found in grammar.
898rule: <${t}> can be invoked from itself (directly or indirectly)
899without consuming any Tokens. The grammar path that causes this is: 
900 ${i}
901 To fix this refactor your grammar to remove the left recursion.
902see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`;return a},buildInvalidRuleNameError:e=>"deprecated",buildDuplicateRuleNameError(e){let t;t=e.topLevelRule instanceof Rule?e.topLevelRule.name:e.topLevelRule;let r=`Duplicate definition, rule: ->${t}<- is already defined in the grammar: ->${e.grammarName}<-`;return r}};
902let GastRefResolverVisitor=class GastRefResolverVisitor extends GAstVisitor{constructor(e,t){super(),this.nameToTopRule=e,this.errMsgProvider=t,this.errors=[]}resolveRefs(){forEach(values(this.nameToTopRule),e=>{this.currTopLevel=e,e.accept(this)})}visitNonTerminal(e){let t=this.nameToTopRule[e.nonTerminalName];if(t)e.referencedRule=t;else{let t=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:t,type:I.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}}};let AbstractNextPossibleTokensWalker=class AbstractNextPossibleTokensWalker extends RestWalker{constructor(e,t){super(),this.topProd=e,this.path=t,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return 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),this.possibleTokTypes}walk(e,t=[]){this.found||super.walk(e,t)}walkProdRef(e,t,r){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){let i=t.concat(r);this.updateExpectedNext(),this.walk(e.referencedRule,i)}}updateExpectedNext(){isEmpty(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}};let NextAfterTokenWalker=class NextAfterTokenWalker extends AbstractNextPossibleTokensWalker{constructor(e,t){super(e,t),this.path=t,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(e,t,r){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){let e=t.concat(r),i=new Alternative({definition:e});this.possibleTokTypes=first(i),this.found=!0}}};let AbstractNextTerminalAfterProductionWalker=class AbstractNextTerminalAfterProductionWalker extends RestWalker{constructor(e,t){super(),this.topRule=e,this.occurrence=t,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}};let NextTerminalAfterManyWalker=class NextTerminalAfterManyWalker extends AbstractNextTerminalAfterProductionWalker{walkMany(e,t,r){if(e.idx===this.occurrence){let e=head(t.concat(r));this.result.isEndOfRule=void 0===e,e instanceof Terminal&&(this.result.token=e.terminalType,this.result.occurrence=e.idx)}else super.walkMany(e,t,r)}};let NextTerminalAfterManySepWalker=class NextTerminalAfterManySepWalker extends AbstractNextTerminalAfterProductionWalker{walkManySep(e,t,r){if(e.idx===this.occurrence){let e=head(t.concat(r));this.result.isEndOfRule=void 0===e,e instanceof Terminal&&(this.result.token=e.terminalType,this.result.occurrence=e.idx)}else super.walkManySep(e,t,r)}};let NextTerminalAfterAtLeastOneWalker=class NextTerminalAfterAtLeastOneWalker extends AbstractNextTerminalAfterProductionWalker{walkAtLeastOne(e,t,r){if(e.idx===this.occurrence){let e=head(t.concat(r));this.result.isEndOfRule=void 0===e,e instanceof Terminal&&(this.result.token=e.terminalType,this.result.occurrence=e.idx)}else super.walkAtLeastOne(e,t,r)}};let NextTerminalAfterAtLeastOneSepWalker=class NextTerminalAfterAtLeastOneSepWalker extends AbstractNextTerminalAfterProductionWalker{walkAtLeastOneSep(e,t,r){if(e.idx===this.occurrence){let e=head(t.concat(r));this.result.isEndOfRule=void 0===e,e instanceof Terminal&&(this.result.token=e.terminalType,this.result.occurrence=e.idx)}else super.walkAtLeastOneSep(e,t,r)}};function possiblePathsFrom(e,t,r=[]){r=clone(r);let i=[],a=0;function getAlternativesForProd(n){let s=possiblePathsFrom(n.concat(drop(e,a+1)),t,r);return i.concat(s)}for(;r.length<t&&a<e.length;){let t=e[a];if(t instanceof Alternative||t instanceof NonTerminal)return getAlternativesForProd(t.definition);if(t instanceof Option)i=getAlternativesForProd(t.definition);else if(t instanceof RepetitionMandatory){let e=t.definition.concat([new Repetition({definition:t.definition})]);return getAlternativesForProd(e)}else if(t instanceof RepetitionMandatoryWithSeparator){let e=[new Alternative({definition:t.definition}),new Repetition({definition:[new Terminal({terminalType:t.separator})].concat(t.definition)})];return getAlternativesForProd(e)}else if(t instanceof RepetitionWithSeparator){let e=t.definition.concat([new Repetition({definition:[new Terminal({terminalType:t.separator})].concat(t.definition)})]);i=getAlternativesForProd(e)}else if(t instanceof Repetition){let e=t.definition.concat([new Repetition({definition:t.definition})]);i=getAlternativesForProd(e)}else if(t instanceof Alternation)return forEach(t.definition,e=>{!1===isEmpty(e.definition)&&(i=getAlternativesForProd(e.definition))}),i;else if(t instanceof Terminal)r.push(t.terminalType);else throw Error("non exhaustive match");a++}return i.push({partialPath:r,suffixDef:drop(e,a)}),i}
902function nextPossibleTokensAfter(e,t,r,i){let a="EXIT_NONE_TERMINAL",n=[a],s="EXIT_ALTERNATIVE",o=!1,l=t.length,c=l-i-1,u=[],h=[];for(h.push({idx:-1,def:e,ruleStack:[],occurrenceStack:[]});!isEmpty(h);){let e=h.pop();if(e===s){o&&last(h).idx<=c&&h.pop();continue}let i=e.def,d=e.idx,p=e.ruleStack,f=e.occurrenceStack;if(isEmpty(i))continue;let m=i[0];if(m===a){let e={idx:d,def:drop(i),ruleStack:dropRight(p),occurrenceStack:dropRight(f)};h.push(e)}else if(m instanceof Terminal){if(d<l-1){let e=d+1,a=t[e];if(r(a,m.terminalType)){let t={idx:e,def:drop(i),ruleStack:p,occurrenceStack:f};h.push(t)}}else if(d===l-1)u.push({nextTokenType:m.terminalType,nextTokenOccurrence:m.idx,ruleStack:p,occurrenceStack:f}),o=!0;else throw Error("non exhaustive match")}else if(m instanceof NonTerminal){let e=clone(p);e.push(m.nonTerminalName);let t=clone(f);t.push(m.idx);let r={idx:d,def:m.definition.concat(n,drop(i)),ruleStack:e,occurrenceStack:t};h.push(r)}else if(m instanceof Option){let e={idx:d,def:drop(i),ruleStack:p,occurrenceStack:f};h.push(e),h.push(s);let t={idx:d,def:m.definition.concat(drop(i)),ruleStack:p,occurrenceStack:f};h.push(t)}else if(m instanceof RepetitionMandatory){let e=new Repetition({definition:m.definition,idx:m.idx}),t=m.definition.concat([e],drop(i)),r={idx:d,def:t,ruleStack:p,occurrenceStack:f};h.push(r)}else if(m instanceof RepetitionMandatoryWithSeparator){let e=new Terminal({terminalType:m.separator}),t=new Repetition({definition:[e].concat(m.definition),idx:m.idx}),r=m.definition.concat([t],drop(i)),a={idx:d,def:r,ruleStack:p,occurrenceStack:f};h.push(a)}else if(m instanceof RepetitionWithSeparator){let e={idx:d,def:drop(i),ruleStack:p,occurrenceStack:f};h.push(e),h.push(s);let t=new Terminal({terminalType:m.separator}),r=new Repetition({definition:[t].concat(m.definition),idx:m.idx}),a=m.definition.concat([r],drop(i)),n={idx:d,def:a,ruleStack:p,occurrenceStack:f};h.push(n)}else if(m instanceof Repetition){let e={idx:d,def:drop(i),ruleStack:p,occurrenceStack:f};h.push(e),h.push(s);let t=new Repetition({definition:m.definition,idx:m.idx}),r=m.definition.concat([t],drop(i)),a={idx:d,def:r,ruleStack:p,occurrenceStack:f};h.push(a)}else if(m instanceof Alternation)for(let e=m.definition.length-1;e>=0;e--){let t=m.definition[e],r={idx:d,def:t.definition.concat(drop(i)),ruleStack:p,occurrenceStack:f};h.push(r),h.push(s)}else if(m instanceof Alternative)h.push({idx:d,def:m.definition.concat(drop(i)),ruleStack:p,occurrenceStack:f});else if(m instanceof Rule)h.push(function(e,t,r,i){let a=clone(r);a.push(e.name);let n=clone(i);return n.push(1),{idx:t,def:e.definition,ruleStack:a,occurrenceStack:n}}(m,d,p,f));else throw Error("non exhaustive match")}return u}function getProdType(e){if(e instanceof Option||"Option"===e)return C.OPTION;if(e instanceof Repetition||"Repetition"===e)return C.REPETITION;if(e instanceof RepetitionMandatory||"RepetitionMandatory"===e)return C.REPETITION_MANDATORY;if(e instanceof RepetitionMandatoryWithSeparator||"RepetitionMandatoryWithSeparator"===e)return C.REPETITION_MANDATORY_WITH_SEPARATOR;if(e instanceof RepetitionWithSeparator||"RepetitionWithSeparator"===e)return C.REPETITION_WITH_SEPARATOR;if(e instanceof Alternation||"Alternation"===e)return C.ALTERNATION;throw Error("non exhaustive match")}function buildAlternativesLookAheadFunc(e,t,r,i){let a=e.length,n=every(e,e=>every(e,e=>1===e.length));if(t)return function(t){let i=map(t,e=>e.GATE);for(let t=0;t<a;t++){let a=e[t],n=a.length,s=i[t];if(void 0===s||!1!==s.call(this))t:for(let e=0;e<n;e++){let i=a[e],n=i.length;for(let e=0;e<n;e++){let t=this.LA(e+1);if(!1===r(t,i[e]))continue t}return t}}};if(!n||i)return function(){for(let t=0;t<a;t++){let i=e[t],a=i.length;t:for(let e=0;e<a;e++){let a=i[e],n=a.length;for(let e=0;e<n;e++){let t=this.LA(e+1);if(!1===r(t,a[e]))continue t}return t}}};{let t=map(e,e=>flatten(e)),r=reduce(t,(e,t,r)=>(forEach(t,t=>{has(e,t.tokenTypeIdx)||(e[t.tokenTypeIdx]=r),forEach(t.categoryMatches,t=>{has(e,t)||(e[t]=r)})}),e),{});return function(){let e=this.LA(1);return r[e.tokenTypeIdx]}}}function buildSingleAlternativeLookaheadFunction(e,t,r){let i=every(e,e=>1===e.length),a=e.length;if(!i||r)return function(){t:for(let r=0;r<a;r++){let i=e[r],a=i.length;for(let e=0;e<a;e++){let r=this.LA(e+1);if(!1===t(r,i[e]))continue t}return!0}return!1};{let t=flatten(e);if(1===t.length&&isEmpty(t[0].categoryMatches)){let e=t[0],r=e.tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===r}}{let e=reduce(t,(e,t,r)=>(e[t.tokenTypeIdx]=!0,forEach(t.categoryMatches,t=>{e[t]=!0}),e),[]);return function(){let t=this.LA(1);return!0===e[t.tokenTypeIdx]}}}}(R=C||(C={}))[R.OPTION=0]="OPTION",R[R.REPETITION=1]="REPETITION",R[R.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",R[R.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",R[R.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",R[R.ALTERNATION=5]="ALTERNATION";let RestDefinitionFinderWalker=class RestDefinitionFinderWalker extends RestWalker{constructor(e,t,r){super(),this.topProd=e,this.targetOccurrence=t,this.targetProdType=r}startWalking(){return this.walk(this.topProd),this.restDef}
902checkIsTarget(e,t,r,i){return e.idx===this.targetOccurrence&&this.targetProdType===t&&(this.restDef=r.concat(i),!0)}walkOption(e,t,r){this.checkIsTarget(e,C.OPTION,t,r)||super.walkOption(e,t,r)}walkAtLeastOne(e,t,r){this.checkIsTarget(e,C.REPETITION_MANDATORY,t,r)||super.walkOption(e,t,r)}walkAtLeastOneSep(e,t,r){this.checkIsTarget(e,C.REPETITION_MANDATORY_WITH_SEPARATOR,t,r)||super.walkOption(e,t,r)}walkMany(e,t,r){this.checkIsTarget(e,C.REPETITION,t,r)||super.walkOption(e,t,r)}walkManySep(e,t,r){this.checkIsTarget(e,C.REPETITION_WITH_SEPARATOR,t,r)||super.walkOption(e,t,r)}};let InsideDefinitionFinderVisitor=class InsideDefinitionFinderVisitor extends GAstVisitor{constructor(e,t,r){super(),this.targetOccurrence=e,this.targetProdType=t,this.targetRef=r,this.result=[]}checkIsTarget(e,t){e.idx===this.targetOccurrence&&this.targetProdType===t&&(void 0===this.targetRef||e===this.targetRef)&&(this.result=e.definition)}visitOption(e){this.checkIsTarget(e,C.OPTION)}visitRepetition(e){this.checkIsTarget(e,C.REPETITION)}visitRepetitionMandatory(e){this.checkIsTarget(e,C.REPETITION_MANDATORY)}visitRepetitionMandatoryWithSeparator(e){this.checkIsTarget(e,C.REPETITION_MANDATORY_WITH_SEPARATOR)}visitRepetitionWithSeparator(e){this.checkIsTarget(e,C.REPETITION_WITH_SEPARATOR)}visitAlternation(e){this.checkIsTarget(e,C.ALTERNATION)}};function initializeArrayOfArrays(e){let t=Array(e);for(let r=0;r<e;r++)t[r]=[];return t}function pathToHashKeys(e){let t=[""];for(let r=0;r<e.length;r++){let i=e[r],a=[];for(let e=0;e<t.length;e++){let r=t[e];a.push(r+"_"+i.tokenTypeIdx);for(let e=0;e<i.categoryMatches.length;e++){let t="_"+i.categoryMatches[e];a.push(r+t)}}t=a}return t}function lookAheadSequenceFromAlternatives(e,t){let r=map(e,e=>possiblePathsFrom([e],1)),i=initializeArrayOfArrays(r.length),a=map(r,e=>{let t={};return forEach(e,e=>{let r=pathToHashKeys(e.partialPath);forEach(r,e=>{t[e]=!0})}),t}),n=r;for(let e=1;e<=t;e++){let r=n;n=initializeArrayOfArrays(r.length);for(let s=0;s<r.length;s++){let o=r[s];for(let r=0;r<o.length;r++){let l=o[r].partialPath,c=o[r].suffixDef,u=pathToHashKeys(l),h=function(e,t,r){for(let i=0;i<e.length;i++){if(i===r)continue;let a=e[i];for(let e=0;e<t.length;e++){let r=t[e];if(!0===a[r])return!1}}return!0}(a,u,s);if(h||isEmpty(c)||l.length===t){let e=i[s];if(!1===containsPath(e,l)){e.push(l);for(let e=0;e<u.length;e++){let t=u[e];a[s][t]=!0}}}else{let t=possiblePathsFrom(c,e+1,l);n[s]=n[s].concat(t),forEach(t,e=>{let t=pathToHashKeys(e.partialPath);forEach(t,e=>{a[s][e]=!0})})}}}}return i}function getLookaheadPathsForOr(e,t,r,i){let a=new InsideDefinitionFinderVisitor(e,C.ALTERNATION,i);return t.accept(a),lookAheadSequenceFromAlternatives(a.result,r)}function getLookaheadPathsForOptionalProd(e,t,r,i){let a=new InsideDefinitionFinderVisitor(e,r);t.accept(a);let n=a.result,s=new RestDefinitionFinderWalker(t,e,r),o=s.startWalking(),l=new Alternative({definition:n}),c=new Alternative({definition:o});return lookAheadSequenceFromAlternatives([l,c],i)}function containsPath(e,t){r:for(let r=0;r<e.length;r++){let i=e[r];if(i.length===t.length){for(let e=0;e<i.length;e++){let r=t[e],a=i[e],n=r===a||void 0!==a.categoryMatchesMap[r.tokenTypeIdx];if(!1===n)continue r}return!0}}return!1}function areTokenCategoriesNotUsed(e){return every(e,e=>every(e,e=>every(e,e=>isEmpty(e.categoryMatches))))}function identifyProductionForDuplicates(e){return`${getProductionDslName(e)}_#_${e.idx}_#_${getExtraProductionArgument(e)}`}function getExtraProductionArgument(e){return e instanceof Terminal?e.terminalType.name:e instanceof NonTerminal?e.nonTerminalName:""}let OccurrenceValidationCollector=class OccurrenceValidationCollector extends GAstVisitor{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(e){this.allProductions.push(e)}visitOption(e){this.allProductions.push(e)}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}visitAlternation(e){this.allProductions.push(e)}visitTerminal(e){this.allProductions.push(e)}};let OrCollector=class OrCollector extends GAstVisitor{constructor(){super(...arguments),this.alternations=[]}visitAlternation(e){this.alternations.push(e)}};let RepetitionCollector=class RepetitionCollector extends GAstVisitor{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}};let iR="MismatchedTokenException",iA="NoViableAltException",i_="EarlyExitException",iM="NotAllInputParsedException",iC=[iR,iA,i_,iM];function isRecognitionException(e){return includes(iC,e.name)}Object.freeze(iC);
902let RecognitionException=class RecognitionException extends Error{constructor(e,t){super(e),this.token=t,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};let MismatchedTokenException=class MismatchedTokenException extends RecognitionException{constructor(e,t,r){super(e,t),this.previousToken=r,this.name=iR}};let NoViableAltException=class NoViableAltException extends RecognitionException{constructor(e,t,r){super(e,t),this.previousToken=r,this.name=iA}};let NotAllInputParsedException=class NotAllInputParsedException extends RecognitionException{constructor(e,t){super(e,t),this.name=iM}};let EarlyExitException=class EarlyExitException extends RecognitionException{constructor(e,t,r){super(e,t),this.previousToken=r,this.name=i_}};let iw={},iI="InRuleRecoveryException";let InRuleRecoveryException=class InRuleRecoveryException extends Error{constructor(e){super(e),this.name=iI}};function attemptInRepetitionRecovery(e,t,r,i,a,n,s){let o=this.getKeyForAutomaticLookahead(i,a),l=this.firstAfterRepMap[o];if(void 0===l){let e=this.getCurrRuleFullName(),t=this.getGAstProductions()[e],r=new n(t,a);l=r.startWalking(),this.firstAfterRepMap[o]=l}let c=l.token,u=l.occurrence,h=l.isEndOfRule;1===this.RULE_STACK.length&&h&&void 0===c&&(c=ix,u=1),void 0!==c&&void 0!==u&&this.shouldInRepetitionRecoveryBeTried(c,u,s)&&this.tryInRepetitionRecovery(e,t,r,c)}let LLkLookaheadStrategy=class LLkLookaheadStrategy{constructor(e){var t;this.maxLookahead=null!==(t=null==e?void 0:e.maxLookahead)&&void 0!==t?t:iD.maxLookahead}validate(e){let t=this.validateNoLeftRecursion(e.rules);if(isEmpty(t)){let r=this.validateEmptyOrAlternatives(e.rules),i=this.validateAmbiguousAlternationAlternatives(e.rules,this.maxLookahead),a=this.validateSomeNonEmptyLookaheadPath(e.rules,this.maxLookahead),n=[...t,...r,...i,...a];return n}return t}validateNoLeftRecursion(e){return flatMap(e,e=>(function validateNoLeftRecursion(e,t,r,i=[]){let a=[],n=function getFirstNoneTerminal(e){let t=[];if(isEmpty(e))return t;let r=head(e);if(r instanceof NonTerminal)t.push(r.referencedRule);else if(r instanceof Alternative||r instanceof Option||r instanceof RepetitionMandatory||r instanceof RepetitionMandatoryWithSeparator||r instanceof RepetitionWithSeparator||r instanceof Repetition)t=t.concat(getFirstNoneTerminal(r.definition));else if(r instanceof Alternation)t=flatten(map(r.definition,e=>getFirstNoneTerminal(e.definition)));else if(r instanceof Terminal);else throw Error("non exhaustive match");let i=isOptionalProd(r),a=e.length>1;if(!i||!a)return t;{let r=drop(e);return t.concat(getFirstNoneTerminal(r))}}(t.definition);if(isEmpty(n))return[];{let t=e.name,s=includes(n,e);s&&a.push({message:r.buildLeftRecursionError({topLevelRule:e,leftRecursionPath:i}),type:I.LEFT_RECURSION,ruleName:t});let o=rV(n,i.concat([e])),l=flatMap(o,t=>{let a=clone(i);return a.push(t),validateNoLeftRecursion(e,t,r,a)});return a.concat(l)}})(e,e,ib))}validateEmptyOrAlternatives(e){return flatMap(e,e=>(function(e,t){let r=new OrCollector;e.accept(r);let i=r.alternations,a=flatMap(i,r=>{let i=dropRight(r.definition);return flatMap(i,(i,a)=>{let n=nextPossibleTokensAfter([i],[],tokenStructuredMatcher,1);return isEmpty(n)?[{message:t.buildEmptyAlternationError({topLevelRule:e,alternation:r,emptyChoiceIdx:a}),type:I.NONE_LAST_EMPTY_ALT,ruleName:e.name,occurrence:r.idx,alternative:a+1}]:[]})});return a})(e,ib))}validateAmbiguousAlternationAlternatives(e,t){return flatMap(e,e=>(function(e,t,r){let i=new OrCollector;e.accept(i);let a=i.alternations;a=reject(a,e=>!0===e.ignoreAmbiguities);let n=flatMap(a,i=>{let a=i.idx,n=i.maxLookahead||t,s=getLookaheadPathsForOr(a,e,n,i),o=function(e,t,r,i){let a=[],n=reduce(e,(r,i,n)=>(!0===t.definition[n].ignoreAmbiguities||forEach(i,i=>{let s=[n];forEach(e,(e,r)=>{n!==r&&containsPath(e,i)&&!0!==t.definition[r].ignoreAmbiguities&&s.push(r)}),s.length>1&&!containsPath(a,i)&&(a.push(i),r.push({alts:s,path:i}))}),r),[]),s=map(n,e=>{let a=map(e.alts,e=>e+1),n=i.buildAlternationAmbiguityError({topLevelRule:r,alternation:t,ambiguityIndices:a,prefixPath:e.path});return{message:n,type:I.AMBIGUOUS_ALTS,ruleName:r.name,occurrence:t.idx,alternatives:e.alts}});return s}(s,i,e,r),l=function(e,t,r,i){let a=reduce(e,(e,t,r)=>{let i=map(t,e=>({idx:r,path:e}));return e.concat(i)},[]),n=compact(flatMap(a,e=>{let n=t.definition[e.idx];if(!0===n.ignoreAmbiguities)return[];let s=e.idx,o=e.path,l=filter(a,e=>{var r;return!0!==t.definition[e.idx].ignoreAmbiguities&&e.idx<s&&(r=e.path).length<o.length&&every(r,(e,t)=>{let r=o[t];return e===r||r.categoryMatchesMap[e.tokenTypeIdx]})}),c=map(l,e=>
902{let a=[e.idx+1,s+1],n=0===t.idx?"":t.idx,o=i.buildAlternationPrefixAmbiguityError({topLevelRule:r,alternation:t,ambiguityIndices:a,prefixPath:e.path});return{message:o,type:I.AMBIGUOUS_PREFIX_ALTS,ruleName:r.name,occurrence:n,alternatives:a}});return c}));return n}(s,i,e,r);return o.concat(l)});return n})(e,t,ib))}validateSomeNonEmptyLookaheadPath(e,t){return function(e,t,r){let i=[];return forEach(e,e=>{let a=new RepetitionCollector;e.accept(a);let n=a.allProductions;forEach(n,a=>{let n=getProdType(a),s=a.maxLookahead||t,o=a.idx,l=getLookaheadPathsForOptionalProd(o,e,n,s),c=l[0];if(isEmpty(flatten(c))){let t=r.buildEmptyRepetitionError({topLevelRule:e,repetition:a});i.push({message:t,type:I.NO_NON_EMPTY_LOOKAHEAD,ruleName:e.name})}})}),i}(e,t,ib)}buildLookaheadForAlternation(e){return function(e,t,r,i,a,n){let s=getLookaheadPathsForOr(e,t,r),o=areTokenCategoriesNotUsed(s)?tokenStructuredMatcherNoCategories:tokenStructuredMatcher;return n(s,i,o,a)}(e.prodOccurrence,e.rule,e.maxLookahead,e.hasPredicates,e.dynamicTokensEnabled,buildAlternativesLookAheadFunc)}buildLookaheadForOptional(e){return function(e,t,r,i,a,n){let s=getLookaheadPathsForOptionalProd(e,t,a,r),o=areTokenCategoriesNotUsed(s)?tokenStructuredMatcherNoCategories:tokenStructuredMatcher;return n(s[0],o,i)}(e.prodOccurrence,e.rule,e.maxLookahead,e.dynamicTokensEnabled,getProdType(e.prodType),buildSingleAlternativeLookaheadFunction)}};let iP=new class extends GAstVisitor{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(e){this.dslMethods.option.push(e)}visitRepetitionWithSeparator(e){this.dslMethods.repetitionWithSeparator.push(e)}visitRepetitionMandatory(e){this.dslMethods.repetitionMandatory.push(e)}visitRepetitionMandatoryWithSeparator(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)}visitRepetition(e){this.dslMethods.repetition.push(e)}visitAlternation(e){this.dslMethods.alternation.push(e)}};function setNodeLocationOnlyOffset(e,t){!0===isNaN(e.startOffset)?(e.startOffset=t.startOffset,e.endOffset=t.endOffset):e.endOffset<t.endOffset==!0&&(e.endOffset=t.endOffset)}function setNodeLocationFull(e,t){!0===isNaN(e.startOffset)?(e.startOffset=t.startOffset,e.startColumn=t.startColumn,e.startLine=t.startLine,e.endOffset=t.endOffset,e.endColumn=t.endColumn,e.endLine=t.endLine):e.endOffset<t.endOffset==!0&&(e.endOffset=t.endOffset,e.endColumn=t.endColumn,e.endLine=t.endLine)}function defineNameProp(e,t){Object.defineProperty(e,"name",{enumerable:!1,configurable:!0,writable:!1,value:t})}function defaultVisit(e,t){let r=keys(e),i=r.length;for(let a=0;a<i;a++){let i=r[a],n=e[i],s=n.length;for(let e=0;e<s;e++){let r=n[e];void 0===r.tokenTypeIdx&&this[r.name](r.children,t)}}}(A=w||(w={}))[A.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",A[A.MISSING_METHOD=1]="MISSING_METHOD";let iN={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(iN);let iO=createTokenInternal({name:"RECORDING_PHASE_TOKEN",pattern:Lexer.NA});augmentTokenTypes([iO]);let iL=createTokenInstance(iO,"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(iL);let ik={name:"This CSTNode indicates the Parser is in Recording Phase\n	See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details",children:{}};function recordProd(e,t,r,i=!1){assertMethodIdxIsValid(r);let a=last(this.recordingProdStack),n=isFunction(t)?t:t.DEF,s=new e({definition:[],idx:r});return i&&(s.separator=t.SEP),has(t,"MAX_LOOKAHEAD")&&(s.maxLookahead=t.MAX_LOOKAHEAD),this.recordingProdStack.push(s),n.call(this),a.definition.push(s),this.recordingProdStack.pop(),iN}function recordOrProd(e,t){assertMethodIdxIsValid(t);let r=last(this.recordingProdStack),i=!1===e2(e),a=!1===i?e:e.DEF,n=new Alternation({definition:[],idx:t,ignoreAmbiguities:i&&!0===e.IGNORE_AMBIGUITIES});has(e,"MAX_LOOKAHEAD")&&(n.maxLookahead=e.MAX_LOOKAHEAD);let s=some(a,e=>isFunction(e.GATE));
902return n.hasPredicates=s,r.definition.push(n),forEach(a,e=>{let t=new Alternative({definition:[]});n.definition.push(t),has(e,"IGNORE_AMBIGUITIES")?t.ignoreAmbiguities=e.IGNORE_AMBIGUITIES:has(e,"GATE")&&(t.ignoreAmbiguities=!0),this.recordingProdStack.push(t),e.ALT.call(this),this.recordingProdStack.pop()}),iN}function getIdxSuffix(e){return 0===e?"":`${e}`}function assertMethodIdxIsValid(e){if(e<0||e>255){let t=Error(`Invalid DSL Method idx value: <${e}>
903	Idx value must be a none negative value smaller than 256`);throw t.KNOWN_RECORDER_ERROR=!0,t}}let iF=createTokenInstance(ix,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(iF);let iD=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:iS,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),iU=Object.freeze({recoveryValueFunc:()=>void 0,resyncEnabled:!0});(_=I||(I={}))[_.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",_[_.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",_[_.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",_[_.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",_[_.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",_[_.LEFT_RECURSION=5]="LEFT_RECURSION",_[_.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",_[_.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",_[_.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",_[_.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",_[_.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",_[_.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",_[_.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",_[_.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION";let Parser=class Parser{static performSelfAnalysis(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated.	\nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let e;this.selfAnalysisDone=!0;let t=this.className;this.TRACE_INIT("toFastProps",()=>{toFastProperties(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),forEach(this.definedRulesNames,e=>{let t;let r=this[e],i=r.originalGrammarAction;this.TRACE_INIT(`${e} Rule`,()=>{t=this.topLevelRuleRecord(e,i)}),this.gastProductionsCache[e]=t})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT("Grammar Resolving",()=>{r=function(e){let t=rB(e,{errMsgProvider:iE}),r={};return forEach(e.rules,e=>{r[e.name]=e}),function(e,t){let r=new GastRefResolverVisitor(e,t);return r.resolveRefs(),r.errors}(r,t.errMsgProvider)}({rules:values(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT("Grammar Validations",()=>{if(isEmpty(r)&&!1===this.skipValidations){var e;let r=function(e,t,r,i){let a=flatMap(e,e=>(function(e,t){let r=new OccurrenceValidationCollector;e.accept(r);let i=r.allProductions,a=rW(i,identifyProductionForDuplicates),n=pickBy(a,e=>e.length>1),s=map(values(n),r=>{let i=head(r),a=t.buildDuplicateFoundError(e,r),n=getProductionDslName(i),s={message:a,type:I.DUPLICATE_PRODUCTIONS,ruleName:e.name,dslName:n,occurrence:i.idx},o=getExtraProductionArgument(i);return o&&(s.parameter=o),s});return s})(e,r)),n=function(e,t,r){let i=[],a=map(t,e=>e.name);return forEach(e,e=>{let t=e.name;if(includes(a,t)){let a=r.buildNamespaceConflictError(e);i.push({message:a,type:I.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:t})}}),i}(e,t,r),s=flatMap(e,e=>(function(e,t){let r=new OrCollector;e.accept(r);let i=r.alternations,a=flatMap(i,r=>r.definition.length>255?[{message:t.buildTooManyAlternativesError({topLevelRule:e,alternation:r}),type:I.TOO_MANY_ALTS,ruleName:e.name,occurrence:r.idx}]:[]);return a})(e,r)),o=flatMap(e,t=>(function(e,t,r,i){let a=[],n=reduce(t,(t,r)=>r.name===e.name?t+1:t,0);if(n>1){let t=i.buildDuplicateRuleNameError({topLevelRule:e,grammarName:r});a.push({message:t,type:I.DUPLICATE_RULE_NAME,ruleName:e.name})}return a})(t,e,i,r));return a.concat(n,s,o)}((e=rB(e={rules:values(this.gastProductionsCache),tokenTypes:values(this.tokensMap),errMsgProvider:ib,grammarName:t},{errMsgProvider:ib})).rules,e.tokenTypes,e.errMsgProvider,e.grammarName),i=function(e){let t=e.lookaheadStrategy.validate({rules:e.rules,tokenTypes:e.tokenTypes,grammarName:e.grammarName});return map(t,e=>Object.assign({type:I.CUSTOM_LOOKAHEAD_VALIDATION},e))}({lookaheadStrategy:this.lookaheadStrategy,rules:values(this.gastProductionsCache),tokenTypes:values(this.tokensMap),grammarName:t});this.definitionErrors=this.definitionErrors.concat(r,i)}}),isEmpty(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{let e=function(e){let t={};return forEach(e,e=>{let r=new ResyncFollowsWalker(e).startWalking();tG(t,r)}),t}(values(this.gastProductionsCache));this.resyncFollows=e}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var e,t;null===(t=(e=this.lookaheadStrategy).initialize)||void 0===t||t.call(e,{rules:values(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(values(this.gastProductionsCache))})),!Parser.DEFER_DEFINITION_ERRORS_HANDLING&&!isEmpty(this.definitionErrors))throw e=map(this.definitionErrors,e=>e.message),Error(`Parser Definition Errors detected:
904 ${e.join("\n-------------------------------\n")}`)})}constructor(e,t){if(this.definitionErrors=[],this.selfAnalysisDone=!1,this.initErrorHandler(t),this.initLexerAdapter(),this.initLooksAhead(t),this.initRecognizerEngine(e,t),this.initRecoverable(t),this.initTreeBuilder(t),this.initContentAssist(),this.initGastRecorder(t),this.initPerformanceTracer(t),has(t,"ignoredIssues"))throw Error("The <ignoredIssues> IParserConfig property has been deprecated.\n	Please use the <IGNORE_AMBIGUITIES> 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(t,"skipValidations")?t.skipValidations:iD.skipValidations}};Parser.DEFER_DEFINITION_ERRORS_HANDLING=!1,function(e,t){t.forEach(t=>{let r=t.prototype;Object.getOwnPropertyNames(r).forEach(i=>
904{if("constructor"===i)return;let a=Object.getOwnPropertyDescriptor(r,i);a&&(a.get||a.set)?Object.defineProperty(e.prototype,i,a):e.prototype[i]=t.prototype[i]})})}(Parser,[class{initRecoverable(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=has(e,"recoveryEnabled")?e.recoveryEnabled:iD.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=attemptInRepetitionRecovery)}getTokenToInsert(e){let t=createTokenInstance(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return t.isInsertedInRecovery=!0,t}canTokenTypeBeInsertedInRecovery(e){return!0}canTokenTypeBeDeletedInRecovery(e){return!0}tryInRepetitionRecovery(e,t,r,i){let a=this.findReSyncTokenType(),n=this.exportLexerState(),s=[],o=!1,l=this.LA(1),c=this.LA(1),generateErrorMessage=()=>{let e=this.LA(0),t=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:l,previous:e,ruleName:this.getCurrRuleFullName()}),r=new MismatchedTokenException(t,l,this.LA(0));r.resyncedTokens=dropRight(s),this.SAVE_ERROR(r)};for(;!o;){if(this.tokenMatcher(c,i)){generateErrorMessage();return}if(r.call(this)){generateErrorMessage(),e.apply(this,t);return}this.tokenMatcher(c,a)?o=!0:(c=this.SKIP_TOKEN(),this.addToResyncTokens(c,s))}this.importLexerState(n)}shouldInRepetitionRecoveryBeTried(e,t,r){return!(!1===r||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,t)))}getFollowsForInRuleRecovery(e,t){let r=this.getCurrentGrammarPath(e,t),i=this.getNextPossibleTokenTypes(r);return i}tryInRuleRecovery(e,t){if(this.canRecoverWithSingleTokenInsertion(e,t)){let t=this.getTokenToInsert(e);return t}if(this.canRecoverWithSingleTokenDeletion(e)){let e=this.SKIP_TOKEN();return this.consumeToken(),e}throw new InRuleRecoveryException("sad sad panda")}canPerformInRuleRecovery(e,t){return this.canRecoverWithSingleTokenInsertion(e,t)||this.canRecoverWithSingleTokenDeletion(e)}canRecoverWithSingleTokenInsertion(e,t){if(!this.canTokenTypeBeInsertedInRecovery(e)||isEmpty(t))return!1;let r=this.LA(1),i=void 0!==rj(t,e=>this.tokenMatcher(r,e));return i}canRecoverWithSingleTokenDeletion(e){if(!this.canTokenTypeBeDeletedInRecovery(e))return!1;let t=this.tokenMatcher(this.LA(2),e);return t}isInCurrentRuleReSyncSet(e){let t=this.getCurrFollowKey(),r=this.getFollowSetFromFollowKey(t);return includes(r,e)}findReSyncTokenType(){let e=this.flattenFollowSet(),t=this.LA(1),r=2;for(;;){let i=rj(e,e=>{let r=tokenStructuredMatcher(t,e);return r});if(void 0!==i)return i;t=this.LA(r),r++}}getCurrFollowKey(){if(1===this.RULE_STACK.length)return iw;let e=this.getLastExplicitRuleShortName(),t=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:t,inRule:this.shortRuleNameToFullName(r)}}buildFullFollowKeyStack(){let e=this.RULE_STACK,t=this.RULE_OCCURRENCE_STACK;return map(e,(r,i)=>0===i?iw:{ruleName:this.shortRuleNameToFullName(r),idxInCallingRule:t[i],inRule:this.shortRuleNameToFullName(e[i-1])})}flattenFollowSet(){let e=map(this.buildFullFollowKeyStack(),e=>this.getFollowSetFromFollowKey(e));return flatten(e)}getFollowSetFromFollowKey(e){if(e===iw)return[ix];let t=e.ruleName+e.idxInCallingRule+rQ+e.inRule;return this.resyncFollows[t]}addToResyncTokens(e,t){return this.tokenMatcher(e,ix)||t.push(e),t}reSyncTo(e){let t=[],r=this.LA(1);for(;!1===this.tokenMatcher(r,e);)r=this.SKIP_TOKEN(),this.addToResyncTokens(r,t);return dropRight(t)}attemptInRepetitionRecovery(e,t,r,i,a,n,s){}getCurrentGrammarPath(e,t){let r=this.getHumanReadableRuleStack(),i=clone(this.RULE_OCCURRENCE_STACK);return{ruleStack:r,occurrenceStack:i,lastTok:e,lastTokOccurrence:t}}getHumanReadableRuleStack(){return map(this.RULE_STACK,e=>this.shortRuleNameToFullName(e))}},class{initLooksAhead(e){this.dynamicTokensEnabled=has(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:iD.dynamicTokensEnabled,this.maxLookahead=has(e,"maxLookahead")?e.maxLookahead:iD.maxLookahead,this.lookaheadStrategy=has(e,"lookaheadStrategy")?e.lookaheadStrategy:new LLkLookaheadStrategy({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(e){forEach(e,e=>{this.TRACE_INIT(`${e.name} Rule Lookahead`,()=>{let{alternation:t,repetition:r,option:i,repetitionMandatory:a,repetitionMandatoryWithSeparator:n,repetitionWithSeparator:s}=function(e){iP.reset(),e.accept(iP);let t=iP.dslMethods;return iP.reset(),t}(e);forEach(t,t=>{let r=0===t.idx?"":t.idx;this.TRACE_INIT(`${getProductionDslName(t)}${r}`,()=>{var r;let i=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:t.idx,rule:e,maxLookahead:t.maxLookahead||this.maxLookahead,hasPredicates:t.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),a=(r=this.fullRuleNameToShort[e.name],256|t.idx|r);this.setLaFuncCache(a,i)})}
904),forEach(r,t=>{this.computeLookaheadFunc(e,t.idx,768,"Repetition",t.maxLookahead,getProductionDslName(t))}),forEach(i,t=>{this.computeLookaheadFunc(e,t.idx,512,"Option",t.maxLookahead,getProductionDslName(t))}),forEach(a,t=>{this.computeLookaheadFunc(e,t.idx,1024,"RepetitionMandatory",t.maxLookahead,getProductionDslName(t))}),forEach(n,t=>{this.computeLookaheadFunc(e,t.idx,1536,"RepetitionMandatoryWithSeparator",t.maxLookahead,getProductionDslName(t))}),forEach(s,t=>{this.computeLookaheadFunc(e,t.idx,1280,"RepetitionWithSeparator",t.maxLookahead,getProductionDslName(t))})})})}computeLookaheadFunc(e,t,r,i,a,n){this.TRACE_INIT(`${n}${0===t?"":t}`,()=>{let n=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:t,rule:e,maxLookahead:a||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),s=t|r|this.fullRuleNameToShort[e.name];this.setLaFuncCache(s,n)})}getKeyForAutomaticLookahead(e,t){let r=this.getLastExplicitRuleShortName();return t|e|r}getLaFuncFromCache(e){return this.lookAheadFuncsCache.get(e)}setLaFuncCache(e,t){this.lookAheadFuncsCache.set(e,t)}},class{initTreeBuilder(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=has(e,"nodeLocationTracking")?e.nodeLocationTracking:iD.nodeLocationTracking,this.outputCst){if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=setNodeLocationFull,this.setNodeLocationFromNode=setNodeLocationFull,this.cstPostRule=noop,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=noop,this.setNodeLocationFromNode=noop,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=setNodeLocationOnlyOffset,this.setNodeLocationFromNode=setNodeLocationOnlyOffset,this.cstPostRule=noop,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(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 <nodeLocationTracking> config option: "${e.nodeLocationTracking}"`)}else this.cstInvocationStateUpdate=noop,this.cstFinallyStateUpdate=noop,this.cstPostTerminal=noop,this.cstPostNonTerminal=noop,this.cstPostRule=noop}setInitialNodeLocationOnlyOffsetRecovery(e){e.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(e){let t=this.LA(1);e.location={startOffset:t.startOffset,startLine:t.startLine,startColumn:t.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(e){let t={name:e,children:Object.create(null)};this.setInitialNodeLocation(t),this.CST_STACK.push(t)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(e){let t=this.LA(0),r=e.location;r.startOffset<=t.startOffset==!0?(r.endOffset=t.endOffset,r.endLine=t.endLine,r.endColumn=t.endColumn):(r.startOffset=NaN,r.startLine=NaN,r.startColumn=NaN)}cstPostRuleOnlyOffset(e){let t=this.LA(0),r=e.location;r.startOffset<=t.startOffset==!0?r.endOffset=t.endOffset:r.startOffset=NaN}cstPostTerminal(e,t){let r=this.CST_STACK[this.CST_STACK.length-1];void 0===r.children[e]?r.children[e]=[t]:r.children[e].push(t),this.setNodeLocationFromToken(r.location,t)}cstPostNonTerminal(e,t){let r=this.CST_STACK[this.CST_STACK.length-1];void 0===r.children[t]?r.children[t]=[e]:r.children[t].push(e),this.setNodeLocationFromNode(r.location,e.location)}getBaseCstVisitorConstructor(){if(isUndefined(this.baseCstVisitorConstructor)){let e=function(e,t){let derivedConstructor=function(){};return defineNameProp(derivedConstructor,e+"BaseSemantics"),derivedConstructor.prototype={visit:function(e,t){if(e2(e)&&(e=e[0]),!isUndefined(e))return this[e.name](e.children,t)},validateVisitor:function(){let e=function(e,t){let r=function(e,t){let r=filter(t,t=>!1===isFunction(e[t])),i=map(r,t=>({msg:`Missing visitor method: <${t}> on ${e.constructor.name} CST Visitor.`,type:w.MISSING_METHOD,methodName:t}));return compact(i)}(e,t);return r}(this,t);if(!isEmpty(e)){let t=map(e,e=>e.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>:
905	${t.join("\n\n").replace(/\n/g,"\n	")}`)}}},derivedConstructor.prototype.constructor=derivedConstructor,derivedConstructor._RULE_NAMES=t,derivedConstructor}(this.className,keys(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(isUndefined(this.baseCstVisitorWithDefaultsConstructor)){let e=function(e,t,r){let derivedConstructor=function(){};defineNameProp(derivedConstructor,e+"BaseSemanticsWithDefaults");let i=Object.create(r.prototype);return forEach(t,e=>{i[e]=defaultVisit}),derivedConstructor.prototype=i,derivedConstructor.prototype.constructor=derivedConstructor,derivedConstructor}(this.className,keys(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){let e=this.RULE_STACK;return e[e.length-1]}getPreviousExplicitRuleShortName(){let e=this.RULE_STACK;return e[e.length-2]}getLastExplicitRuleOccurrenceIndex(){let e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]}},class{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(e){if(!0!==this.selfAnalysisDone)throw Error("Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):iF}LA(e){let t=this.currIdx+e;return t<0||this.tokVectorLength<=t?iF:this.tokVector[t]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(e){this.currIdx=e}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}},class{initRecognizerEngine(e,t){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={}
905,this.ruleShortNameIdx=256,this.tokenMatcher=tokenStructuredMatcherNoCategories,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},has(t,"serializedGrammar"))throw Error("The Parser's configuration can no longer contain a <serializedGrammar> property.\n	See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\n	For Further details.");if(e2(e)){if(isEmpty(e))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("number"==typeof e[0].startOffset)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(e2(e))this.tokensMap=reduce(e,(e,t)=>(e[t.name]=t,e),{});else if(has(e,"modes")&&every(flatten(values(e.modes)),isTokenType)){let t=flatten(values(e.modes)),r=uniq(t);this.tokensMap=reduce(r,(e,t)=>(e[t.name]=t,e),{})}else if(isObject(e))this.tokensMap=clone(e);else throw Error("<tokensDictionary> argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=ix;let r=has(e,"modes")?flatten(values(e.modes)):values(e),i=every(r,e=>isEmpty(e.categoryMatches));this.tokenMatcher=i?tokenStructuredMatcherNoCategories:tokenStructuredMatcher,augmentTokenTypes(values(this.tokensMap))}defineRule(e,t,r){let i;if(this.selfAnalysisDone)throw Error(`Grammar rule <${e}> may not be defined after the 'performSelfAnalysis' method has been called'
906Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);let a=has(r,"resyncEnabled")?r.resyncEnabled:iU.resyncEnabled,n=has(r,"re
906coveryValueFunc")?r.recoveryValueFunc:iU.recoveryValueFunc,s=this.ruleShortNameIdx<<12;this.ruleShortNameIdx++,this.shortRuleNameToFull[s]=e,this.fullRuleNameToShort[e]=s,i=!0===this.outputCst?function(...r){try{this.ruleInvocationStateUpdate(s,e,this.subruleIdx),t.apply(this,r);let i=this.CST_STACK[this.CST_STACK.length-1];return this.cstPostRule(i),i}catch(e){return this.invokeRuleCatch(e,a,n)}finally{this.ruleFinallyStateUpdate()}}:function(...r){try{return this.ruleInvocationStateUpdate(s,e,this.subruleIdx),t.apply(this,r)}catch(e){return this.invokeRuleCatch(e,a,n)}finally{this.ruleFinallyStateUpdate()}};let o=Object.assign(i,{ruleName:e,originalGrammarAction:t});return o}invokeRuleCatch(e,t,r){let i=1===this.RULE_STACK.length,a=t&&!this.isBackTracking()&&this.recoveryEnabled;if(isRecognitionException(e)){if(a){let t=this.findReSyncTokenType();if(this.isInCurrentRuleReSyncSet(t)){if(e.resyncedTokens=this.reSyncTo(t),!this.outputCst)return r(e);{let e=this.CST_STACK[this.CST_STACK.length-1];return e.recoveredNode=!0,e}}if(this.outputCst){let t=this.CST_STACK[this.CST_STACK.length-1];t.recoveredNode=!0,e.partialCstResult=t}throw e}if(i)return this.moveToTerminatedState(),r(e)}throw e}optionInternal(e,t){let r=this.getKeyForAutomaticLookahead(512,t);return this.optionInternalLogic(e,t,r)}optionInternalLogic(e,t,r){let i,a=this.getLaFuncFromCache(r);if("function"!=typeof e){i=e.DEF;let t=e.GATE;if(void 0!==t){let e=a;a=()=>t.call(this)&&e.call(this)}}else i=e;if(!0===a.call(this))return i.call(this)}atLeastOneInternal(e,t){let r=this.getKeyForAutomaticLookahead(1024,e);return this.atLeastOneInternalLogic(e,t,r)}atLeastOneInternalLogic(e,t,r){let i,a=this.getLaFuncFromCache(r);if("function"!=typeof t){i=t.DEF;let e=t.GATE;if(void 0!==e){let t=a;a=()=>e.call(this)&&t.call(this)}}else i=t;if(!0===a.call(this)){let e=this.doSingleRepetition(i);for(;!0===a.call(this)&&!0===e;)e=this.doSingleRepetition(i)}else throw this.raiseEarlyExitException(e,C.REPETITION_MANDATORY,t.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[e,t],a,1024,e,NextTerminalAfterAtLeastOneWalker)}atLeastOneSepFirstInternal(e,t){let r=this.getKeyForAutomaticLookahead(1536,e);this.atLeastOneSepFirstInternalLogic(e,t,r)}atLeastOneSepFirstInternalLogic(e,t,r){let i=t.DEF,a=t.SEP,n=this.getLaFuncFromCache(r);if(!0===n.call(this)){i.call(this);let separatorLookAheadFunc=()=>this.tokenMatcher(this.LA(1),a);for(;!0===this.tokenMatcher(this.LA(1),a);)this.CONSUME(a),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,a,separatorLookAheadFunc,i,NextTerminalAfterAtLeastOneSepWalker],separatorLookAheadFunc,1536,e,NextTerminalAfterAtLeastOneSepWalker)}else throw this.raiseEarlyExitException(e,C.REPETITION_MANDATORY_WITH_SEPARATOR,t.ERR_MSG)}manyInternal(e,t){let r=this.getKeyForAutomaticLookahead(768,e);return this.manyInternalLogic(e,t,r)}manyInternalLogic(e,t,r){let i,a=this.getLaFuncFromCache(r);if("function"!=typeof t){i=t.DEF;let e=t.GATE;if(void 0!==e){let t=a;a=()=>e.call(this)&&t.call(this)}}else i=t;let n=!0;for(;!0===a.call(this)&&!0===n;)n=this.doSingleRepetition(i);this.attemptInRepetitionRecovery(this.manyInternal,[e,t],a,768,e,NextTerminalAfterManyWalker,n)}manySepFirstInternal(e,t){let r=this.getKeyForAutomaticLookahead(1280,e);this.manySepFirstInternalLogic(e,t,r)}manySepFirstInternalLogic(e,t,r){let i=t.DEF,a=t.SEP,n=this.getLaFuncFromCache(r);if(!0===n.call(this)){i.call(this);let separatorLookAheadFunc=()=>this.tokenMatcher(this.LA(1),a);for(;!0===this.tokenMatcher(this.LA(1),a);)this.CONSUME(a),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,a,separatorLookAheadFunc,i,NextTerminalAfterManySepWalker],separatorLookAheadFunc,1280,e,NextTerminalAfterManySepWalker)}}repetitionSepSecondInternal(e,t,r,i,a){for(;r();)this.CONSUME(t),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,t,r,i,a],r,1536,e,a)}doSingleRepetition(e){let t=this.getLexerPosition();e.call(this);let r=this.getLexerPosition();return r>t}orInternal(e,t){let r=this.getKeyForAutomaticLookahead(256,t),i=e2(e)?e:e.DEF,a=this.getLaFuncFromCac
906he(r),n=a.call(this,i);if(void 0!==n){let e=i[n];return e.ALT.call(this)}this.raiseNoAltException(t,e.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),0===this.RULE_STACK.length&&!1===this.isAtEndOfInput()){let e=this.LA(1),t=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new NotAllInputParsedException(t,e))}}subruleInternal(e,t,r){let i;try{let a=void 0!==r?r.ARGS:void 0;return this.subruleIdx=t,i=e.apply(this,a),this.cstPostNonTerminal(i,void 0!==r&&void 0!==r.LABEL?r.LABEL:e.ruleName),i}catch(t){throw this.subruleInternalError(t,r,e.ruleName)}}subruleInternalError(e,t,r){throw isRecognitionException(e)&&void 0!==e.partialCstResult&&(this.cstPostNonTerminal(e.partialCstResult,void 0!==t&&void 0!==t.LABEL?t.LABEL:r),delete e.partialCstResult),e}consumeInternal(e,t,r){let i;try{let t=this.LA(1);!0===this.tokenMatcher(t,e)?(this.consumeToken(),i=t):this.consumeInternalError(e,t,r)}catch(r){i=this.consumeInternalRecovery(e,t,r)}
906return this.cstPostTerminal(void 0!==r&&void 0!==r.LABEL?r.LABEL:e.name,i),i}consumeInternalError(e,t,r){let i;let a=this.LA(0);throw i=void 0!==r&&r.ERR_MSG?r.ERR_MSG:this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:t,previous:a,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new MismatchedTokenException(i,t,a))}consumeInternalRecovery(e,t,r){if(this.recoveryEnabled&&"MismatchedTokenException"===r.name&&!this.isBackTracking()){let i=this.getFollowsForInRuleRecovery(e,t);try{return this.tryInRuleRecovery(e,i)}catch(e){if(e.name===iI)throw r;throw e}}else throw r}saveRecogState(){let e=this.errors,t=clone(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:t,CST_STACK:this.CST_STACK}}reloadRecogState(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK}ruleInvocationStateUpdate(e,t,r){this.RULE_OCCURRENCE_STACK.push(r),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(t)}isBackTracking(){return 0!==this.isBackTrackingStack.length}getCurrRuleFullName(){let e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]}shortRuleNameToFullName(e){return this.shortRuleNameToFull[e]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),ix)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}},class{ACTION(e){return e.call(this)}consume(e,t,r){return this.consumeInternal(t,e,r)}subrule(e,t,r){return this.subruleInternal(t,e,r)}option(e,t){return this.optionInternal(t,e)}or(e,t){return this.orInternal(t,e)}many(e,t){return this.manyInternal(e,t)}atLeastOne(e,t){return this.atLeastOneInternal(e,t)}CONSUME(e,t){return this.consumeInternal(e,0,t)}CONSUME1(e,t){return this.consumeInternal(e,1,t)}CONSUME2(e,t){return this.consumeInternal(e,2,t)}CONSUME3(e,t){return this.consumeInternal(e,3,t)}CONSUME4(e,t){return this.consumeInternal(e,4,t)}CONSUME5(e,t){return this.consumeInternal(e,5,t)}CONSUME6(e,t){return this.consumeInternal(e,6,t)}CONSUME7(e,t){return this.consumeInternal(e,7,t)}CONSUME8(e,t){return this.consumeInternal(e,8,t)}CONSUME9(e,t){return this.consumeInternal(e,9,t)}SUBRULE(e,t){return this.subruleInternal(e,0,t)}SUBRULE1(e,t){return this.subruleInternal(e,1,t)}SUBRULE2(e,t){return this.subruleInternal(e,2,t)}SUBRULE3(e,t){return this.subruleInternal(e,3,t)}SUBRULE4(e,t){return this.subruleInternal(e,4,t)}SUBRULE5(e,t){return this.subruleInternal(e,5,t)}SUBRULE6(e,t){return this.subruleInternal(e,6,t)}SUBRULE7(e,t){return this.subruleInternal(e,7,t)}SUBRULE8(e,t){return this.subruleInternal(e,8,t)}SUBRULE9(e,t){return this.subruleInternal(e,9,t)}OPTION(e){return this.optionInternal(e,0)}OPTION1(e){return this.optionInternal(e,1)}OPTION2(e){return this.optionInternal(e,2)}OPTION3(e){return this.optionInternal(e,3)}OPTION4(e){return this.optionInternal(e,4)}OPTION5(e){return this.optionInternal(e,5)}OPTION6(e){return this.optionInternal(e,6)}OPTION7(e){return this.optionInternal(e,7)}OPTION8(e){return this.optionInternal(e,8)}OPTION9(e){return this.optionInternal(e,9)}OR(e){return this.orInternal(e,0)}OR1(e){return this.orInternal(e,1)}OR2(e){return this.orInternal(e,2)}OR3(e){return this.orInternal(e,3)}OR4(e){return this.orInternal(e,4)}OR5(e){return this.orInternal(e,5)}OR6(e){return this.orInternal(e,6)}OR7(e){return this.orInternal(e,7)}OR8(e){return this.orInternal(e,8)}OR9(e){return this.orInternal(e,9)}MANY(e){this.manyInternal(0,e)}MANY1(e){this.manyInternal(1,e)}MANY2(e){this.manyInternal(2,e)}MANY3(e){this.manyInternal(3,e)}MANY4(e){this.manyInternal(4,e)}MANY5(e){this.manyInternal(5,e)}MANY6(e){this.manyInternal(6,e)}MANY7(e){this.manyInternal(7,e)}MANY8(e){this.manyInternal(8,e)}MANY9(e){this.manyInternal(9,e)}MANY_SEP(e){this.manySepFirstInternal(0,e)}MANY_SEP1(e){this.manySepFirstInternal(1,e)}MANY_SEP2(e){this.manySepFirstInternal(2,e)}MANY_SEP3(e){this.manySepFirstInternal(3,e)}MANY_SEP4(e){this.manySepFirstInternal(4,e)}MANY_SEP5(e){this.manySepFirstInternal(5,e)}MANY_SEP6(e){this.manySepFirstInternal(6,e)}MANY_SEP7(e){this.manySepFirstInternal(7,e)}MANY_SEP8(e){this.manySepFirstInternal(8,e)}MANY_SEP9(e){this.manySepFirstInternal(9,e)}AT_LEAST_ONE(e){this.atLeastOneInternal(0,e)}AT_LEAST_ONE1(e){return this.atLeastOneInternal(1,e)}AT_LEAST_ONE2(e){this.atLeastOneInternal(2,e)}AT_LEAST_ONE3(e){this.atLeastOneInternal(3,e)}AT_LEAST_ONE4(e){this.atLeastOneInternal(4,e)}AT_LEAST_ONE5(e){this.atLeastOneInternal(5,e)}AT_LEAST_ONE6(e){this.atLeastOneInternal(6,e)}AT_LEAST_ONE7(e){this.atLeastOneInternal(7,e)}AT_LEAST_ONE8(e){this.atLeastOneInternal(8,e)}AT_LEAST_ONE9(e){this.atLeastOneInternal(9,e)}AT_LEAST_ONE_SEP(e){this.atLeastOneSepFirstInternal(0,e)}AT_LEAST_ONE_SEP1(e){this.atLeastOneSepFirstInternal(1,e)}AT_LEAST_ONE_SEP2(e){this.atLeastOneSepFirstInternal(2,e)}AT_LEAST_ONE_SEP3(e){this.atLeastOneSepFirstInternal(3,e)}AT_LEAST_ONE_SEP4(e){this.atLeastOneSepFirstInternal(4,e)}AT_LEAST_ONE_SEP5(e){this.atLeastOneSepFirstInternal(5,e)}AT_LEAST_ONE_SEP6(e){this.atLeastOneSepFirstInternal(6,e)}AT_LEAST_ONE_SEP7(e){this.atLeastOneSepFirstInternal(7,e)}AT_LEAST_ONE_SEP8(e){this.atLeastOneSepFirstInternal(8,e)}AT_LEAST_ONE_SEP9(e){this.atLeastOneSepFirstInternal(9,e)}RULE(e,t,r=iU){if(includes(this.definedRulesNames,e)){let t=ib.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),r={message:t,type:I.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(r)}this.definedRulesNames.push(e);let i=this.defineRule(e,t,r);return this[e]=i,i}OVERRIDE_RULE(e,t,r=iU){let i=function(e,t,r){let i=[];return includes(t,e)||i.push({message:`Invalid rule override, rule: ->${e}<- cannot be overridden in the grammar: ->${r}<-as it is not defined in any of the super grammars `,type:I.INVALID_RULE_OVERRIDE,ruleName:e}),i}(e,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);let a=this.defineRule(e,t,r);return this[e]=a,a}BACKTRACK(e,t){return function(){this.isBackTrackingStack.push(1);let r=this.saveRecogState();try{return e.apply(this,t),!0}catch(e){if(isRecognitionException(e))return!1;throw e}finally{this.reloadRecogState(r),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return map(values(this.gastProductionsCache),function serializeProduction(e){function convertDefinition(e){return map(e,serializeProduction)}if(e instanceof NonTerminal){let t={type:"NonTerminal",name:e.nonTerminalName,idx:e.idx};return isString(e.label)&&(t.label=e.label),t}if(e instanceof Alternative)return{type:"Alternative",definition:convertDefinition(e.definition)};if(e instanceof Option)return{type:"Option",idx:e.idx,definition:convertDefinition(e.definition)};if(e instanceof RepetitionMandatory)return{type:"RepetitionMandatory",idx:e.idx,definition:convertDefinition(e.definition)};if(e instanceof RepetitionMandatoryWithSeparator)return{type:"RepetitionMandatoryWithSeparator",idx:e.idx,separator:serializeProduction(new Terminal({terminalType:e.separator})),definition:convertDefinition(e.definition)};if(e instanceof RepetitionWithSeparator)return{type:"RepetitionWithSeparator",idx:e.idx,separator:serializeProduction(new Terminal({terminalType:e.separator})),definition:convertDefinition(e.definition)};if(e instanceof Repetition)return{type:"Repetition",idx:e.idx,definition:convertDefinition(e.definition)};else if(e instanceof Alternation)return{type:"Alternation",idx:e.idx,definition:convertDefinition(e.definition)};else if(e instanceof Terminal){var t,r;let i={type:"Terminal",name:e.terminalType.name,label:isString((r=t=e.terminalType).LABEL)&&""!==r.LABEL?t.LABEL:t.name,idx:e.idx};isString(e.label)&&(i.terminalLabel=e.label);let a=e.terminalType.PATTERN;return e.terminalType.PATTERN&&(i.pattern=rZ(a)?a.source:a),i}else if(e instanceof Rule)return{type:"Rule",name:e.name,orgText:e.orgText,definition:convertDefinition(e.definition)};else throw Error("non exhaustive match")})}},class{initErrorHandler(e){this._errors=[],this.errorMessageProvider=has(e,"errorMessageProvider")?e.errorMessageProvider:iD.errorMessageProvider}SAVE_ERROR(e){if(isRecognitionException(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:clone(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return clone(this._errors)}set errors(e){this._errors=e}raiseEarlyExitException(e,t,r){let i=this.getCurrRuleFullName(),a=this.getGAstProductions()[i],n=getLookaheadPathsF
906orOptionalProd(e,a,t,this.maxLookahead),s=n[0],o=[];for(let e=1;e<=this.maxLookahead;e++)o.push(this.LA(e));let l=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:s,actual:o,previous:this.LA(0),customUserDescription:r,ruleName:i});throw this.SAVE_ERROR(new EarlyExitException(l,this.LA(1),this.LA(0)))}raiseNoAltException(e,t){let r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],a=getLookaheadPathsForOr(e,i,this.maxLookahead),n=[];for(let e=1;e<=this.maxLookahead;e++)n.push(this.LA(e));let s=this.LA(0),o=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:a,actual:n,previous:s,customUserDescription:t,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new NoViableAltException(o,this.LA(1),s))}},class{initContentAssist(){}computeContentAssist(e,t){let r=this.gastProductionsCache[e];if(isUndefined(r))throw Error(`Rule ->${e}<- does not exist in this grammar.`);return nextPossibleTokensAfter([r],t,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(e){let t=head(e.ruleStack),r=this.getGAstProductions(),i=r[t],a=new NextAfterTokenWalker(i,e).startWalking();return a}},class{initGastRecorder(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let e=0;e<10;e++){let t=e>0?e:"";this[`CONSUME${t}`]=function(t,r){return this.consumeInternalRecord(t,e,r)},this[`SUBRULE${t}`]=function(t,r){return this.subruleInternalRecord(t,e,r)},this[`OPTION${t}`]=function(t){return this.optionInternalRecord(t,e)},this[`OR${t}`]=function(t){return this.orInternalRecord(t,e)},this[`MANY${t}`]=function(t){this.manyInternalRecord(e,t)},this[`MANY_SEP${t}`]=function(t){this.manySepFirstInternalRecord(e,t)},this[`AT_LEAST_ONE${t}`]=function(t){this.atLeastOneInternalRecord(e,t)},this[`AT_LEAST_ONE_SEP${t}`]=function(t){this.atLeastOneSepFirstInternalRecord(e,t)}}this.consume=function(e,t,r){return this.consumeInternalRecord(t,e,r)},this.subrule=function(e,t,r){return this.subruleInternalRecord(t,e,r)},this.option=function(e,t){return this.optionInternalRecord(t,e)},this.or=function(e,t){return this.orInternalRecord(t,e)},this.many=function(e,t){this.manyInternalRecord(e,t)},this.atLeastOne=function(e,t){this.atLeastOneInternalRecord(e,t)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{for(let e=0;e<10;e++){let t=e>0?e:"";delete this[`CONSUME${t}`],delete this[`SUBRULE${t}`],delete this[`OPTION${t}`],delete this[`OR${t}`],delete this[`MANY${t}`],delete this[`MANY_SEP${t}`],delete this[`AT_LEAST_ONE${t}`],delete this[`AT_LEAST_ONE_SEP${t}`]}delete this.consume,delete this.subrule,delete this.option,delete this.or,delete this.many,delete this.atLeastOne,delete this.ACTION,delete this.BACKTRACK,delete this.LA})}ACTION_RECORD(e){}BACKTRACK_RECORD(e,t){return()=>!0}LA_RECORD(e){return iF}topLevelRuleRecord(e,t){try{let r=new Rule({definition:[],name:e});return r.name=e,this.recordingProdStack.push(r),t.call(this),this.recordingProdStack.pop(),r}catch(e){if(!0!==e.KNOWN_RECORDER_ERROR)try{e.message=e.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(t){throw e}throw e}}optionInternalRecord(e,t){return recordProd.call(this,Option,e,t)}atLeastOneInternalRecord(e,t){recordProd.call(this,RepetitionMandatory,t,e)}atLeastOneSepFirstInternalRecord(e,t){recordProd.call(this,RepetitionMandatoryWithSeparator,t,e,!0)}manyInternalRecord(e,t){recordProd.call(this,Repetition,t,e)}manySepFirstInternalRecord(e,t){recordProd.call(this,RepetitionWithSeparator,t,e,!0)}orInternalRecord(e,t){return recordOrProd.call(this,e,t)}subruleInternalRecord(e,t,r){if(assertMethodIdxIsValid(t),!e||!1===has(e,"ruleName")){let r=Error(`<SUBRULE${getIdxSuffix(t)}> argument is invalid expecting a Parser method reference but got: <${JSON.stringify(e)}>
907 inside top level rule: <${this.recordingProdStack[0].name}>`);throw r.KNOWN_RECORDER_ERROR=!0,r}let i=last(this.recordingProdStack),a=e.ruleName,n=new NonTerminal({idx:t,nonTerminalName:a,label:null==r?void 0:r.LABEL,referencedRule:void 0});return i.definition.push(n),this.outputCst?ik:iN}consumeInternalRecord(e,t,r){if(assertMethodIdxIsValid(t),!hasShortKeyProperty(e)){let r=Error(`<CONSUME${getIdxSuffix(t)}>
907 argument is invalid expecting a TokenType reference but got: <${JSON.stringify(e)}>
908 inside top level rule: <${this.recordingProdStack[0].name}>`);throw r.KNOWN_RECORDER_ERROR=!0,r}let i=last(this.recordingProdStack),a=new Terminal({idx:t,terminalType:e,label:null==r?void 0:r.LABEL});return i.definition.push(a),iL}},class{initPerformanceTracer(e){if(has(e,"traceInitPerf")){let t=e.traceInitPerf,r="number"==typeof t;this.traceInitMaxIdent=r?t:1/0,this.traceInitPerf=r?t>0:t}else this.traceInitMaxIdent=0,this.traceInitPerf=iD.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(e,t){if(!0!==this.traceInitPerf)return t();{this.traceInitIndent++;let r=Array(this.traceInitIndent+1).join("	");this.traceInitIndent<this.traceInitMaxIdent&&console.log(`${r}--> <${e}>`);let{time:i,value:a}=timer(t),n=i>10?console.warn:console.log;return this.traceInitIndent<this.traceInitMaxIdent&&n(`${r}<-- <${e}> time: ${i}ms`),this.traceInitIndent--,a}}}]);let WorkerPool=class WorkerPool{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){let t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return -1}_onMessage(e,t){let r=this.workersResolve[e];if(r&&r(t),this.queue.length){let{resolve:t,msg:r,transfer:i}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(r,i)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise(r=>{let i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<<i,this.workersResolve[i]=r,this.workers[i].postMessage(e,t)):this.queue.push({resolve:r,msg:e,transfer:t})})}dispose(){this.workers.forEach(e=>e.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}};let CompressedArrayTexture=class CompressedArrayTexture extends P.CompressedTexture{constructor(e,t,r,i,a,n){super(e,t,r,a,n),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=P.ClampToEdgeWrapping}};let iB=new WeakMap,iV=0,iz=class extends P.Loader{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new WorkerPool,this.workerSourceURL="",this.workerConfig=null,"undefined"!=typeof MSC_TRANSCODER&&console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.')}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}detectSupport(e){return this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},e.capabilities.isWebGL2&&(this.workerConfig.etc1Supported=!1),this}init(){if(!this.transcoderPending){let e=new P.FileLoader(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);let t=e.loadAsync("basis_transcoder.js"),r=new P.FileLoader(this.manager);r.setPath(this.transcoderPath),r.setResponseType("arraybuffer"),r.setWithCredentials(this.withCredentials);let i=r.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([t,i]).then(([e,t])=>{let r=iz.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(iz.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(iz.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(iz.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([i])),this.transcoderBinary=t,this.workerPool.setWorkerCreator(()=>{let e=new Worker(this.workerSourceURL),t=this.transcoderBinary.slice(0);return e.postMessage({type:"init",config:this.workerConfig,transcoderBinary:t},[t]),e})}),iV>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),iV++}return this.transcoderPending}load(e,t,r,i){if(null===this.workerConfig)throw Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");let a=new P.FileLoader(this.manager);a.setResponseType("arraybuffer"),a.setWithCredentials(this.withCredentials),a.load(e,e=>{if(iB.has(e)){let r=iB.get(e);
908return r.promise.then(t).catch(i)}this._createTexture(e).then(e=>t?t(e):null).catch(i)},r,i)}_createTextureFrom(e,t){let{mipmaps:r,width:i,height:a,format:n,type:s,error:o,dfdTransferFn:l,dfdFlags:c}=e;if("error"===s)return Promise.reject(o);let u=t.layerCount>1?new CompressedArrayTexture(r,i,a,t.layerCount,n,P.UnsignedByteType):new P.CompressedTexture(r,i,a,n,P.UnsignedByteType);return u.minFilter=1===r.length?P.LinearFilter:P.LinearMipmapLinearFilter,u.magFilter=P.LinearFilter,u.generateMipmaps=!1,u.needsUpdate=!0,"colorSpace"in u?u.colorSpace=l===N.FVZ?"srgb":"srgb-linear":u.encoding=l===N.FVZ?3001:3e3,u.premultiplyAlpha=!!(c&N.qHj),u}async _createTexture(e,t={}){let r=(0,N.ij3)(new Uint8Array(e));if(r.vkFormat!==N.kXg)return createDataTexture(r);let i=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:t},[e])).then(e=>this._createTextureFrom(e.data,r));return iB.set(e,{promise:i}),i}dispose(){return this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),iV--,this}};__publicField(iz,"BasisFormat",{ETC1S:0,UASTC_4x4:1}),__publicField(iz,"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(iz,"EngineFormat",{RGBAFormat:P.RGBAFormat,RGBA_ASTC_4x4_Format:P.RGBA_ASTC_4x4_Format,RGBA_BPTC_Format:P.RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:P.RGBA_ETC2_EAC_Format,RGBA_PVRTC_4BPPV1_Format:P.RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT5_Format:P.RGBA_S3TC_DXT5_Format,RGB_ETC1_Format:P.RGB_ETC1_Format,RGB_ETC2_Format:P.RGB_ETC2_Format,RGB_PVRTC_4BPPV1_Format:P.RGB_PVRTC_4BPPV1_Format,RGB_S3TC_DXT1_Format:P.RGB_S3TC_DXT1_Format}),__publicField(iz,"BasisWorker",function(){let e,t,r;let i=_EngineFormat,a=_TranscoderFormat,n=_BasisFormat;self.addEventListener("message",function(s){let c=s.data;switch(c.type){case"init":var u;e=c.config,u=c.transcoderBinary,t=new Promise(e=>{r={wasmBinary:u,onRuntimeInitialized:e},BASIS(r)}).then(()=>{r.initializeBasis(),void 0===r.KTX2File&&console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")});break;case"transcode":t.then(()=>{try{let{width:t,height:s,hasAlpha:u,mipmaps:h,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){let s=new r.KTX2File(new Uint8Array(t));function cleanup(){s.close(),s.delete()}if(!s.isValid())throw cleanup(),Error("THREE.KTX2Loader:	Invalid or unsupported .ktx2 file");let c=s.isUASTC()?n.UASTC_4x4:n.ETC1S,u=s.getWidth(),h=s.getHeight(),d=s.getLayers()||1,p=s.getLevels(),f=s.getHasAlpha(),m=s.getDFDTransferFunc(),g=s.getDFDFlags(),{transcoderFormat:v,engineFormat:y}=function(t,r,s,c){let u;let h=t===n.ETC1S?o:l;for(let i=0;i<h.length;i++){let a=h[i];if(e[a.if]&&a.basisFormat.includes(t)&&(!c||!(a.transcoderFormat.length<2))&&(!a.needsPowerOfTwo||isPowerOfTwo(r)&&isPowerOfTwo(s)))return{transcoderFormat:a.transcoderFormat[c?1:0],engineFormat:a.engineFormat[c?1:0]}}return console.warn("THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32."),{transcoderFormat:a.RGBA32,engineFormat:i.RGBAFormat}}(c,u,h,f);if(!u||!h||!p)throw cleanup(),Error("THREE.KTX2Loader:	Invalid texture");if(!s.startTranscoding())throw cleanup(),Error("THREE.KTX2Loader: .startTranscoding failed");let T=[];for(let e=0;e<p;e++){let t,r;let i=[];for(let a=0;a<d;a++){let n=s.getImageLevelInfo(e,a,0);t=n.origWidth<4?n.origWidth:n.width,r=n.origHeight<4?n.origHeight:n.height;let o=new Uint8Array(s.getImageTranscodedSizeInBytes(e,a,0,v)),l=s.transcodeImage(o,e,a,0,v,0,-1,-1);if(!l)throw cleanup(),Error("THREE.KTX2Loader: .transcodeImage failed.");i.push(o)}T.push({data:function(e){let t=0;for(let r=0;r<e.length;r++){let i=e[r];t+=i.byteLength}let r=new Uint8Array(t),i=0;for(let t=0;t<e.length;t++){let a=e[t];r.set(a,i),i+=a.byteLength}return r}(i),width:t,height:r})}return cleanup(),{width:u,height:h,hasAlpha:f,mipmaps:T,format:y,dfdTransferFn:m,dfdFlags:g}}(c.buffer),m=[];for(let e=0;e<h.length;++e)m.push(h[e].data.buffer);self.postMessage({type:"transcode",id:c.id,width:t,height:s,hasAlpha:u,mipmaps:h,format:d,dfdTransferFn:p,dfdFlags:f},m)}catch(e){console.error(e),self.postMessage({type:"error",id:c.id,error:e.message})}})}});let s=[{if:"astcSupported",basisFormat:[n.UASTC_4x4],transcoderFormat:[a.ASTC_4x4,a.ASTC_4x4],engineFormat:[i.RGBA_ASTC_4x4_Format,i.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.BC7_M5,a.BC7_M5],engineFormat:[i.RGBA_BPTC_Format,i.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.BC1,a.BC3],engineFormat:[i.RGB_S3TC_DXT1_Format,i.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.ETC1,a.ETC2],engineFormat:[i.RGB_ETC2_Format,i.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.ETC1],engineFormat:[i.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.PVRTC1_4_RGB,a.PVRTC1_4_RGBA],engineFormat:[i.RGB_PVRTC_4BPPV1_Format,i.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],o=s.sort(function(e,t){return e.priorityETC1S-t.priorityETC1S}),l=s.sort(function(e,t){return e.priorityUASTC-t.priorityUASTC});function isPowerOfTwo(e){return e<=2||(e&e-1)==0&&0!==e}});let ij={[N.qfi]:P.RGBAFormat,[N.IgZ]:P.RGBAFormat,[N.MCP]:P.RGBAFormat,[N.OmG]:P.RGBAFormat,[N.bWS]:P.RGFormat,[N.LR2]:P.RGFormat,[N.gJS]:P.RGFormat,[N.IJq]:P.RGFormat,[N.eQx]:P.RedFormat,[N.wOb]:P.RedFormat,[N.e1Y]:P.RedFormat,[N.tLr]:P.RedFormat},iG={[N.qfi]:P.FloatType,[N.IgZ]:P.HalfFloatType,[N.MCP]:P.UnsignedByteType,[N.OmG]:P.UnsignedByteType,[N.bWS]:P.FloatType,[N.LR2]:P.HalfFloatType,[N.gJS]:P.UnsignedByteType,[N.IJq]:P.UnsignedByteType,[N.eQx]:P.FloatType,[N.wOb]:P.HalfFloatType,[N.e1Y]:P.UnsignedByteType,[N.tLr]:P.UnsignedByteType},iW={[N.OmG]:3001,[N.IJq]:3001,[N.e1Y]:3001};async function createDataTexture(e){let t,r;let{vkFormat:i,pixelWidth:a,pixelHeight:n,pixelDepth:s}=e;if(void 0===ij[i])throw Error("THREE.KTX2Loader: Unsupported vkFormat.");let l=e.levels[0];if(e.supercompressionScheme===N.Oi)t=l.levelData;else if(e.supercompressionScheme===N.c6w)o||(o=new Promise(async e=>{let t=new O.L;await t.init(),e(t)})),t=(await o).decode(l.levelData,l.uncompressedByteLength);else throw Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");r=iG[i]===P.FloatType?new Float32Array(t.buffer,t.byteOffset,t.byteLength/Float32Array.BYTES_PER_ELEMENT):iG[i]===P.HalfFloatType?new Uint16Array(t.buffer,t.byteOffset,t.byteLength/Uint16Array.BYTES_PER_ELEMENT):t;
908let c=0===s?new P.DataTexture(r,a,n):new Data3DTexture(r,a,n,s);return c.type=iG[i],c.format=ij[i],c.encoding=iW[i]||3e3,c.needsUpdate=!0,Promise.resolve(c)}let iH=new WeakMap,iK=class extends P.Loader{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.workerConfig=null}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerLimit=e,this}detectSupport(e){return this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},this}load(e,t,r,i){let a=new P.FileLoader(this.manager);a.setResponseType("arraybuffer"),a.setWithCredentials(this.withCredentials);let n=new P.CompressedTexture;return a.load(e,e=>{if(iH.has(e)){let r=iH.get(e);return r.promise.then(t).catch(i)}this._createTexture([e]).then(function(e){n.copy(e),n.needsUpdate=!0,t&&t(n)}).catch(i)},r,i),n}parseInternalAsync(e){let{levels:t}=e,r=new Set;for(let e=0;e<t.length;e++)r.add(t[e].data.buffer);return this._createTexture(Array.from(r),{...e,lowLevel:!0})}_createTexture(e,t={}){let r,i;let a=0;for(let t=0;t<e.length;t++)a+=e[t].byteLength;let n=this._allocateWorker(a).then(a=>(r=a,i=this.workerNextTaskID++,new Promise((a,n)=>{r._callbacks[i]={resolve:a,reject:n},r.postMessage({type:"transcode",id:i,buffers:e,taskConfig:t},e)}))).then(e=>{let{mipmaps:t,width:r,height:i,format:a}=e,n=new P.CompressedTexture(t,r,i,a,P.UnsignedByteType);return n.minFilter=1===t.length?P.LinearFilter:P.LinearMipmapLinearFilter,n.magFilter=P.LinearFilter,n.generateMipmaps=!1,n.needsUpdate=!0,n});return n.catch(()=>!0).then(()=>{r&&i&&(r._taskLoad-=a,delete r._callbacks[i])}),iH.set(e[0],{promise:n}),n}_initTranscoder(){if(!this.transcoderPending){let e=new P.FileLoader(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);let t=new Promise((t,r)=>{e.load("basis_transcoder.js",t,void 0,r)}),r=new P.FileLoader(this.manager);r.setPath(this.transcoderPath),r.setResponseType("arraybuffer"),r.setWithCredentials(this.withCredentials);let i=new Promise((e,t)=>{r.load("basis_transcoder.wasm",e,void 0,t)});this.transcoderPending=Promise.all([t,i]).then(([e,t])=>{let r=iK.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(iK.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(iK.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(iK.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([i])),this.transcoderBinary=t})}return this.transcoderPending}_allocateWorker(e){return this._initTranscoder().then(()=>{if(this.workerPool.length<this.workerLimit){let e=new Worker(this.workerSourceURL);e._callbacks={},e._taskLoad=0,e.postMessage({type:"init",config:this.workerConfig,transcoderBinary:this.transcoderBinary}),e.onmessage=function(t){let r=t.data;switch(r.type){case"transcode":e._callbacks[r.id].resolve(r);break;case"error":e._callbacks[r.id].reject(r);break;default:console.error('THREE.BasisTextureLoader: Unexpected message, "'+r.type+'"')}},this.workerPool.push(e)}else this.workerPool.sort(function(e,t){return e._taskLoad>t._taskLoad?-1:1});let t=this.workerPool[this.workerPool.length-1];return t._taskLoad+=e,t})}dispose(){for(let e=0;e<this.workerPool.length;e++)this.workerPool[e].terminate();return this.workerPool.length=0,this}};__publicField(iK,"BasisFormat",{ETC1S:0,UASTC_4x4:1}),__publicField(iK,"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(iK,"EngineFormat",{RGBAFormat:P.RGBAFormat,RGBA_ASTC_4x4_Format:P.RGBA_ASTC_4x4_Format,RGBA_BPTC_Format:P.RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:P.RGBA_ETC2_EAC_Format,RGBA_PVRTC_4BPPV1_Format:P.RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT5_Format:P.RGBA_S3TC_DXT5_Format,RGB_ETC1_Format:P.RGB_ETC1_Format,RGB_ETC2_Format:P.RGB_ETC2_Format,RGB_PVRTC_4BPPV1_Format:P.RGB_PVRTC_4BPPV1_Format,RGB_S3TC_DXT1_Format:P.RGB_S3TC_DXT1_Format}),__publicField(iK,"BasisWorker",function(){let e,t,r;let i=_EngineFormat,a=_TranscoderFormat,n=_BasisFormat;onmessage=function(i){let a=i.data;switch(a.type){case"init":var s;e=a.config,s=a.transcoderBinary,t=new Promise(e=>{r={wasmBinary:s,onRuntimeInitialized:e},BASIS(r)}).then(()=>{r.initializeBasis()});break;case"transcode":t.then(()=>{try{let{width:e,height:t,hasAlpha:i,mipmaps:s,format:o}=a.taskConfig.lowLevel?function(e){let{basisFormat:t,width:i,height:a,hasAlpha:s}=e,{transcoderFormat:o,engineFormat:l}=getTranscoderFormat(t,i,a,s),c=r.getBytesPerBlockOrPixel(o);assert(r.isFormatSupported(o),"THREE.BasisTextureLoader: Unsupported format.");let u=[];
908if(t===n.ETC1S){let t=new r.LowLevelETC1SImageTranscoder,{endpointCount:i,endpointsData:a,selectorCount:n,selectorsData:l,tablesData:h}=e.globalData;try{let r;r=t.decodePalettes(i,a,n,l),assert(r,"THREE.BasisTextureLoader: decodePalettes() failed."),r=t.decodeTables(h),assert(r,"THREE.BasisTextureLoader: decodeTables() failed.");for(let i=0;i<e.levels.length;i++){let a=e.levels[i],n=e.globalData.imageDescs[i],l=getTranscodedImageByteLength(o,a.width,a.height),h=new Uint8Array(l);r=t.transcodeImage(o,h,l/c,a.data,getWidthInBlocks(o,a.width),getHeightInBlocks(o,a.height),a.width,a.height,a.index,n.rgbSliceByteOffset,n.rgbSliceByteLength,n.alphaSliceByteOffset,n.alphaSliceByteLength,n.imageFlags,s,!1,0,0),assert(r,"THREE.BasisTextureLoader: transcodeImage() failed for level "+a.index+"."),u.push({data:h,width:a.width,height:a.height})}}finally{t.delete()}}else for(let t=0;t<e.levels.length;t++){let i=e.levels[t],a=getTranscodedImageByteLength(o,i.width,i.height),n=new Uint8Array(a),l=r.transcodeUASTCImage(o,n,a/c,i.data,getWidthInBlocks(o,i.width),getHeightInBlocks(o,i.height),i.width,i.height,i.index,0,i.data.byteLength,0,s,!1,0,0,-1,-1);assert(l,"THREE.BasisTextureLoader: transcodeUASTCImage() failed for level "+i.index+"."),u.push({data:n,width:i.width,height:i.height})}return{width:i,height:a,hasAlpha:s,mipmaps:u,format:l}}(a.taskConfig):function(e){let t=new r.BasisFile(new Uint8Array(e)),i=t.isUASTC()?n.UASTC_4x4:n.ETC1S,a=t.getImageWidth(0,0),s=t.getImageHeight(0,0),o=t.getNumLevels(0),l=t.getHasAlpha();function cleanup(){t.close(),t.delete()}let{transcoderFormat:c,engineFormat:u}=getTranscoderFormat(i,a,s,l);if(!a||!s||!o)throw cleanup(),Error("THREE.BasisTextureLoader:	Invalid texture");if(!t.startTranscoding())throw cleanup(),Error("THREE.BasisTextureLoader: .startTranscoding failed");let h=[];for(let e=0;e<o;e++){let r=t.getImageWidth(0,e),i=t.getImageHeight(0,e),a=new Uint8Array(t.getImageTranscodedSizeInBytes(0,e,c)),n=t.transcodeImage(a,0,e,c,0,l);if(!n)throw cleanup(),Error("THREE.BasisTextureLoader: .transcodeImage failed.");h.push({data:a,width:r,height:i})}return cleanup(),{width:a,height:s,hasAlpha:l,mipmaps:h,format:u}}(a.buffers[0]),l=[];for(let e=0;e<s.length;++e)l.push(s[e].data.buffer);self.postMessage({type:"transcode",id:a.id,width:e,height:t,hasAlpha:i,mipmaps:s,format:o},l)}catch(e){console.error(e),self.postMessage({type:"error",id:a.id,error:e.message})}})}};let s=[{if:"astcSupported",basisFormat:[n.UASTC_4x4],transcoderFormat:[a.ASTC_4x4,a.ASTC_4x4],engineFormat:[i.RGBA_ASTC_4x4_Format,i.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.BC7_M5,a.BC7_M5],engineFormat:[i.RGBA_BPTC_Format,i.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.BC1,a.BC3],engineFormat:[i.RGB_S3TC_DXT1_Format,i.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.ETC1,a.ETC2],engineFormat:[i.RGB_ETC2_Format,i.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.ETC1,a.ETC1],engineFormat:[i.RGB_ETC1_Format,i.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[a.PVRTC1_4_RGB,a.PVRTC1_4_RGBA],engineFormat:[i.RGB_PVRTC_4BPPV1_Format,i.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],o=s.sort(function(e,t){return e.priorityETC1S-t.priorityETC1S}),l=s.sort(function(e,t){return e.priorityUASTC-t.priorityUASTC});function getTranscoderFormat(t,r,s,c){let u;let h=t===n.ETC1S?o:l;for(let i=0;i<h.length;i++){let a=h[i];if(e[a.if]&&a.basisFormat.includes(t)&&(!a.needsPowerOfTwo||isPowerOfTwo(r)&&isPowerOfTwo(s)))return{transcoderFormat:a.transcoderFormat[c?1:0],engineFormat:a.engineFormat[c?1:0]}}return console.warn("THREE.BasisTextureLoader: No suitable compressed texture format found. Decoding to RGBA32."),{transcoderFormat:a.RGBA32,engineFormat:i.RGBAFormat}}function assert(e,t){if(!e)throw Error(t)}function getWidthInBlocks(e,t){return Math.ceil(t/r.getFormatBlockWidth(e))}function getHeightInBlocks(e,t){return Math.ceil(t/r.getFormatBlockHeight(e))}function getTranscodedImageByteLength(e,t,i){let n=r.getBytesPerBlockOrPixel(e);
908if(r.formatIsUncompressed(e))return t*i*n;if(e===a.PVRTC1_4_RGB||e===a.PVRTC1_4_RGBA){let e=t+3&-4,r=i+3&-4;return(Math.max(8,e)*Math.max(8,r)*4+7)/8}return getWidthInBlocks(e,t)*getHeightInBlocks(e,i)*n}function isPowerOfTwo(e){return e<=2||(e&e-1)==0&&0!==e}}),Float32Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array;let i$=new P.Box3,iY=new P.Vector3;let LineSegmentsGeometry=class LineSegmentsGeometry extends P.InstancedBufferGeometry{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry",this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute("position",new P.Float32BufferAttribute([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute("uv",new P.Float32BufferAttribute([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){let t=this.attributes.instanceStart,r=this.attributes.instanceEnd;return void 0!==t&&(t.applyMatrix4(e),r.applyMatrix4(e),t.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let r=new P.InstancedInterleavedBuffer(t,6,1);return this.setAttribute("instanceStart",new P.InterleavedBufferAttribute(r,3,0)),this.setAttribute("instanceEnd",new P.InterleavedBufferAttribute(r,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let r=new P.InstancedInterleavedBuffer(t,6,1);return this.setAttribute("instanceColorStart",new P.InterleavedBufferAttribute(r,3,0)),this.setAttribute("instanceColorEnd",new P.InterleavedBufferAttribute(r,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new P.WireframeGeometry(e.geometry)),this}fromLineSegments(e){let t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new P.Box3);let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;void 0!==e&&void 0!==t&&(this.boundingBox.setFromBufferAttribute(e),i$.setFromBufferAttribute(t),this.boundingBox.union(i$))}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new P.Sphere),null===this.boundingBox&&this.computeBoundingBox();let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(void 0!==e&&void 0!==t){let r=this.boundingSphere.center;this.boundingBox.getCenter(r);let i=0;for(let a=0,n=e.count;a<n;a++)iY.fromBufferAttribute(e,a),i=Math.max(i,r.distanceToSquared(iY)),iY.fromBufferAttribute(t,a),i=Math.max(i,r.distanceToSquared(iY));this.boundingSphere.radius=Math.sqrt(i),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(e){return console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4()."),this.applyMatrix4(e)}};let LineGeometry=class LineGeometry extends LineSegmentsGeometry{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(e){let t=e.length-3,r=new Float32Array(2*t);for(let i=0;i<t;i+=3)r[2*i]=e[i],r[2*i+1]=e[i+1],r[2*i+2]=e[i+2],r[2*i+3]=e[i+3],r[2*i+4]=e[i+4],r[2*i+5]=e[i+5];return super.setPositions(r),this}setColors(e){let t=e.length-3,r=new Float32Array(2*t);for(let i=0;i<t;i+=3)r[2*i]=e[i],r[2*i+1]=e[i+1],r[2*i+2]=e[i+2],r[2*i+3]=e[i+3],r[2*i+4]=e[i+4],r[2*i+5]=e[i+5];return super.setColors(r),this}fromLine(e){let t=e.geometry;return this.setPositions(t.attributes.position.array),this}};let LineMaterial=class LineMaterial extends P.ShaderMaterial{constructor(e){super({type:"LineMaterial",uniforms:P.UniformsUtils.clone(P.UniformsUtils.merge([P.UniformsLib.common,P.UniformsLib.fog,{worldUnits:{value:1},linewidth:{value:1},resolution:{value:new P.Vector2(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}}])),vertexShader:`
909				#include <common>
910				#include <color_pars_vertex>
911				#include <fog_pars_vertex>
912				#include <logdepthbuf_pars_vertex>
913				#include <clipping_planes_pars_vertex>
914
915				uniform float linewidth;
916				uniform vec2 resolution;
917
918				attribute vec3 instanceStart;
919				attribute vec3 instanceEnd;
920
921				attribute vec3 instanceColorStart;
922				attribute vec3 instanceColorEnd;
923
924				#ifdef WORLD_UNITS
925
926					varying vec4 worldPos;
927					varying vec3 worldStart;
928					varying vec3 worldEnd;
929
930					#ifdef USE_DASH
931
932						varying vec2 vUv;
933
934					#endif
935
936				#else
937
938					varying vec2 vUv;
939
940				#endif
941
942				#ifdef USE_DASH
943
944					uniform float dashScale;
945					attribute float instanceDistanceStart;
946					attribute float instanceDistanceEnd;
947					varying float vLineDistance;
948
949				#endif
950
951				void trimSegment( const in vec4 start, inout vec4 end ) {
952
953					// trim end segment so it terminates between the camera plane and the near plane
954
955					// conservative estimate of the near plane
956					float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
957					float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
958					float nearEstimate = - 0.5 * b / a;
959
960					float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
961
962					end.xyz = mix( start.xyz, end.xyz, alpha );
963
964				}
965
966				void main() {
967
968					#ifdef USE_COLOR
969
970						vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
971
972					#endif
973
974					#ifdef USE_DASH
975
976						vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
977						vUv = uv;
978
979					#endif
980
981					float aspect = resolution.x / resolution.y;
982
983					// camera space
984					vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
985					vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
986
987					#ifdef WORLD_UNITS
988
989						worldStart = start.xyz;
990						worldEnd = end.xyz;
991
992					#else
993
994						vUv = uv;
995
996					#endif
997
998					// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
999					// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
1000					// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
1001					// perhaps there is a more elegant solution -- WestLangley
1002
1003					bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
1004
1005					if ( perspective ) {
1006
1007						if ( start.z < 0.0 && end.z >= 0.0 ) {
1008
1009							trimSegment( start, end );
1010
1011						} else if ( end.z < 0.0 && start.z >= 0.0 ) {
1012
1013							trimSegment( end, start );
1014
1015						}
1016
1017					}
1018
1019					// clip space
1020					vec4 clipStart = projectionMatrix * start;
1021					vec4 clipEnd = projectionMatrix * end;
1022
1023					// ndc space
1024					vec3 ndcStart = clipStart.xyz / clipStart.w;
1025					vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
1026
1027					// direction
1028					vec2 dir = ndcEnd.xy - ndcStart.xy;
1029
1030					// account for clip-space aspect ratio
1031					dir.x *= aspect;
1032					dir = normalize( dir );
1033
1034					#ifdef WORLD_UNITS
1035
1036						// get the offset direction as perpendicular to the view vector
1037						vec3 worldDir = normalize( end.xyz - start.xyz );
1038						vec3 offset;
1039						if ( position.y < 0.5 ) {
1040
1041							offset = normalize( cross( start.xyz, worldDir ) );
1042
1043						} else {
1044
1045							offset = normalize( cross( end.xyz, worldDir ) );
1046
1047						}
1048
1049						// sign flip
1050						if ( position.x < 0.0 ) offset *= - 1.0;
1051
1052						float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
1053
1054						// don't extend the line if we're rendering dashes because we
1055						// won't be rendering the endcaps
1056						#ifndef USE_DASH
1057
1058							// extend the line bounds to encompass  endcaps
1059							start.xyz += - worldDir * linewidth * 0.5;
1060							end.xyz += worldDir * linewidth * 0.5;
1061
1062							// shift the position of the quad so it hugs the forward edge of the line
1063							offset.xy -= dir * forwardOffset;
1064							offset.z += 0.5;
1065
1066						#endif
1067
1068						// endcaps
1069						if ( position.y > 1.0 || position.y < 0.0 ) {
1070
1071							offset.xy += dir * 2.0 * forwardOffset;
1072
1073						}
1074
1075						// adjust for linewidth
1076						offset *= linewidth * 0.5;
1077
1078						// set the world position
1079						worldPos = ( position.y < 0.5 ) ? start : end;
1080						worldPos.xyz += offset;
1081
1082						// project the worldpos
1083						vec4 clip = projectionMatrix * worldPos;
1084
1085						// shift the depth of the projected points so the line
1086						// segments overlap neatly
1087						vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
1088						clip.z = clipPose.z * clip.w;
1089
1090					#else
1091
1092						vec2 offset = vec2( dir.y, - dir.x );
1093						// undo aspect ratio adjustment
1094						dir.x /= aspect;
1095						offset.x /= aspect;
1096
1097						// sign flip
1098						if ( position.x < 0.0 ) offset *= - 1.0;
1099
1100						// endcaps
1101						if ( position.y < 0.0 ) {
1102
1103							offset += - dir;
1104
1105						} else if ( position.y > 1.0 ) {
1106
1107							offset += dir;
1108
1109						}
1110
1111						// adjust for linewidth
1112						offset *= linewidth;
1113
1114						// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
1115						offset /= resolution.y;
1116
1117						// select end
1118						vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
1119
1120						// back to clip space
1121						offset *= clip.w;
1122
1123						clip.xy += offset;
1124
1125					#endif
1126
1127					gl_Position = clip;
1128
1129					vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
1130
1131					#include <logdepthbuf_vertex>
1132					#include <clipping_planes_vertex>
1133					#include <fog_vertex>
1134
1135				}
1136			`,fragmentShader:`
1137				uniform vec3 diffuse;
1138				uniform float opacity;
1139				uniform float linewidth;
1140
1141				#ifdef USE_DASH
1142
1143					uniform float dashOffset;
1144					uniform float dashSize;
1145					uniform float gapSize;
1146
1147				#endif
1148
1149				varying float vLineDistance;
1150
1151				#ifdef WORLD_UNITS
1152
1153					varying vec4 worldPos;
1154					varying vec3 worldStart;
1155					varying vec3 worldEnd;
1156
1157					#ifdef USE_DASH
1158
1159						varying vec2 vUv;
1160
1161					#endif
1162
1163				#else
1164
1165					varying vec2 vUv;
1166
1167				#endif
1168
1169				#include <common>
1170				#include <color_pars_fragment>
1171				#include <fog_pars_fragment>
1172				#include <logdepthbuf_pars_fragment>
1173				#include <clipping_planes_pars_fragment>
1174
1175				vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
1176
1177					float mua;
1178					float mub;
1179
1180					vec3 p13 = p1 - p3;
1181					vec3 p43 = p4 - p3;
1182
1183					vec3 p21 = p2 - p1;
1184
1185					float d1343 = dot( p13, p43 );
1186					float d4321 = dot( p43, p21 );
1187					float d1321 = dot( p13, p21 );
1188					float d4343 = dot( p43, p43 );
1189					float d2121 = dot( p21, p21 );
1190
1191					float denom = d2121 * d4343 - d4321 * d4321;
1192
1193					float numer = d1343 * d4321 - d1321 * d4343;
1194
1195					mua = numer / denom;
1196					mua = clamp( mua, 0.0, 1.0 );
1197					mub = ( d1343 + d4321 * ( mua ) ) / d4343;
1198					mub = clamp( mub, 0.0, 1.0 );
1199
1200					return vec2( mua, mub );
1201
1202				}
1203
1204				void main() {
1205
1206					#include <clipping_planes_fragment>
1207
1208					#ifdef USE_DASH
1209
1210						if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
1211
1212						if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
1213
1214					#endif
1215
1216					float alpha = opacity;
1217
1218					#ifdef WORLD_UNITS
1219
1220						// Find the closest points on the view ray and the line segment
1221						vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
1222						vec3 lineDir = worldEnd - worldStart;
1223						vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
1224
1225						vec3 p1 = worldStart + lineDir * params.x;
1226						vec3 p2 = rayEnd * params.y;
1227						vec3 delta = p1 - p2;
1228						float len = length( delta );
1229						float norm = len / linewidth;
1230
1231						#ifndef USE_DASH
1232
1233							#ifdef USE_ALPHA_TO_COVERAGE
1234
1235								float dnorm = fwidth( norm );
1236								alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
1237
1238							#else
1239
1240								if ( norm > 0.5 ) {
1241
1242									discard;
1243
1244								}
1245
1246							#endif
1247
1248						#endif
1249
1250					#else
1251
1252						#ifdef USE_ALPHA_TO_COVERAGE
1253
1254							// artifacts appear on some hardware if a derivative is taken within a conditional
1255							float a = vUv.x;
1256							float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
1257							float len2 = a * a + b * b;
1258							float dlen = fwidth( len2 );
1259
1260							if ( abs( vUv.y ) > 1.0 ) {
1261
1262								alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
1263
1264							}
1265
1266						#else
1267
1268							if ( abs( vUv.y ) > 1.0 ) {
1269
1270								float a = vUv.x;
1271								float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
1272								float len2 = a * a + b * b;
1273
1274								if ( len2 > 1.0 ) discard;
1275
1276							}
1277
1278						#endif
1279
1280					#endif
1281
1282					vec4 diffuseColor = vec4( diffuse, alpha );
1283
1284					#include <logdepthbuf_fragment>
1285					#include <color_fragment>
1286
1287					gl_FragColor = vec4( diffuseColor.rgb, alpha );
1288
1289					#include <tonemapping_fragment>
1290					#include <${parseInt(P.REVISION.replace(/\D+/g,""))>=154?"colorspace_fragment":"encodings_fragment"}>
1291					#include <fog_fragment>
1292					#include <premultiplied_alpha_fragment>
1293
1294				}
1295			`,clipping:!0}),this.isLineMaterial=!0,Object.defineProperties(this,{color:{enumerable:!0,get:function(){return this.uniforms.diffuse.value},set:function(e){this.uniforms.diffuse.value=e}},worldUnits:{enumerable:!0,get:function(){return"WORLD_UNITS"in this.defines},set:function(e){!0===e?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}},linewidth:{enumerable:!0,get:function(){return this.uniforms.linewidth.value},set:function(e){this.uniforms.linewidth.value=e}},dashed:{enumerable:!0,get:function(){return"USE_DASH"in this.defines},set(e){!!e!="USE_DASH"in this.defines&&(this.needsUpdate=!0),!0===e?this.defines.USE_DASH="":delete this.defines.USE_DASH}},dashScale:{enumerable:!0,get:function(){return this.uniforms.dashScale.value},set:function(e){this.uniforms.dashScale.value=e}},dashSize:{enumerable:!0,get:function(){return this.uniforms.dashSize.value},set:function(e){this.uniforms.dashSize.value=e}},dashOffset:{enumerable:!0,get:function(){return this.uniforms.dashOffset.value},set:function(e){this.uniforms.dashOffset.value=e}},gapSize:{enumerable:!0,get:function(){return this.uniforms.gapSize.value},set:function(e){this.uniforms.gapSize.value=e}},opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(e){this.uniforms.opacity.value=e}},resolution:{enumerable:!0,get:function(){return this.uniforms.resolution.value},set:function(e){this.uniforms.resolution.value.copy(e)}},alphaToCoverage:{enumerable:!0,get:function(){return"USE_ALPHA_TO_COVERAGE"in this.defines},set:function(e){!!e!="USE_ALPHA_TO_COVERAGE"in this.defines&&(this.needsUpdate=!0),!0===e?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1)}}}),this.setValues(e)}};let iX=new P.Vector3,iZ=new P.Vector3,iq=new P.Vector4,iQ=new P.Vector4,iJ=new P.Vector4,i1=new P.Vector3,i0=new P.Matrix4,i2=new P.Line3,i3=new P.Vector3,i4=new P.Box3,i5=new P.
1295Sphere,i6=new P.Vector4;function getWorldSpaceHalfWidth(e,t,r){return i6.set(0,0,-t,1).applyMatrix4(e.projectionMatrix),i6.multiplyScalar(1/i6.w),i6.x=h/r.width,i6.y=h/r.height,i6.applyMatrix4(e.projectionMatrixInverse),i6.multiplyScalar(1/i6.w),Math.abs(Math.max(i6.x,i6.y))}let LineSegments2=class LineSegments2 extends P.Mesh{constructor(e=new LineSegmentsGeometry,t=new LineMaterial({color:16777215*Math.random()})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){let e=this.geometry,t=e.attributes.instanceStart,r=e.attributes.instanceEnd,i=new Float32Array(2*t.count);for(let e=0,a=0,n=t.count;e<n;e++,a+=2)iX.fromBufferAttribute(t,e),iZ.fromBufferAttribute(r,e),i[a]=0===a?0:i[a-1],i[a+1]=i[a]+iX.distanceTo(iZ);let a=new P.InstancedInterleavedBuffer(i,2,1);return e.setAttribute("instanceDistanceStart",new P.InterleavedBufferAttribute(a,1,0)),e.setAttribute("instanceDistanceEnd",new P.InterleavedBufferAttribute(a,1,1)),this}raycast(e,t){let r,i;let a=this.material.worldUnits,n=e.camera;null!==n||a||console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');let s=void 0!==e.params.Line2&&e.params.Line2.threshold||0;l=e.ray;let o=this.matrixWorld,d=this.geometry,p=this.material;if(h=p.linewidth+s,c=d.attributes.instanceStart,u=d.attributes.instanceEnd,null===d.boundingSphere&&d.computeBoundingSphere(),i5.copy(d.boundingSphere).applyMatrix4(o),a)r=.5*h;else{let e=Math.max(n.near,i5.distanceToPoint(l.origin));r=getWorldSpaceHalfWidth(n,e,p.resolution)}if(i5.radius+=r,!1!==l.intersectsSphere(i5)){if(null===d.boundingBox&&d.computeBoundingBox(),i4.copy(d.boundingBox).applyMatrix4(o),a)i=.5*h;else{let e=Math.max(n.near,i4.distanceToPoint(l.origin));i=getWorldSpaceHalfWidth(n,e,p.resolution)}i4.expandByScalar(i),!1!==l.intersectsBox(i4)&&(a?function(e,t){for(let r=0,i=c.count;r<i;r++){i2.start.fromBufferAttribute(c,r),i2.end.fromBufferAttribute(u,r);let i=new P.Vector3,a=new P.Vector3;l.distanceSqToSegment(i2.start,i2.end,a,i);let n=a.distanceTo(i)<.5*h;n&&t.push({point:a,pointOnLine:i,distance:l.origin.distanceTo(a),object:e,face:null,faceIndex:r,uv:null,uv2:null})}}(this,t):function(e,t,r){let i=t.projectionMatrix,a=e.material,n=a.resolution,s=e.matrixWorld,o=e.geometry,c=o.attributes.instanceStart,u=o.attributes.instanceEnd,d=-t.near;l.at(1,iJ),iJ.w=1,iJ.applyMatrix4(t.matrixWorldInverse),iJ.applyMatrix4(i),iJ.multiplyScalar(1/iJ.w),iJ.x*=n.x/2,iJ.y*=n.y/2,iJ.z=0,i1.copy(iJ),i0.multiplyMatrices(t.matrixWorldInverse,s);for(let t=0,a=c.count;t<a;t++){iq.fromBufferAttribute(c,t),iQ.fromBufferAttribute(u,t),iq.w=1,iQ.w=1,iq.applyMatrix4(i0),iQ.applyMatrix4(i0);let a=iq.z>d&&iQ.z>d;if(a)continue;if(iq.z>d){let e=iq.z-iQ.z,t=(iq.z-d)/e;iq.lerp(iQ,t)}else if(iQ.z>d){let e=iQ.z-iq.z,t=(iQ.z-d)/e;iQ.lerp(iq,t)}iq.applyMatrix4(i),iQ.applyMatrix4(i),iq.multiplyScalar(1/iq.w),iQ.multiplyScalar(1/iQ.w),iq.x*=n.x/2,iq.y*=n.y/2,iQ.x*=n.x/2,iQ.y*=n.y/2,i2.start.copy(iq),i2.start.z=0,i2.end.copy(iQ),i2.end.z=0;let o=i2.closestPointToPointParameter(i1,!0);i2.at(o,i3);let p=P.MathUtils.lerp(iq.z,iQ.z,o),f=p>=-1&&p<=1,m=i1.distanceTo(i3)<.5*h;if(f&&m){i2.start.fromBufferAttribute(c,t),i2.end.fromBufferAttribute(u,t),i2.start.applyMatrix4(s),i2.end.applyMatrix4(s);let i=new P.Vector3,a=new P.Vector3;l.distanceSqToSegment(i2.start,i2.end,a,i),r.push({point:a,pointOnLine:i,distance:l.origin.distanceTo(a),object:e,face:null,faceIndex:t,uv:null,uv2:null})}}}(this,n,t))}}};let Line2=class Line2 extends LineSegments2{constructor(e=new LineGeometry,t=new LineMaterial({color:16777215*Math.random()})){super(e,t),this.isLine2=!0,this.type="Line2"}}}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.