/** * @license * Copyright 2010-2025 Three.js Authors * SPDX-License-Identifier: MIT */ import{Color as e,Vector2 as t,Vector3 as r,Vector4 as s,Matrix2 as i,Matrix3 as n,Matrix4 as a,EventDispatcher as o,MathUtils as u,WebGLCoordinateSystem as l,WebGPUCoordinateSystem as d,ColorManagement as c,SRGBTransfer as h,NoToneMapping as p,StaticDrawUsage as g,InterleavedBuffer as m,InterleavedBufferAttribute as f,DynamicDrawUsage as y,NoColorSpace as b,Texture as x,UnsignedIntType as T,IntType as _,NearestFilter as v,Sphere as N,BackSide as S,DoubleSide as E,Euler as R,CubeTexture as A,CubeReflectionMapping as w,CubeRefractionMapping as C,TangentSpaceNormalMap as M,ObjectSpaceNormalMap as P,InstancedInterleavedBuffer as B,InstancedBufferAttribute as L,DataArrayTexture as F,FloatType as I,FramebufferTexture as D,LinearMipmapLinearFilter as U,DepthTexture as V,Material as O,NormalBlending as G,LineBasicMaterial as k,LineDashedMaterial as z,NoBlending as $,MeshNormalMaterial as H,SRGBColorSpace as W,WebGLCubeRenderTarget as q,BoxGeometry as j,Mesh as X,Scene as K,LinearFilter as Y,CubeCamera as Q,EquirectangularReflectionMapping as Z,EquirectangularRefractionMapping as J,AddOperation as ee,MixOperation as te,MultiplyOperation as re,MeshBasicMaterial as se,MeshLambertMaterial as ie,MeshPhongMaterial as ne,OrthographicCamera as ae,PerspectiveCamera as oe,RenderTarget as ue,LinearSRGBColorSpace as le,RGBAFormat as de,HalfFloatType as ce,CubeUVReflectionMapping as he,BufferGeometry as pe,BufferAttribute as ge,MeshStandardMaterial as me,MeshPhysicalMaterial as fe,MeshToonMaterial as ye,MeshMatcapMaterial as be,SpriteMaterial as xe,PointsMaterial as Te,ShadowMaterial as _e,Uint32BufferAttribute as ve,Uint16BufferAttribute as Ne,arrayNeedsUint32 as Se,Camera as Ee,DepthStencilFormat as Re,DepthFormat as Ae,UnsignedInt248Type as we,UnsignedByteType as Ce,Plane as Me,Object3D as Pe,warnOnce as Be,LinearMipMapLinearFilter as Le,Float32BufferAttribute as Fe,UVMapping as Ie,VSMShadowMap as De,LessCompare as Ue,RGFormat as Ve,BasicShadowMap as Oe,SphereGeometry as Ge,LinearMipmapNearestFilter as ke,NearestMipmapLinearFilter as ze,Float16BufferAttribute as $e,REVISION as He,ArrayCamera as We,PlaneGeometry as qe,FrontSide as je,CustomBlending as Xe,AddEquation as Ke,ZeroFactor as Ye,CylinderGeometry as Qe,Quaternion as Ze,WebXRController as Je,RAD2DEG as et,PCFShadowMap as tt,FrustumArray as rt,Frustum as st,DataTexture as it,RedIntegerFormat as nt,RedFormat as at,ShortType as ot,ByteType as ut,UnsignedShortType as lt,RGIntegerFormat as dt,RGBIntegerFormat as ct,RGBFormat as ht,RGBAIntegerFormat as pt,createCanvasElement as gt,ReverseSubtractEquation as mt,SubtractEquation as ft,OneMinusDstAlphaFactor as yt,OneMinusDstColorFactor as bt,OneMinusSrcAlphaFactor as xt,OneMinusSrcColorFactor as Tt,DstAlphaFactor as _t,DstColorFactor as vt,SrcAlphaSaturateFactor as Nt,SrcAlphaFactor as St,SrcColorFactor as Et,OneFactor as Rt,CullFaceNone as At,CullFaceBack as wt,CullFaceFront as Ct,MultiplyBlending as Mt,SubtractiveBlending as Pt,AdditiveBlending as Bt,NotEqualDepth as Lt,GreaterDepth as Ft,GreaterEqualDepth as It,EqualDepth as Dt,LessEqualDepth as Ut,LessDepth as Vt,AlwaysDepth as Ot,NeverDepth as Gt,UnsignedShort4444Type as kt,UnsignedShort5551Type as zt,UnsignedInt5999Type as $t,UnsignedInt101111Type as Ht,AlphaFormat as Wt,RGB_S3TC_DXT1_Format as qt,RGBA_S3TC_DXT1_Format as jt,RGBA_S3TC_DXT3_Format as Xt,RGBA_S3TC_DXT5_Format as Kt,RGB_PVRTC_4BPPV1_Format as Yt,RGB_PVRTC_2BPPV1_Format as Qt,RGBA_PVRTC_4BPPV1_Format as Zt,RGBA_PVRTC_2BPPV1_Format as Jt,RGB_ETC1_Format as er,RGB_ETC2_Format as tr,RGBA_ETC2_EAC_Format as rr,RGBA_ASTC_4x4_Format as sr,RGBA_ASTC_5x4_Format as ir,RGBA_ASTC_5x5_Format as nr,RGBA_ASTC_6x5_Format as ar,RGBA_ASTC_6x6_Format as or,RGBA_ASTC_8x5_Format as ur,RGBA_ASTC_8x6_Format as lr,RGBA_ASTC_8x8_Format as dr,RGBA_ASTC_10x5_Format as cr,RGBA_ASTC_10x6_Format as hr,RGBA_ASTC_10x8_Format as pr,RGBA_ASTC_10x10_Format as gr,RGBA_ASTC_12x10_Format as mr,RGBA_ASTC_12x12_Format as fr,RGBA_BPTC_Format as yr,RED_RGTC1_Format as br,SIGNED_RED_RGTC1_Format as xr,RED_GREEN_RGTC2_Format as Tr,SIGNED_RED_GREEN_RGTC2_Format as _r,MirroredRepeatWrapping as vr,ClampToEdgeWrapping as Nr,RepeatWrapping as Sr,NearestMipmapNearestFilter as Er,NotEqualCompare as Rr,GreaterCompare as Ar,GreaterEqualCompare as wr,EqualCompare as Cr,LessEqualCompare as Mr,AlwaysCompare as Pr,NeverCompare as Br,LinearTransfer as Lr,getByteLength as Fr,TimestampQuery as Ir,NotEqualStencilFunc as Dr,GreaterStencilFunc as Ur,GreaterEqualStencilFunc as Vr,EqualStencilFunc as Or,LessEqualStencilFunc as Gr,LessStencilFunc as kr,AlwaysStencilFunc as zr,NeverStencilFunc as $r,DecrementWrapStencilOp as Hr,IncrementWrapStencilOp as Wr,DecrementStencilOp as qr,IncrementStencilOp as jr,InvertStencilOp as Xr,ReplaceStencilOp as Kr,ZeroStencilOp as Yr,KeepStencilOp as Qr,MaxEquation as Zr,MinEquation as Jr,SpotLight as es,PointLight as ts,DirectionalLight as rs,RectAreaLight as ss,AmbientLight as is,HemisphereLight as ns,LightProbe as as,LinearToneMapping as os,ReinhardToneMapping as us,CineonToneMapping as ls,ACESFilmicToneMapping as ds,AgXToneMapping as cs,NeutralToneMapping as hs,Group as ps,Loader as gs,FileLoader as ms,MaterialLoader as fs,ObjectLoader as ys}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BatchedMesh,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,CameraHelper,CanvasTexture,CapsuleGeometry,CatmullRomCurve3,CircleGeometry,Clock,ColorKeyframeTrack,CompressedArrayTexture,CompressedCubeTexture,CompressedTexture,CompressedTextureLoader,ConeGeometry,ConstantAlphaFactor,ConstantColorFactor,Controls,CubeTextureLoader,CubicBezierCurve,CubicBezierCurve3,CubicInterpolant,CullFaceFrontBack,Curve,CurvePath,CustomToneMapping,Cylindrical,Data3DTexture,DataTextureLoader,DataUtils,DefaultLoadingManager,DetachedBindMode,DirectionalLightHelper,DiscreteInterpolant,DodecahedronGeometry,DynamicCopyUsage,DynamicReadUsage,EdgesGeometry,EllipseCurve,ExternalTexture,ExtrudeGeometry,Fog,FogExp2,GLBufferAttribute,GLSL1,GLSL3,GridHelper,HemisphereLightHelper,IcosahedronGeometry,ImageBitmapLoader,ImageLoader,ImageUtils,InstancedBufferGeometry,InstancedMesh,Int16BufferAttribute,Int32BufferAttribute,Int8BufferAttribute,Interpolant,InterpolateDiscrete,InterpolateLinear,InterpolateSmooth,InterpolationSamplingMode,InterpolationSamplingType,KeyframeTrack,LOD,LatheGeometry,Layers,Light,Line,Line3,LineCurve,LineCurve3,LineLoop,LineSegments,LinearInterpolant,LinearMipMapNearestFilter,LoaderUtils,LoadingManager,LoopOnce,LoopPingPong,LoopRepeat,MOUSE,MeshDepthMaterial,MeshDistanceMaterial,NearestMipMapLinearFilter,NearestMipMapNearestFilter,NormalAnimationBlendMode,NumberKeyframeTrack,OctahedronGeometry,OneMinusConstantAlphaFactor,OneMinusConstantColorFactor,PCFSoftShadowMap,Path,PlaneHelper,PointLightHelper,Points,PolarGridHelper,PolyhedronGeometry,PositionalAudio,PropertyBinding,PropertyMixer,QuadraticBezierCurve,QuadraticBezierCurve3,QuaternionKeyframeTrack,QuaternionLinearInterpolant,RGBADepthPacking,RGBDepthPacking,RGB_BPTC_SIGNED_Format,RGB_BPTC_UNSIGNED_Format,RGDepthPacking,RawShaderMaterial,Ray,Raycaster,RenderTarget3D,RingGeometry,ShaderMaterial,Shape,ShapeGeometry,ShapePath,ShapeUtils,Skeleton,SkeletonHelper,SkinnedMesh,Source,Spherical,SphericalHarmonics3,SplineCurve,SpotLightHelper,Sprite,StaticCopyUsage,StaticReadUsage,StereoCamera,StreamCopyUsage,StreamDrawUsage,StreamReadUsage,StringKeyframeTrack,TOUCH,TetrahedronGeometry,TextureLoader,TextureUtils,Timer,TorusGeometry,TorusKnotGeometry,Triangle,TriangleFanDrawMode,TriangleStripDrawMode,TrianglesDrawMode,TubeGeometry,Uint8BufferAttribute,Uint8ClampedBufferAttribute,Uniform,UniformsGroup,VectorKeyframeTrack,VideoFrameTexture,VideoTexture,WebGL3DRenderTarget,WebGLArrayRenderTarget,WebGLRenderTarget,WireframeGeometry,WrapAroundEnding,ZeroCurvatureEnding,ZeroSlopeEnding}from"./three.core.min.js";const bs=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],xs=new WeakMap;class Ts{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=bs,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:r,material:s,object:i}=e;if(t={material:this.getMaterialData(s),geometry:{id:r.id,attributes:this.getAttributesData(r.attributes),indexVersion:r.index?r.index.version:null,drawRange:{start:r.drawRange.start,count:r.drawRange.count}},worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:r,height:s}=e.context;t.bufferWidth=r,t.bufferHeight=s}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const r in e){const s=e[r];t[r]={version:s.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return null!==e.renderer.overrideNodes.modelViewMatrix||null!==e.renderer.overrideNodes.modelNormalViewMatrix}getMaterialData(e){const t={};for(const r of this.refreshUniforms){const s=e[r];null!=s&&("object"==typeof s&&void 0!==s.clone?!0===s.isTexture?t[r]={id:s.id,version:s.version}:t[r]=s.clone():t[r]=s)}return t}equals(e,t){const{object:r,material:s,geometry:i}=e,n=this.getRenderObjectData(e);if(!0!==n.worldMatrix.equals(r.matrixWorld))return n.worldMatrix.copy(r.matrixWorld),!1;const a=n.material;for(const e in a){const t=a[e],r=s[e];if(void 0!==t.equals){if(!1===t.equals(r))return t.copy(r),!1}else if(!0===r.isTexture){if(t.id!==r.id||t.version!==r.version)return t.id=r.id,t.version=r.version,!1}else if(t!==r)return a[e]=r,!1}if(a.transmission>0){const{width:t,height:r}=e.context;if(n.bufferWidth!==t||n.bufferHeight!==r)return n.bufferWidth=t,n.bufferHeight=r,!1}const o=n.geometry,u=i.attributes,l=o.attributes,d=Object.keys(l),c=Object.keys(u);if(o.id!==i.id)return o.id=i.id,!1;if(d.length!==c.length)return n.geometry.attributes=this.getAttributesData(u),!1;for(const e of d){const t=l[e],r=u[e];if(void 0===r)return delete l[e],!1;if(t.version!==r.version)return t.version=r.version,!1}const h=i.index,p=o.indexVersion,g=h?h.version:null;if(p!==g)return o.indexVersion=g,!1;if(o.drawRange.start!==i.drawRange.start||o.drawRange.count!==i.drawRange.count)return o.drawRange.start=i.drawRange.start,o.drawRange.count=i.drawRange.count,!1;if(n.morphTargetInfluences){let e=!1;for(let t=0;t>>16,2246822507),r^=Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&s)+(r>>>0)}const vs=e=>_s(e),Ns=e=>_s(e),Ss=(...e)=>_s(e);function Es(e,t=!1){const r=[];!0===e.isNode&&r.push(e.id);for(const{property:s,childNode:i}of Rs(e))r.push(_s(s.slice(0,-4)),i.getCacheKey(t));return _s(r)}function*Rs(e,t=!1){for(const r of Object.getOwnPropertyNames(e)){if(!0===r.startsWith("_"))continue;const s=e[r];if(!0===Array.isArray(s))for(let e=0;ee.charCodeAt(0)).buffer}var Os=Object.freeze({__proto__:null,arrayBufferToBase64:Us,base64ToArrayBuffer:Vs,getByteBoundaryFromType:Ls,getCacheKey:Es,getDataFromObject:Ds,getLengthFromType:Ps,getMemoryLengthFromType:Bs,getNodeChildren:Rs,getTypeFromLength:Cs,getTypedArrayFromType:Ms,getValueFromType:Is,getValueType:Fs,hash:Ss,hashArray:Ns,hashString:vs});const Gs={VERTEX:"vertex",FRAGMENT:"fragment"},ks={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},zs={BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},$s={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},Hs=["fragment","vertex"],Ws=["setup","analyze","generate"],qs=[...Hs,"compute"],js=["x","y","z","w"],Xs={analyze:"setup",generate:"analyze"};let Ks=0;class Ys extends o{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=ks.NONE,this.updateBeforeType=ks.NONE,this.updateAfterType=ks.NONE,this.uuid=u.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Ks++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,ks.FRAME)}onRenderUpdate(e){return this.onUpdate(e,ks.RENDER)}onObjectUpdate(e){return this.onUpdate(e,ks.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of Rs(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Ss(Es(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let r=0;for(const e of this.getChildren())t["node"+r++]=e;return t.outputNode||null}analyze(e,t=null){const r=e.increaseUsage(this);if(!0===this.parents){const r=e.getDataFromNode(this,"any");r.stages=r.stages||{},r.stages[e.shaderStage]=r.stages[e.shaderStage]||[],r.stages[e.shaderStage].push(t)}if(1===r){const t=e.getNodeProperties(this);for(const r of Object.values(t))r&&!0===r.isNode&&r.build(e,this)}}generate(e,t){const{outputNode:r}=e.getNodeProperties(this);if(r&&!0===r.isNode)return r.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const r=this.getShared(e);if(this!==r)return r.build(e,t);const s=e.getDataFromNode(this);s.buildStages=s.buildStages||{},s.buildStages[e.buildStage]=!0;const i=Xs[e.buildStage];if(i&&!0!==s.buildStages[i]){const t=e.getBuildStage();e.setBuildStage(i),this.build(e),e.setBuildStage(t)}e.addNode(this),e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const r of Object.values(t))if(r&&!0===r.isNode){if(!0===r.parents){const t=e.getNodeProperties(r);t.parents=t.parents||[],t.parents.push(this)}r.build(e)}}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(1===this.generate.length){const r=this.getNodeType(e),s=e.getDataFromNode(this);n=s.snippet,void 0===n?void 0===s.generated?(s.generated=!0,n=this.generate(e)||"",s.snippet=n):(console.warn("THREE.Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==s.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,r,t)}else n=this.generate(e,t)||"";""===n&&null!==t&&"void"!==t&&"OutputType"!==t&&(console.error(`THREE.TSL: Invalid generated code, expected a "${t}".`),n=e.generateConst(t))}return e.removeChain(this),e.addSequentialNode(this),n}getSerializeChildren(){return Rs(this)}serialize(e){const t=this.getSerializeChildren(),r={};for(const{property:s,index:i,childNode:n}of t)void 0!==i?(void 0===r[s]&&(r[s]=Number.isInteger(i)?[]:{}),r[s][i]=n.toJSON(e.meta).uuid):r[s]=n.toJSON(e.meta).uuid;Object.keys(r).length>0&&(e.inputNodes=r)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const r in e.inputNodes)if(Array.isArray(e.inputNodes[r])){const s=[];for(const i of e.inputNodes[r])s.push(t[i]);this[r]=s}else if("object"==typeof e.inputNodes[r]){const s={};for(const i in e.inputNodes[r]){const n=e.inputNodes[r][i];s[i]=t[n]}this[r]=s}else{const s=e.inputNodes[r];this[r]=t[s]}}}toJSON(e){const{uuid:t,type:r}=this,s=void 0===e||"string"==typeof e;s&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function n(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(void 0===i&&(i={uuid:t,type:r,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==s&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),s){const t=n(e.textures),r=n(e.images),s=n(e.nodes);t.length>0&&(i.textures=t),r.length>0&&(i.images=r),s.length>0&&(i.nodes=s)}return i}}class Qs extends Ys{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Zs extends Ys{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let r=null;for(const s of this.convertTo.split("|"))null!==r&&e.getTypeLength(t)!==e.getTypeLength(s)||(r=s);return r}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const r=this.node,s=this.getNodeType(e),i=r.build(e,s);return e.format(i,s,t)}}class Js extends Ys{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const r=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(void 0!==s.propertyName)return e.format(s.propertyName,r,t);if("void"!==r&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,r),n=e.getVarFromNode(this,null,r),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${i}`,this),s.snippet=i,s.propertyName=a,e.format(s.propertyName,r,t)}}return super.build(e,t)}}class ei extends Js{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,r)=>t+e.getTypeLength(r.getNodeType(e)),0))}generate(e,t){const r=this.getNodeType(e),s=e.getTypeLength(r),i=this.nodes,n=e.getComponentType(r),a=[];let o=0;for(const t of i){if(o>=s){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${r}()' type.`);break}let i,u=t.getNodeType(e),l=e.getTypeLength(u);o+l>s&&(console.error(`THREE.TSL: Length of '${r}()' data exceeds maximum length of output type.`),l=s-o,u=e.getTypeFromLength(l)),o+=l,i=t.build(e,u);if(e.getComponentType(u)!==n){const t=e.getTypeFromLength(l,n);i=e.format(i,u,t)}a.push(i)}const u=`${e.getType(r)}( ${a.join(", ")} )`;return e.format(u,r,t)}}const ti=js.join("");class ri extends Ys{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(js.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const r=this.node,s=e.getTypeLength(r.getNodeType(e));let i=null;if(s>1){let n=null;this.getVectorLength()>=s&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=r.build(e,n);i=this.components.length===s&&this.components===ti.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else i=r.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class si extends Js{static get type(){return"SetNode"}constructor(e,t,r){super(),this.sourceNode=e,this.components=t,this.targetNode=r}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:r,targetNode:s}=this,i=this.getNodeType(e),n=e.getComponentType(s.getNodeType(e)),a=e.getTypeFromLength(r.length,n),o=s.build(e,a),u=t.build(e,i),l=e.getTypeLength(i),d=[];for(let e=0;e(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");Ys.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==li?li.assign(this,...e):console.error("THREE.TSL: No stack defined for assign operation. Make sure the assign is inside a Fn()."),this;{const t=di.get("assign");return this.add(t(...e))}},Ys.prototype.toVarIntent=function(){return this},Ys.prototype.get=function(e){return new ui(this,e)};const pi={};function gi(e,t,r){pi[e]=pi[t]=pi[r]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new ri(this,e),this._cache[e]=t),t},set(t){this[e].assign(Gi(t))}};const s=e.toUpperCase(),i=t.toUpperCase(),n=r.toUpperCase();Ys.prototype["set"+s]=Ys.prototype["set"+i]=Ys.prototype["set"+n]=function(t){const r=hi(e);return new si(this,r,Gi(t))},Ys.prototype["flip"+s]=Ys.prototype["flip"+i]=Ys.prototype["flip"+n]=function(){const t=hi(e);return new ii(this,t)}}const mi=["x","y","z","w"],fi=["r","g","b","a"],yi=["s","t","p","q"];for(let e=0;e<4;e++){let t=mi[e],r=fi[e],s=yi[e];gi(t,r,s);for(let i=0;i<4;i++){t=mi[e]+mi[i],r=fi[e]+fi[i],s=yi[e]+yi[i],gi(t,r,s);for(let n=0;n<4;n++){t=mi[e]+mi[i]+mi[n],r=fi[e]+fi[i]+fi[n],s=yi[e]+yi[i]+yi[n],gi(t,r,s);for(let a=0;a<4;a++)t=mi[e]+mi[i]+mi[n]+mi[a],r=fi[e]+fi[i]+fi[n]+fi[a],s=yi[e]+yi[i]+yi[n]+yi[a],gi(t,r,s)}}}for(let e=0;e<32;e++)pi[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Qs(this,new oi(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(Gi(t))}};Object.defineProperties(Ys.prototype,pi);const bi=new WeakMap,xi=function(e,t=null){for(const r in e)e[r]=Gi(e[r],t);return e},Ti=function(e,t=null){const r=e.length;for(let s=0;so?(console.error(`THREE.TSL: "${r}" parameter length exceeds limit.`),t.slice(0,o)):t}return null===t?n=(...t)=>i(new e(...$i(l(t)))):null!==r?(r=Gi(r),n=(...s)=>i(new e(t,...$i(l(s)),r))):n=(...r)=>i(new e(t,...$i(l(r)))),n.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),n),n.setName=e=>(u=e,n),n},vi=function(e,...t){return Gi(new e(...$i(t)))};class Ni extends Ys{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:r}=this,s=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",n=i||"default";if(s[n])return s[n];const a=e.subBuildFn;e.subBuildFn=i;let o=null;if(t.layout){let s=bi.get(e.constructor);void 0===s&&(s=new WeakMap,bi.set(e.constructor,s));let i=s.get(t);void 0===i&&(i=Gi(e.buildFunctionNode(t)),s.set(t,i)),e.addInclude(i);const n=r?function(e){let t;zi(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(r):null;o=Gi(i.call(n))}else{const s=new Proxy(e,{get:(e,t,r)=>{let s;return s=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,r),s}}),i=r?function(e){let t=0;return zi(e),new Proxy(e,{get:(r,s,i)=>{let n;if("length"===s)return n=e.length,n;if(Symbol.iterator===s)n=function*(){for(const t of e)yield Gi(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const r=e[0];n=void 0===r[s]?r[t++]:Reflect.get(r,s,i)}else e[0]instanceof Ys&&(n=void 0===e[s]?e[t++]:Reflect.get(e,s,i));else n=Reflect.get(r,s,i);n=Gi(n)}return n}})}(r):null,n=Array.isArray(r)?r.length>0:null!==r,a=t.jsFunc,u=n||a.length>1?a(i,s):a(s);o=Gi(u)}return e.subBuildFn=a,t.once&&(s[n]=o),o}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),r=e.getSubBuildOutput(this);return t[r]=t[r]||this.setupOutput(e),t[r].subBuild=e.getClosestSubBuild(this),t[r]}build(e,t=null){let r=null;const s=e.getBuildStage(),i=e.getNodeProperties(this),n=e.getSubBuildOutput(this),a=this.getOutputNode(e);if("setup"===s){const t=e.getSubBuildProperty("initialized",this);if(!0!==i[t]&&(i[t]=!0,i[n]=this.getOutputNode(e),i[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const r=e.getDataFromNode(t,"any");r.subBuilds=r.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)r.subBuilds.add(e)}r=i[n]}else"analyze"===s?a.build(e,t):"generate"===s&&(r=a.build(e,t)||"");return r}}class Si extends Ys{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return Gi(new Ni(this,e))}setup(){return this.call()}}const Ei=[!1,!0],Ri=[0,1,2,3],Ai=[-1,-2],wi=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],Ci=new Map;for(const e of Ei)Ci.set(e,new oi(e));const Mi=new Map;for(const e of Ri)Mi.set(e,new oi(e,"uint"));const Pi=new Map([...Mi].map(e=>new oi(e.value,"int")));for(const e of Ai)Pi.set(e,new oi(e,"int"));const Bi=new Map([...Pi].map(e=>new oi(e.value)));for(const e of wi)Bi.set(e,new oi(e));for(const e of wi)Bi.set(-e,new oi(-e));const Li={bool:Ci,uint:Mi,ints:Pi,float:Bi},Fi=new Map([...Ci,...Bi]),Ii=(e,t)=>Fi.has(e)?Fi.get(e):!0===e.isNode?e:new oi(e,t),Di=function(e,t=null){return(...r)=>{for(const t of r)if(void 0===t)return console.error(`THREE.TSL: Invalid parameter for the type "${e}".`),Gi(new oi(0,e));if((0===r.length||!["bool","float","int","uint"].includes(e)&&r.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(r=[Is(e,...r)]),1===r.length&&null!==t&&t.has(r[0]))return ki(t.get(r[0]));if(1===r.length){const t=Ii(r[0],e);return t.nodeType===e?ki(t):ki(new Zs(t,e))}const s=r.map(e=>Ii(e));return ki(new ei(s,e))}},Ui=e=>"object"==typeof e&&null!==e?e.value:e,Vi=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function Oi(e,t){return new Si(e,t)}const Gi=(e,t=null)=>function(e,t=null){const r=Fs(e);return"node"===r?e:null===t&&("float"===r||"boolean"===r)||r&&"shader"!==r&&"string"!==r?Gi(Ii(e,t)):"shader"===r?e.isFn?e:Ki(e):e}(e,t),ki=(e,t=null)=>Gi(e,t).toVarIntent(),zi=(e,t=null)=>new xi(e,t),$i=(e,t=null)=>new Ti(e,t),Hi=(e,t=null,r=null,s=null)=>new _i(e,t,r,s),Wi=(e,...t)=>new vi(e,...t),qi=(e,t=null,r=null,s={})=>new _i(e,t,r,{intent:!0,...s});let ji=0;class Xi extends Ys{constructor(e,t=null){super();let r=null;null!==t&&("object"==typeof t?r=t.return:("string"==typeof t?r=t:console.error("THREE.TSL: Invalid layout type."),t=null)),this.shaderNode=new Oi(e,r),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const r={name:"fn"+ji++,type:t,inputs:[]};for(const t in e)"return"!==t&&r.inputs.push({name:t,type:e[t]});e=r}return this.shaderNode.setLayout(e),this}getNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return console.error('THREE.TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".'),e.generateConst(t)}}function Ki(e,t=null){const r=new Xi(e,t);return new Proxy(()=>{},{apply:(e,t,s)=>r.call(...s),get:(e,t,s)=>Reflect.get(r,t,s),set:(e,t,s,i)=>Reflect.set(r,t,s,i)})}const Yi=e=>{li=e},Qi=()=>li,Zi=(...e)=>li.If(...e);function Ji(e){return li&&li.add(e),e}ci("toStack",Ji);const en=new Di("color"),tn=new Di("float",Li.float),rn=new Di("int",Li.ints),sn=new Di("uint",Li.uint),nn=new Di("bool",Li.bool),an=new Di("vec2"),on=new Di("ivec2"),un=new Di("uvec2"),ln=new Di("bvec2"),dn=new Di("vec3"),cn=new Di("ivec3"),hn=new Di("uvec3"),pn=new Di("bvec3"),gn=new Di("vec4"),mn=new Di("ivec4"),fn=new Di("uvec4"),yn=new Di("bvec4"),bn=new Di("mat2"),xn=new Di("mat3"),Tn=new Di("mat4");ci("toColor",en),ci("toFloat",tn),ci("toInt",rn),ci("toUint",sn),ci("toBool",nn),ci("toVec2",an),ci("toIVec2",on),ci("toUVec2",un),ci("toBVec2",ln),ci("toVec3",dn),ci("toIVec3",cn),ci("toUVec3",hn),ci("toBVec3",pn),ci("toVec4",gn),ci("toIVec4",mn),ci("toUVec4",fn),ci("toBVec4",yn),ci("toMat2",bn),ci("toMat3",xn),ci("toMat4",Tn);const _n=Hi(Qs).setParameterLength(2),vn=(e,t)=>Gi(new Zs(Gi(e),t));ci("element",_n),ci("convert",vn);ci("append",e=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),Ji(e)));class Nn extends Ys{static get type(){return"PropertyNode"}constructor(e,t=null,r=!1){super(e),this.name=t,this.varying=r,this.isPropertyNode=!0,this.global=!0}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Sn=(e,t)=>Gi(new Nn(e,t)),En=(e,t)=>Gi(new Nn(e,t,!0)),Rn=Wi(Nn,"vec4","DiffuseColor"),An=Wi(Nn,"vec3","EmissiveColor"),wn=Wi(Nn,"float","Roughness"),Cn=Wi(Nn,"float","Metalness"),Mn=Wi(Nn,"float","Clearcoat"),Pn=Wi(Nn,"float","ClearcoatRoughness"),Bn=Wi(Nn,"vec3","Sheen"),Ln=Wi(Nn,"float","SheenRoughness"),Fn=Wi(Nn,"float","Iridescence"),In=Wi(Nn,"float","IridescenceIOR"),Dn=Wi(Nn,"float","IridescenceThickness"),Un=Wi(Nn,"float","AlphaT"),Vn=Wi(Nn,"float","Anisotropy"),On=Wi(Nn,"vec3","AnisotropyT"),Gn=Wi(Nn,"vec3","AnisotropyB"),kn=Wi(Nn,"color","SpecularColor"),zn=Wi(Nn,"float","SpecularF90"),$n=Wi(Nn,"float","Shininess"),Hn=Wi(Nn,"vec4","Output"),Wn=Wi(Nn,"float","dashSize"),qn=Wi(Nn,"float","gapSize"),jn=Wi(Nn,"float","pointWidth"),Xn=Wi(Nn,"float","IOR"),Kn=Wi(Nn,"float","Transmission"),Yn=Wi(Nn,"float","Thickness"),Qn=Wi(Nn,"float","AttenuationDistance"),Zn=Wi(Nn,"color","AttenuationColor"),Jn=Wi(Nn,"float","Dispersion");class ea extends Ys{static get type(){return"UniformGroupNode"}constructor(e,t=!1,r=1){super("string"),this.name=e,this.shared=t,this.order=r,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const ta=e=>new ea(e),ra=(e,t=0)=>new ea(e,!0,t),sa=ra("frame"),ia=ra("render"),na=ta("object");class aa extends ni{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=na}setName(e){return this.name=e,this}label(e){return console.warn('THREE.TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const r=e(t,this);void 0!==r&&(this.value=r)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const r=this.getNodeType(e),s=this.getUniformHash(e);let i=e.getNodeFromHash(s);void 0===i&&(e.setHashNode(this,s),i=this);const n=i.getInputType(e),a=e.getUniformFromNode(i,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let u=o;if("bool"===r){const t=e.getDataFromNode(this);let s=t.propertyName;if(void 0===s){const i=e.getVarFromNode(this,null,"bool");s=e.getPropertyName(i),t.propertyName=s,u=e.format(o,n,r),e.addLineFlowCode(`${s} = ${u}`,this)}u=s}return e.format(u,r,t)}}const oa=(e,t)=>{const r=Vi(t||e);return r===e&&(e=Is(r)),e=e&&!0===e.isNode?e.node&&e.node.value||e.value:e,Gi(new aa(e,r))};class ua extends Js{static get type(){return"ArrayNode"}constructor(e,t,r=null){super(e),this.count=t,this.values=r,this.isArrayNode=!0}getArrayCount(){return this.count}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const la=(...e)=>{let t;if(1===e.length){const r=e[0];t=new ua(null,r.length,r)}else{const r=e[0],s=e[1];t=new ua(r,s)}return Gi(t)};ci("toArray",(e,t)=>la(Array(t).fill(e)));class da extends Js{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const r=e.getTypeLength(t.node.getNodeType(e));return js.join("").slice(0,r)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:r}=this,s=t.getScope();e.getNodeProperties(s).assign=!0;const i=e.getNodeProperties(this);i.sourceNode=r,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:r,sourceNode:s}=e.getNodeProperties(this),i=this.needsSplitAssign(e),n=r.build(e),a=r.getNodeType(e),o=s.build(e,a),u=s.getNodeType(e),l=e.getDataFromNode(this);let d;if(!0===l.initialized)"void"!==t&&(d=n);else if(i){const s=e.getVarFromNode(this,null,a),i=e.getPropertyName(s);e.addLineFlowCode(`${i} = ${o}`,this);const u=r.node,l=u.node.context({assign:!0}).build(e);for(let t=0;t{const s=r.type;let i;return i="pointer"===s?"&"+t.build(e):t.build(e,s),i};if(Array.isArray(i)){if(i.length>s.length)console.error("THREE.TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),i.length=s.length;else if(i.length(t=t.length>1||t[0]&&!0===t[0].isNode?$i(t):zi(t[0]),Gi(new ha(Gi(e),t)));ci("call",pa);const ga={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class ma extends Js{static get type(){return"OperatorNode"}constructor(e,t,r,...s){if(super(),s.length>0){let i=new ma(e,t,r);for(let t=0;t>"===r||"<<"===r)return e.getIntegerType(n);if("!"===r||"&&"===r||"||"===r||"^^"===r)return"bool";if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const r=this.op,{aNode:s,bNode:i}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=s.getNodeType(e),o=i?i.getNodeType(e):null,"<"===r||">"===r||"<="===r||">="===r||"=="===r||"!="===r?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===r||"<<"===r?(a=n,o=e.changeComponentType(o,"uint")):"%"===r?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const u=s.build(e,a),d=i?i.build(e,o):null,c=e.getFunctionOperator(r);if("void"!==t){const s=e.renderer.coordinateSystem===l;if("=="===r||"!="===r||"<"===r||">"===r||"<="===r||">="===r)return s&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${u}, ${d} )`,n,t):e.format(`( ${u} ${r} ${d} )`,n,t);if("%"===r)return e.isInteger(o)?e.format(`( ${u} % ${d} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${u}, ${d} )`,n,t);if("!"===r||"~"===r)return e.format(`(${r}${u})`,a,t);if(c)return e.format(`${c}( ${u}, ${d} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${d} ${r} ${u} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${u} ${r} ${d}`,n,t);{let i=`( ${u} ${r} ${d} )`;return!s&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,n,t)}}if("void"!==a)return c?e.format(`${c}( ${u}, ${d} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${d} ${r} ${u}`,n,t):e.format(`${u} ${r} ${d}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const fa=qi(ma,"+").setParameterLength(2,1/0).setName("add"),ya=qi(ma,"-").setParameterLength(2,1/0).setName("sub"),ba=qi(ma,"*").setParameterLength(2,1/0).setName("mul"),xa=qi(ma,"/").setParameterLength(2,1/0).setName("div"),Ta=qi(ma,"%").setParameterLength(2).setName("mod"),_a=qi(ma,"==").setParameterLength(2).setName("equal"),va=qi(ma,"!=").setParameterLength(2).setName("notEqual"),Na=qi(ma,"<").setParameterLength(2).setName("lessThan"),Sa=qi(ma,">").setParameterLength(2).setName("greaterThan"),Ea=qi(ma,"<=").setParameterLength(2).setName("lessThanEqual"),Ra=qi(ma,">=").setParameterLength(2).setName("greaterThanEqual"),Aa=qi(ma,"&&").setParameterLength(2,1/0).setName("and"),wa=qi(ma,"||").setParameterLength(2,1/0).setName("or"),Ca=qi(ma,"!").setParameterLength(1).setName("not"),Ma=qi(ma,"^^").setParameterLength(2).setName("xor"),Pa=qi(ma,"&").setParameterLength(2).setName("bitAnd"),Ba=qi(ma,"~").setParameterLength(2).setName("bitNot"),La=qi(ma,"|").setParameterLength(2).setName("bitOr"),Fa=qi(ma,"^").setParameterLength(2).setName("bitXor"),Ia=qi(ma,"<<").setParameterLength(2).setName("shiftLeft"),Da=qi(ma,">>").setParameterLength(2).setName("shiftRight"),Ua=Ki(([e])=>(e.addAssign(1),e)),Va=Ki(([e])=>(e.subAssign(1),e)),Oa=Ki(([e])=>{const t=rn(e).toConst();return e.addAssign(1),t}),Ga=Ki(([e])=>{const t=rn(e).toConst();return e.subAssign(1),t});ci("add",fa),ci("sub",ya),ci("mul",ba),ci("div",xa),ci("mod",Ta),ci("equal",_a),ci("notEqual",va),ci("lessThan",Na),ci("greaterThan",Sa),ci("lessThanEqual",Ea),ci("greaterThanEqual",Ra),ci("and",Aa),ci("or",wa),ci("not",Ca),ci("xor",Ma),ci("bitAnd",Pa),ci("bitNot",Ba),ci("bitOr",La),ci("bitXor",Fa),ci("shiftLeft",Ia),ci("shiftRight",Da),ci("incrementBefore",Ua),ci("decrementBefore",Va),ci("increment",Oa),ci("decrement",Ga);const ka=(e,t)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),Ta(rn(e),rn(t)));ci("modInt",ka);class za extends Js{static get type(){return"MathNode"}constructor(e,t,r=null,s=null){if(super(),(e===za.MAX||e===za.MIN)&&arguments.length>3){let i=new za(e,t,r);for(let t=2;tn&&i>a?t:n>a?r:a>i?s:t}getNodeType(e){const t=this.method;return t===za.LENGTH||t===za.DISTANCE||t===za.DOT?"float":t===za.CROSS?"vec3":t===za.ALL||t===za.ANY?"bool":t===za.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:r,method:s}=this;let i=null;if(s===za.ONE_MINUS)i=ya(1,t);else if(s===za.RECIPROCAL)i=xa(1,t);else if(s===za.DIFFERENCE)i=go(ya(t,r));else if(s===za.TRANSFORM_DIRECTION){let s=t,n=r;e.isMatrix(s.getNodeType(e))?n=gn(dn(n),0):s=gn(dn(s),0);const a=ba(s,n).xyz;i=no(a)}return null!==i?i:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let r=this.method;const s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=this.cNode,u=e.renderer.coordinateSystem;if(r===za.NEGATE)return e.format("( - "+n.build(e,i)+" )",s,t);{const c=[];return r===za.CROSS?c.push(n.build(e,s),a.build(e,s)):u===l&&r===za.STEP?c.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":i),a.build(e,i)):u!==l||r!==za.MIN&&r!==za.MAX?r===za.REFRACT?c.push(n.build(e,i),a.build(e,i),o.build(e,"float")):r===za.MIX?c.push(n.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(u===d&&r===za.ATAN&&null!==a&&(r="atan2"),"fragment"===e.shaderStage||r!==za.DFDX&&r!==za.DFDY||(console.warn(`THREE.TSL: '${r}' is not supported in the ${e.shaderStage} stage.`),r="/*"+r+"*/"),c.push(n.build(e,i)),null!==a&&c.push(a.build(e,i)),null!==o&&c.push(o.build(e,i))):c.push(n.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(r,s)}( ${c.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}za.ALL="all",za.ANY="any",za.RADIANS="radians",za.DEGREES="degrees",za.EXP="exp",za.EXP2="exp2",za.LOG="log",za.LOG2="log2",za.SQRT="sqrt",za.INVERSE_SQRT="inversesqrt",za.FLOOR="floor",za.CEIL="ceil",za.NORMALIZE="normalize",za.FRACT="fract",za.SIN="sin",za.COS="cos",za.TAN="tan",za.ASIN="asin",za.ACOS="acos",za.ATAN="atan",za.ABS="abs",za.SIGN="sign",za.LENGTH="length",za.NEGATE="negate",za.ONE_MINUS="oneMinus",za.DFDX="dFdx",za.DFDY="dFdy",za.ROUND="round",za.RECIPROCAL="reciprocal",za.TRUNC="trunc",za.FWIDTH="fwidth",za.TRANSPOSE="transpose",za.DETERMINANT="determinant",za.INVERSE="inverse",za.EQUALS="equals",za.MIN="min",za.MAX="max",za.STEP="step",za.REFLECT="reflect",za.DISTANCE="distance",za.DIFFERENCE="difference",za.DOT="dot",za.CROSS="cross",za.POW="pow",za.TRANSFORM_DIRECTION="transformDirection",za.MIX="mix",za.CLAMP="clamp",za.REFRACT="refract",za.SMOOTHSTEP="smoothstep",za.FACEFORWARD="faceforward";const $a=tn(1e-6),Ha=tn(1e6),Wa=tn(Math.PI),qa=tn(2*Math.PI),ja=qi(za,za.ALL).setParameterLength(1),Xa=qi(za,za.ANY).setParameterLength(1),Ka=qi(za,za.RADIANS).setParameterLength(1),Ya=qi(za,za.DEGREES).setParameterLength(1),Qa=qi(za,za.EXP).setParameterLength(1),Za=qi(za,za.EXP2).setParameterLength(1),Ja=qi(za,za.LOG).setParameterLength(1),eo=qi(za,za.LOG2).setParameterLength(1),to=qi(za,za.SQRT).setParameterLength(1),ro=qi(za,za.INVERSE_SQRT).setParameterLength(1),so=qi(za,za.FLOOR).setParameterLength(1),io=qi(za,za.CEIL).setParameterLength(1),no=qi(za,za.NORMALIZE).setParameterLength(1),ao=qi(za,za.FRACT).setParameterLength(1),oo=qi(za,za.SIN).setParameterLength(1),uo=qi(za,za.COS).setParameterLength(1),lo=qi(za,za.TAN).setParameterLength(1),co=qi(za,za.ASIN).setParameterLength(1),ho=qi(za,za.ACOS).setParameterLength(1),po=qi(za,za.ATAN).setParameterLength(1,2),go=qi(za,za.ABS).setParameterLength(1),mo=qi(za,za.SIGN).setParameterLength(1),fo=qi(za,za.LENGTH).setParameterLength(1),yo=qi(za,za.NEGATE).setParameterLength(1),bo=qi(za,za.ONE_MINUS).setParameterLength(1),xo=qi(za,za.DFDX).setParameterLength(1),To=qi(za,za.DFDY).setParameterLength(1),_o=qi(za,za.ROUND).setParameterLength(1),vo=qi(za,za.RECIPROCAL).setParameterLength(1),No=qi(za,za.TRUNC).setParameterLength(1),So=qi(za,za.FWIDTH).setParameterLength(1),Eo=qi(za,za.TRANSPOSE).setParameterLength(1),Ro=qi(za,za.DETERMINANT).setParameterLength(1),Ao=qi(za,za.INVERSE).setParameterLength(1),wo=(e,t)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),_a(e,t)),Co=qi(za,za.MIN).setParameterLength(2,1/0),Mo=qi(za,za.MAX).setParameterLength(2,1/0),Po=qi(za,za.STEP).setParameterLength(2),Bo=qi(za,za.REFLECT).setParameterLength(2),Lo=qi(za,za.DISTANCE).setParameterLength(2),Fo=qi(za,za.DIFFERENCE).setParameterLength(2),Io=qi(za,za.DOT).setParameterLength(2),Do=qi(za,za.CROSS).setParameterLength(2),Uo=qi(za,za.POW).setParameterLength(2),Vo=e=>ba(e,e),Oo=e=>ba(e,e,e),Go=e=>ba(e,e,e,e),ko=qi(za,za.TRANSFORM_DIRECTION).setParameterLength(2),zo=e=>ba(mo(e),Uo(go(e),1/3)),$o=e=>Io(e,e),Ho=qi(za,za.MIX).setParameterLength(3),Wo=(e,t=0,r=1)=>Gi(new za(za.CLAMP,Gi(e),Gi(t),Gi(r))),qo=e=>Wo(e),jo=qi(za,za.REFRACT).setParameterLength(3),Xo=qi(za,za.SMOOTHSTEP).setParameterLength(3),Ko=qi(za,za.FACEFORWARD).setParameterLength(3),Yo=Ki(([e])=>{const t=Io(e.xy,an(12.9898,78.233)),r=Ta(t,Wa);return ao(oo(r).mul(43758.5453))}),Qo=(e,t,r)=>Ho(t,r,e),Zo=(e,t,r)=>Xo(t,r,e),Jo=(e,t)=>Po(t,e),eu=(e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),po(e,t)),tu=Ko,ru=ro;ci("all",ja),ci("any",Xa),ci("equals",wo),ci("radians",Ka),ci("degrees",Ya),ci("exp",Qa),ci("exp2",Za),ci("log",Ja),ci("log2",eo),ci("sqrt",to),ci("inverseSqrt",ro),ci("floor",so),ci("ceil",io),ci("normalize",no),ci("fract",ao),ci("sin",oo),ci("cos",uo),ci("tan",lo),ci("asin",co),ci("acos",ho),ci("atan",po),ci("abs",go),ci("sign",mo),ci("length",fo),ci("lengthSq",$o),ci("negate",yo),ci("oneMinus",bo),ci("dFdx",xo),ci("dFdy",To),ci("round",_o),ci("reciprocal",vo),ci("trunc",No),ci("fwidth",So),ci("atan2",eu),ci("min",Co),ci("max",Mo),ci("step",Jo),ci("reflect",Bo),ci("distance",Lo),ci("dot",Io),ci("cross",Do),ci("pow",Uo),ci("pow2",Vo),ci("pow3",Oo),ci("pow4",Go),ci("transformDirection",ko),ci("mix",Qo),ci("clamp",Wo),ci("refract",jo),ci("smoothstep",Zo),ci("faceForward",Ko),ci("difference",Fo),ci("saturate",qo),ci("cbrt",zo),ci("transpose",Eo),ci("determinant",Ro),ci("inverse",Ao),ci("rand",Yo);class su extends Ys{static get type(){return"ConditionalNode"}constructor(e,t,r=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=r}getNodeType(e){const{ifNode:t,elseNode:r}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const s=t.getNodeType(e);if(null!==r){const t=r.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(s))return t}return s}setup(e){const t=this.condNode.cache(),r=this.ifNode.cache(),s=this.elseNode?this.elseNode.cache():null,i=e.context.nodeBlock;e.getDataFromNode(r).parentNodeBlock=i,null!==s&&(e.getDataFromNode(s).parentNodeBlock=i);const n=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?r:r.context({nodeBlock:r}),a.elseNode=s?n?s:s.context({nodeBlock:s}):null}generate(e,t){const r=this.getNodeType(e),s=e.getDataFromNode(this);if(void 0!==s.nodeProperty)return s.nodeProperty;const{condNode:i,ifNode:n,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,u="void"!==t,l=u?Sn(r).build(e):"";s.nodeProperty=l;const d=i.build(e,"bool");if(e.context.uniformFlow&&null!==a){const s=n.build(e,r),i=a.build(e,r),o=e.getTernary(d,s,i);return e.format(o,r,t)}e.addFlowCode(`\n${e.tab}if ( ${d} ) {\n\n`).addFlowTab();let c=n.build(e,r);if(c&&(u?c=l+" = "+c+";":(c="return "+c+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,r);t&&(u?t=l+" = "+t+";":(t="return "+t+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,r,t)}}const iu=Hi(su).setParameterLength(2,3);ci("select",iu);class nu extends Ys{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const r=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e,t);return e.setContext(r),s}}const au=Hi(nu).setParameterLength(1,2),ou=e=>au(e,{uniformFlow:!0}),uu=(e,t)=>au(e,{nodeName:t});function lu(e,t){return console.warn('THREE.TSL: "label()" has been deprecated. Use "setName()" instead.'),uu(e,t)}ci("context",au),ci("label",lu),ci("uniformFlow",ou),ci("setName",uu);class du extends Ys{static get type(){return"VarNode"}constructor(e,t=null,r=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=r,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}build(...e){if(!0===this.intent){if(!0!==e[0].getNodeProperties(this).assign)return this.node.build(...e)}return super.build(...e)}generate(e){const{node:t,name:r,readOnly:s}=this,{renderer:i}=e,n=!0===i.backend.isWebGPUBackend;let a=!1,o=!1;s&&(a=e.isDeterministic(t),o=n?s:a);const u=e.getVectorType(this.getNodeType(e)),l=t.build(e,u),d=e.getVarFromNode(this,r,u,void 0,o),c=e.getPropertyName(d);let h=c;if(o)if(n)h=a?`const ${c}`:`let ${c}`;else{const r=t.getArrayCount(e);h=`const ${e.getVar(d.type,c,r)}`}return e.addLineFlowCode(`${h} = ${l}`,this),c}}const cu=Hi(du),hu=(e,t=null)=>cu(e,t).toStack(),pu=(e,t=null)=>cu(e,t,!0).toStack(),gu=e=>null===Qi()?e:cu(e).setIntent(!0).toStack();ci("toVar",hu),ci("toConst",pu),ci("toVarIntent",gu);class mu extends Ys{static get type(){return"SubBuild"}constructor(e,t,r=null){super(r),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const r=this.node.build(e,...t);return e.removeSubBuild(),r}}const fu=(e,t,r=null)=>Gi(new mu(Gi(e),t,r));class yu extends Ys{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let r=t.varying;if(void 0===r){const s=this.name,i=this.getNodeType(e),n=this.interpolationType,a=this.interpolationSampling;t.varying=r=e.getVaryingFromNode(this,s,i,n,a),t.node=fu(this.node,"VERTEX")}return r.needsInterpolation||(r.needsInterpolation="fragment"===e.shaderStage),r}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Gs.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Gs.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),r=e.getNodeProperties(this),s=this.setupVarying(e);if(void 0===r[t]){const i=this.getNodeType(e),n=e.getPropertyName(s,Gs.VERTEX);e.flowNodeFromShaderStage(Gs.VERTEX,r.node,i,n),r[t]=n}return e.getPropertyName(s)}}const bu=Hi(yu).setParameterLength(1,2),xu=e=>bu(e);ci("toVarying",bu),ci("toVertexStage",xu),ci("varying",(...e)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),bu(...e))),ci("vertexStage",(...e)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),bu(...e)));const Tu=Ki(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),r=e.mul(.0773993808),s=e.lessThanEqual(.04045);return Ho(t,r,s)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),_u=Ki(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),r=e.mul(12.92),s=e.lessThanEqual(.0031308);return Ho(t,r,s)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),vu="WorkingColorSpace";class Nu extends Js{static get type(){return"ColorSpaceNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.source=t,this.target=r}resolveColorSpace(e,t){return t===vu?c.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,r=this.resolveColorSpace(e,this.source),s=this.resolveColorSpace(e,this.target);let i=t;return!1!==c.enabled&&r!==s&&r&&s?(c.getTransfer(r)===h&&(i=gn(Tu(i.rgb),i.a)),c.getPrimaries(r)!==c.getPrimaries(s)&&(i=gn(xn(c._getMatrix(new n,r,s)).mul(i.rgb),i.a)),c.getTransfer(s)===h&&(i=gn(_u(i.rgb),i.a)),i):i}}const Su=(e,t)=>Gi(new Nu(Gi(e),vu,t)),Eu=(e,t)=>Gi(new Nu(Gi(e),t,vu));ci("workingToColorSpace",Su),ci("colorSpaceToWorking",Eu);let Ru=class extends Qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}};class Au extends Ys{static get type(){return"ReferenceBaseNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.updateType=ks.OBJECT}setGroup(e){return this.group=e,this}element(e){return Gi(new Ru(this,Gi(e)))}setNodeType(e){const t=oa(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eGi(new wu(e,t,r));class Mu extends Js{static get type(){return"ToneMappingNode"}constructor(e,t=Bu,r=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=r}customCacheKey(){return Ss(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,r=this.toneMapping;if(r===p)return t;let s=null;const i=e.renderer.library.getToneMappingFunction(r);return null!==i?s=gn(i(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",r),s=t),s}}const Pu=(e,t,r)=>Gi(new Mu(e,Gi(t),Gi(r))),Bu=Cu("toneMappingExposure","float");ci("toneMapping",(e,t,r)=>Pu(t,r,e));class Lu extends ni{static get type(){return"BufferAttributeNode"}constructor(e,t=null,r=0,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=r,this.bufferOffset=s,this.usage=g,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),r=this.value,s=e.getTypeLength(t),i=this.bufferStride||s,n=this.bufferOffset,a=!0===r.isInterleavedBuffer?r:new m(r,i),o=new f(a,s,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),r=e.getBufferAttributeFromNode(this,t),s=e.getPropertyName(r);let i=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=s,i=s;else{i=bu(this).build(e,t)}return i}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}const Fu=(e,t=null,r=0,s=0)=>Gi(new Lu(e,t,r,s)),Iu=(e,t=null,r=0,s=0)=>Fu(e,t,r,s).setUsage(y),Du=(e,t=null,r=0,s=0)=>Fu(e,t,r,s).setInstanced(!0),Uu=(e,t=null,r=0,s=0)=>Iu(e,t,r,s).setInstanced(!0);ci("toAttribute",e=>Fu(e.value));class Vu extends Ys{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=ks.OBJECT,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return console.warn('THREE.TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:r}=e;if("compute"===r){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}else{const r=e.getNodeProperties(this).outputComputeNode;if(r)return r.build(e,t)}}}const Ou=(e,t=[64])=>{(0===t.length||t.length>3)&&console.error("THREE.TSL: compute() workgroupSize must have 1, 2, or 3 elements");for(let e=0;eOu(e,r).setCount(t);ci("compute",Gu),ci("computeKernel",Ou);class ku extends Ys{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const s=this.node.getNodeType(e);return e.setCache(t),s}build(e,...t){const r=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.build(e,...t);return e.setCache(r),i}}const zu=(e,t)=>Gi(new ku(Gi(e),t));ci("cache",zu);class $u extends Ys{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const Hu=Hi($u).setParameterLength(2);ci("bypass",Hu);class Wu extends Ys{static get type(){return"RemapNode"}constructor(e,t,r,s=tn(0),i=tn(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=r,this.outLowNode=s,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:r,outLowNode:s,outHighNode:i,doClamp:n}=this;let a=e.sub(t).div(r.sub(t));return!0===n&&(a=a.clamp()),a.mul(i.sub(s)).add(s)}}const qu=Hi(Wu,null,null,{doClamp:!1}).setParameterLength(3,5),ju=Hi(Wu).setParameterLength(3,5);ci("remap",qu),ci("remapClamp",ju);class Xu extends Ys{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const r=this.getNodeType(e),s=this.snippet;if("void"!==r)return e.format(s,r,t);e.addLineFlowCode(s,this)}}const Ku=Hi(Xu).setParameterLength(1,2),Yu=e=>(e?iu(e,Ku("discard")):Ku("discard")).toStack();ci("discard",Yu);class Qu extends Js{static get type(){return"RenderOutputNode"}constructor(e,t,r){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=r,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const r=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||p,s=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||b;return r!==p&&(t=t.toneMapping(r)),s!==b&&s!==c.workingColorSpace&&(t=t.workingToColorSpace(s)),t}}const Zu=(e,t=null,r=null)=>Gi(new Qu(Gi(e),t,r));ci("renderOutput",Zu);class Ju extends Js{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,r=this.node.build(e),s="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(s.length);let n="";return n+="// #"+s+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+r+" /* ... */\n",n+="// #"+i+"#\n",null!==t?t(e,n):console.log(n),r}}const el=(e,t=null)=>Gi(new Ju(Gi(e),t)).toStack();ci("debug",el);class tl extends Ys{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const r=this.getAttributeName(e);if(e.hasGeometryAttribute(r)){const s=e.geometry.getAttribute(r);t=e.getTypeFromAttribute(s)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),r=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const s=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(s),n=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(n.name,i,r);return bu(this).build(e,r)}return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(r)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const rl=(e,t=null)=>Gi(new tl(e,t)),sl=(e=0)=>rl("uv"+(e>0?e:""),"vec2");class il extends Ys{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const r=this.textureNode.build(e,"property"),s=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${r}, ${s} )`,this.getNodeType(e),t)}}const nl=Hi(il).setParameterLength(1,2);class al extends aa{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=ks.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,r=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(r&&void 0!==r.width){const{width:e,height:t}=r;this.value=Math.log2(Math.max(e,t))}}}const ol=Hi(al).setParameterLength(1),ul=new x;class ll extends aa{static get type(){return"TextureNode"}constructor(e=ul,t=null,r=null,s=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=r,this.biasNode=s,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=ks.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===T?"uvec4":this.value.type===_?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return sl(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=oa(this.value.matrix)),this._matrixUniform.mul(dn(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?ks.OBJECT:ks.NONE,this}setupUV(e,t){const r=this.value;return e.isFlipY()&&(r.image instanceof ImageBitmap&&!0===r.flipY||!0===r.isRenderTargetTexture||!0===r.isFramebufferTexture||!0===r.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(rn(nl(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const r=this.value;if(!r||!0!==r.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let s=this.uvNode;null!==s&&!0!==e.context.forceUVContext||!e.context.getUV||(s=e.context.getUV(this,e)),s||(s=this.getDefaultUV()),!0===this.updateMatrix&&(s=this.getTransformedUV(s)),s=this.setupUV(e,s);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),t.uvNode=s,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,r,s,i,n,a,o,u){const l=this.value;let d;return d=s?e.generateTextureLevel(l,t,r,s,n,u):i?e.generateTextureBias(l,t,r,i,n,u):o?e.generateTextureGrad(l,t,r,o,n,u):a?e.generateTextureCompare(l,t,r,a,n,u):!1===this.sampler?e.generateTextureLoad(l,t,r,n,u):e.generateTexture(l,t,r,n,u),d}generate(e,t){const r=this.value,s=e.getNodeProperties(this),i=super.generate(e,"property");if(/^sampler/.test(t))return i+"_sampler";if(e.isReference(t))return i;{const n=e.getDataFromNode(this);let a=n.propertyName;if(void 0===a){const{uvNode:t,levelNode:r,biasNode:o,compareNode:u,depthNode:l,gradNode:d,offsetNode:c}=s,h=this.generateUV(e,t),p=r?r.build(e,"float"):null,g=o?o.build(e,"float"):null,m=l?l.build(e,"int"):null,f=u?u.build(e,"float"):null,y=d?[d[0].build(e,"vec2"),d[1].build(e,"vec2")]:null,b=c?this.generateOffset(e,c):null,x=e.getVarFromNode(this);a=e.getPropertyName(x);const T=this.generateSnippet(e,i,h,p,g,m,f,y,b);e.addLineFlowCode(`${a} = ${T}`,this),n.snippet=T,n.propertyName=a}let o=a;const u=this.getNodeType(e);return e.needsToWorkingColorSpace(r)&&(o=Eu(Ku(o,u),r.colorSpace).setup(e).build(e,u)),e.format(o,u,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Gi(e),t.referenceNode=this.getBase(),Gi(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Gi(e).mul(ol(t)),t.referenceNode=this.getBase();const r=t.value;return!1===t.generateMipmaps&&(r&&!1===r.generateMipmaps||r.minFilter===v||r.magFilter===v)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Gi(t)}level(e){const t=this.clone();return t.levelNode=Gi(e),t.referenceNode=this.getBase(),Gi(t)}size(e){return nl(this,e)}bias(e){const t=this.clone();return t.biasNode=Gi(e),t.referenceNode=this.getBase(),Gi(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Gi(e),t.referenceNode=this.getBase(),Gi(t)}grad(e,t){const r=this.clone();return r.gradNode=[Gi(e),Gi(t)],r.referenceNode=this.getBase(),Gi(r)}depth(e){const t=this.clone();return t.depthNode=Gi(e),t.referenceNode=this.getBase(),Gi(t)}offset(e){const t=this.clone();return t.offsetNode=Gi(e),t.referenceNode=this.getBase(),Gi(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const dl=Hi(ll).setParameterLength(1,4).setName("texture"),cl=(e=ul,t=null,r=null,s=null)=>{let i;return e&&!0===e.isTextureNode?(i=Gi(e.clone()),i.referenceNode=e.getBase(),null!==t&&(i.uvNode=Gi(t)),null!==r&&(i.levelNode=Gi(r)),null!==s&&(i.biasNode=Gi(s))):i=dl(e,t,r,s),i},hl=(...e)=>cl(...e).setSampler(!1);class pl extends aa{static get type(){return"BufferNode"}constructor(e,t,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=r}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const gl=(e,t,r)=>Gi(new pl(e,t,r));class ml extends Qs{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),r=this.getNodeType(),s=this.node.getPaddedType();return e.format(t,s,r)}}class fl extends pl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Fs(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=ks.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,r=this.elementType;if("float"===r||"int"===r||"uint"===r)for(let r=0;rGi(new fl(e,t));const bl=Hi(class extends Ys{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let xl,Tl;class _l extends Ys{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===_l.DPR?"float":this.scope===_l.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=ks.NONE;return this.scope!==_l.SIZE&&this.scope!==_l.VIEWPORT&&this.scope!==_l.DPR||(e=ks.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===_l.VIEWPORT?null!==t?Tl.copy(t.viewport):(e.getViewport(Tl),Tl.multiplyScalar(e.getPixelRatio())):this.scope===_l.DPR?this._output.value=e.getPixelRatio():null!==t?(xl.width=t.width,xl.height=t.height):e.getDrawingBufferSize(xl)}setup(){const e=this.scope;let r=null;return r=e===_l.SIZE?oa(xl||(xl=new t)):e===_l.VIEWPORT?oa(Tl||(Tl=new s)):e===_l.DPR?oa(1):an(El.div(Sl)),this._output=r,r}generate(e){if(this.scope===_l.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const r=e.getNodeProperties(Sl).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${r}.y - ${t}.y )`}return t}return super.generate(e)}}_l.COORDINATE="coordinate",_l.VIEWPORT="viewport",_l.SIZE="size",_l.UV="uv",_l.DPR="dpr";const vl=Wi(_l,_l.DPR),Nl=Wi(_l,_l.UV),Sl=Wi(_l,_l.SIZE),El=Wi(_l,_l.COORDINATE),Rl=Wi(_l,_l.VIEWPORT),Al=Rl.zw,wl=El.sub(Rl.xy),Cl=wl.div(Al),Ml=Ki(()=>(console.warn('THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.'),Sl),"vec2").once()(),Pl=oa(0,"uint").setName("u_cameraIndex").setGroup(ra("cameraIndex")).toVarying("v_cameraIndex"),Bl=oa("float").setName("cameraNear").setGroup(ia).onRenderUpdate(({camera:e})=>e.near),Ll=oa("float").setName("cameraFar").setGroup(ia).onRenderUpdate(({camera:e})=>e.far),Fl=Ki(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrix);t=yl(r).setGroup(ia).setName("cameraProjectionMatrices").element(e.isMultiViewCamera?bl("gl_ViewID_OVR"):Pl).toConst("cameraProjectionMatrix")}else t=oa("mat4").setName("cameraProjectionMatrix").setGroup(ia).onRenderUpdate(({camera:e})=>e.projectionMatrix);return t}).once()(),Il=Ki(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.projectionMatrixInverse);t=yl(r).setGroup(ia).setName("cameraProjectionMatricesInverse").element(e.isMultiViewCamera?bl("gl_ViewID_OVR"):Pl).toConst("cameraProjectionMatrixInverse")}else t=oa("mat4").setName("cameraProjectionMatrixInverse").setGroup(ia).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse);return t}).once()(),Dl=Ki(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorldInverse);t=yl(r).setGroup(ia).setName("cameraViewMatrices").element(e.isMultiViewCamera?bl("gl_ViewID_OVR"):Pl).toConst("cameraViewMatrix")}else t=oa("mat4").setName("cameraViewMatrix").setGroup(ia).onRenderUpdate(({camera:e})=>e.matrixWorldInverse);return t}).once()(),Ul=Ki(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.matrixWorld);t=yl(r).setGroup(ia).setName("cameraWorldMatrices").element(e.isMultiViewCamera?bl("gl_ViewID_OVR"):Pl).toConst("cameraWorldMatrix")}else t=oa("mat4").setName("cameraWorldMatrix").setGroup(ia).onRenderUpdate(({camera:e})=>e.matrixWorld);return t}).once()(),Vl=Ki(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.normalMatrix);t=yl(r).setGroup(ia).setName("cameraNormalMatrices").element(e.isMultiViewCamera?bl("gl_ViewID_OVR"):Pl).toConst("cameraNormalMatrix")}else t=oa("mat3").setName("cameraNormalMatrix").setGroup(ia).onRenderUpdate(({camera:e})=>e.normalMatrix);return t}).once()(),Ol=Ki(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t{const r=e.cameras,s=t.array;for(let e=0,t=r.length;et.value.setFromMatrixPosition(e.matrixWorld));return t}).once()(),Gl=Ki(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const r=[];for(const t of e.cameras)r.push(t.viewport);t=yl(r,"vec4").setGroup(ia).setName("cameraViewports").element(Pl).toConst("cameraViewport")}else t=gn(0,0,Sl.x,Sl.y).toConst("cameraViewport");return t}).once()(),kl=new N;class zl extends Ys{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ks.OBJECT,this.uniformNode=new aa(null)}getNodeType(){const e=this.scope;return e===zl.WORLD_MATRIX?"mat4":e===zl.POSITION||e===zl.VIEW_POSITION||e===zl.DIRECTION||e===zl.SCALE?"vec3":e===zl.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===zl.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===zl.POSITION)s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===zl.SCALE)s.value=s.value||new r,s.value.setFromMatrixScale(t.matrixWorld);else if(i===zl.DIRECTION)s.value=s.value||new r,t.getWorldDirection(s.value);else if(i===zl.VIEW_POSITION){const i=e.camera;s.value=s.value||new r,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===zl.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),kl.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),s.value=kl.radius}}generate(e){const t=this.scope;return t===zl.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===zl.POSITION||t===zl.VIEW_POSITION||t===zl.DIRECTION||t===zl.SCALE?this.uniformNode.nodeType="vec3":t===zl.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}zl.WORLD_MATRIX="worldMatrix",zl.POSITION="position",zl.SCALE="scale",zl.VIEW_POSITION="viewPosition",zl.DIRECTION="direction",zl.RADIUS="radius";const $l=Hi(zl,zl.DIRECTION).setParameterLength(1),Hl=Hi(zl,zl.WORLD_MATRIX).setParameterLength(1),Wl=Hi(zl,zl.POSITION).setParameterLength(1),ql=Hi(zl,zl.SCALE).setParameterLength(1),jl=Hi(zl,zl.VIEW_POSITION).setParameterLength(1),Xl=Hi(zl,zl.RADIUS).setParameterLength(1);class Kl extends zl{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Yl=Wi(Kl,Kl.DIRECTION),Ql=Wi(Kl,Kl.WORLD_MATRIX),Zl=Wi(Kl,Kl.POSITION),Jl=Wi(Kl,Kl.SCALE),ed=Wi(Kl,Kl.VIEW_POSITION),td=Wi(Kl,Kl.RADIUS),rd=oa(new n).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),sd=oa(new a).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),id=Ki(e=>e.renderer.overrideNodes.modelViewMatrix||nd).once()().toVar("modelViewMatrix"),nd=Dl.mul(Ql),ad=Ki(e=>(e.context.isHighPrecisionModelViewMatrix=!0,oa("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),od=Ki(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return oa("mat3").onObjectUpdate(({object:e,camera:r})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(r.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),ud=rl("position","vec3"),ld=ud.toVarying("positionLocal"),dd=ud.toVarying("positionPrevious"),cd=Ki(e=>Ql.mul(ld).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),hd=Ki(()=>ld.transformDirection(Ql).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),pd=Ki(e=>e.context.setupPositionView().toVarying("v_positionView"),"vec3").once(["POSITION"])(),gd=pd.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class md extends Ys{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return t.side===S?"false":e.getFrontFacing()}}const fd=Wi(md),yd=tn(fd).mul(2).sub(1),bd=Ki(([e],{material:t})=>{const r=t.side;return r===S?e=e.mul(-1):r===E&&(e=e.mul(yd)),e}),xd=rl("normal","vec3"),Td=Ki(e=>!1===e.geometry.hasAttribute("normal")?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),dn(0,1,0)):xd,"vec3").once()().toVar("normalLocal"),_d=pd.dFdx().cross(pd.dFdy()).normalize().toVar("normalFlat"),vd=Ki(e=>{let t;return t=!0===e.material.flatShading?_d:wd(Td).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Nd=Ki(e=>{let t=vd.transformDirection(Dl);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Sd=Ki(({subBuildFn:e,material:t,context:r})=>{let s;return"NORMAL"===e||"VERTEX"===e?(s=vd,!0!==t.flatShading&&(s=bd(s))):s=r.setupNormal().context({getUV:null}),s},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Ed=Sd.transformDirection(Dl).toVar("normalWorld"),Rd=Ki(({subBuildFn:e,context:t})=>{let r;return r="NORMAL"===e||"VERTEX"===e?Sd:t.setupClearcoatNormal().context({getUV:null}),r},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Ad=Ki(([e,t=Ql])=>{const r=xn(t),s=e.div(dn(r[0].dot(r[0]),r[1].dot(r[1]),r[2].dot(r[2])));return r.mul(s).xyz}),wd=Ki(([e],t)=>{const r=t.renderer.overrideNodes.modelNormalViewMatrix;if(null!==r)return r.transformDirection(e);const s=rd.mul(e);return Dl.transformDirection(s)}),Cd=Ki(()=>(console.warn('THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Sd)).once(["NORMAL","VERTEX"])(),Md=Ki(()=>(console.warn('THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Ed)).once(["NORMAL","VERTEX"])(),Pd=Ki(()=>(console.warn('THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Rd)).once(["NORMAL","VERTEX"])(),Bd=new R,Ld=new a,Fd=oa(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Id=oa(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Dd=oa(new a).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const r=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return r?(Bd.copy(r),Ld.makeRotationFromEuler(Bd)):Ld.identity(),Ld}),Ud=gd.negate().reflect(Sd),Vd=gd.negate().refract(Sd,Fd),Od=Ud.transformDirection(Dl).toVar("reflectVector"),Gd=Vd.transformDirection(Dl).toVar("reflectVector"),kd=new A;class zd extends ll{static get type(){return"CubeTextureNode"}constructor(e,t=null,r=null,s=null){super(e,t,r,s),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===w?Od:e.mapping===C?Gd:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),dn(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return e.renderer.coordinateSystem!==d&&r.isRenderTargetTexture||(t=dn(t.x.negate(),t.yz)),Dd.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const $d=Hi(zd).setParameterLength(1,4).setName("cubeTexture"),Hd=(e=kd,t=null,r=null,s=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=Gi(e.clone()),i.referenceNode=e,null!==t&&(i.uvNode=Gi(t)),null!==r&&(i.levelNode=Gi(r)),null!==s&&(i.biasNode=Gi(s))):i=$d(e,t,r,s),i};class Wd extends Qs{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),r=this.referenceNode.getNodeType(),s=this.getNodeType();return e.format(t,r,s)}}class qd extends Ys{static get type(){return"ReferenceNode"}constructor(e,t,r=null,s=null){super(),this.property=e,this.uniformType=t,this.object=r,this.count=s,this.properties=e.split("."),this.reference=r,this.node=null,this.group=null,this.name=null,this.updateType=ks.OBJECT}element(e){return Gi(new Wd(this,Gi(e)))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return console.warn('THREE.TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?gl(null,e,this.count):Array.isArray(this.getValueFromReference())?yl(null,e):"texture"===e?cl(null):"cubeTexture"===e?Hd(null):oa(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let r=e[t[0]];for(let e=1;eGi(new qd(e,t,r)),Xd=(e,t,r,s)=>Gi(new qd(e,t,s,r));class Kd extends qd{static get type(){return"MaterialReferenceNode"}constructor(e,t,r=null){super(e,t,r),this.material=r,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Yd=(e,t,r=null)=>Gi(new Kd(e,t,r)),Qd=sl(),Zd=pd.dFdx(),Jd=pd.dFdy(),ec=Qd.dFdx(),tc=Qd.dFdy(),rc=Sd,sc=Jd.cross(rc),ic=rc.cross(Zd),nc=sc.mul(ec.x).add(ic.mul(tc.x)),ac=sc.mul(ec.y).add(ic.mul(tc.y)),oc=nc.dot(nc).max(ac.dot(ac)),uc=oc.equal(0).select(0,oc.inverseSqrt()),lc=nc.mul(uc).toVar("tangentViewFrame"),dc=ac.mul(uc).toVar("bitangentViewFrame"),cc=Ki(e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),rl("tangent","vec4")))(),hc=cc.xyz.toVar("tangentLocal"),pc=Ki(({subBuildFn:e,geometry:t,material:r})=>{let s;return s="VERTEX"===e||t.hasAttribute("tangent")?id.mul(gn(hc,0)).xyz.toVarying("v_tangentView").normalize():lc,!0!==r.flatShading&&(s=bd(s)),s},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),gc=pc.transformDirection(Dl).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),mc=Ki(([e,t],{subBuildFn:r,material:s})=>{let i=e.mul(cc.w).xyz;return"NORMAL"===r&&!0!==s.flatShading&&(i=i.toVarying(t)),i}).once(["NORMAL"]),fc=mc(xd.cross(cc),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),yc=mc(Td.cross(hc),"v_bitangentLocal").normalize().toVar("bitangentLocal"),bc=Ki(({subBuildFn:e,geometry:t,material:r})=>{let s;return s="VERTEX"===e||t.hasAttribute("tangent")?mc(Sd.cross(pc),"v_bitangentView").normalize():dc,!0!==r.flatShading&&(s=bd(s)),s},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),xc=mc(Ed.cross(gc),"v_bitangentWorld").normalize().toVar("bitangentWorld"),Tc=xn(pc,bc,Sd).toVar("TBNViewMatrix"),_c=gd.mul(Tc),vc=Ki(()=>{let e=Gn.cross(gd);return e=e.cross(Gn).normalize(),e=Ho(e,Sd,Vn.mul(wn.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()();class Nc extends Js{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=M}setup({material:e}){const{normalMapType:t,scaleNode:r}=this;let s=this.node.mul(2).sub(1);if(null!==r){let t=r;!0===e.flatShading&&(t=bd(t)),s=dn(s.xy.mul(t),s.z)}let i=null;return t===P?i=wd(s):t===M?i=Tc.mul(s).normalize():(console.error(`THREE.NodeMaterial: Unsupported normal map type: ${t}`),i=Sd),i}}const Sc=Hi(Nc).setParameterLength(1,2),Ec=Ki(({textureNode:e,bumpScale:t})=>{const r=t=>e.cache().context({getUV:e=>t(e.uvNode||sl()),forceUVContext:!0}),s=tn(r(e=>e));return an(tn(r(e=>e.add(e.dFdx()))).sub(s),tn(r(e=>e.add(e.dFdy()))).sub(s)).mul(t)}),Rc=Ki(e=>{const{surf_pos:t,surf_norm:r,dHdxy:s}=e,i=t.dFdx().normalize(),n=r,a=t.dFdy().normalize().cross(n),o=n.cross(i),u=i.dot(a).mul(yd),l=u.sign().mul(s.x.mul(a).add(s.y.mul(o)));return u.abs().mul(r).sub(l).normalize()});class Ac extends Js{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Ec({textureNode:this.textureNode,bumpScale:e});return Rc({surf_pos:pd,surf_norm:Sd,dHdxy:t})}}const wc=Hi(Ac).setParameterLength(1,2),Cc=new Map;class Mc extends Ys{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let r=Cc.get(e);return void 0===r&&(r=Yd(e,t),Cc.set(e,r)),r}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,r=this.scope;let s=null;if(r===Mc.COLOR){const e=void 0!==t.color?this.getColor(r):dn();s=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(r===Mc.OPACITY){const e=this.getFloat(r);s=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(r===Mc.SPECULAR_STRENGTH)s=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:tn(1);else if(r===Mc.SPECULAR_INTENSITY){const e=this.getFloat(r);s=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(r).a):e}else if(r===Mc.SPECULAR_COLOR){const e=this.getColor(r);s=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(r).rgb):e}else if(r===Mc.ROUGHNESS){const e=this.getFloat(r);s=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(r).g):e}else if(r===Mc.METALNESS){const e=this.getFloat(r);s=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(r).b):e}else if(r===Mc.EMISSIVE){const e=this.getFloat("emissiveIntensity"),i=this.getColor(r).mul(e);s=t.emissiveMap&&!0===t.emissiveMap.isTexture?i.mul(this.getTexture(r)):i}else if(r===Mc.NORMAL)t.normalMap?(s=Sc(this.getTexture("normal"),this.getCache("normalScale","vec2")),s.normalMapType=t.normalMapType):s=t.bumpMap?wc(this.getTexture("bump").r,this.getFloat("bumpScale")):Sd;else if(r===Mc.CLEARCOAT){const e=this.getFloat(r);s=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Mc.CLEARCOAT_ROUGHNESS){const e=this.getFloat(r);s=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(r).r):e}else if(r===Mc.CLEARCOAT_NORMAL)s=t.clearcoatNormalMap?Sc(this.getTexture(r),this.getCache(r+"Scale","vec2")):Sd;else if(r===Mc.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));s=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(r===Mc.SHEEN_ROUGHNESS){const e=this.getFloat(r);s=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(r).a):e,s=s.clamp(.07,1)}else if(r===Mc.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(r);s=bn(gh.x,gh.y,gh.y.negate(),gh.x).mul(e.rg.mul(2).sub(an(1)).normalize().mul(e.b))}else s=gh;else if(r===Mc.IRIDESCENCE_THICKNESS){const e=jd("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=jd("0","float",t.iridescenceThicknessRange);s=e.sub(i).mul(this.getTexture(r).g).add(i)}else s=e}else if(r===Mc.TRANSMISSION){const e=this.getFloat(r);s=t.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===Mc.THICKNESS){const e=this.getFloat(r);s=t.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===Mc.IOR)s=this.getFloat(r);else if(r===Mc.LIGHT_MAP)s=this.getTexture(r).rgb.mul(this.getFloat("lightMapIntensity"));else if(r===Mc.AO)s=this.getTexture(r).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(r===Mc.LINE_DASH_OFFSET)s=t.dashOffset?this.getFloat(r):tn(0);else{const t=this.getNodeType(e);s=this.getCache(r,t)}return s}}Mc.ALPHA_TEST="alphaTest",Mc.COLOR="color",Mc.OPACITY="opacity",Mc.SHININESS="shininess",Mc.SPECULAR="specular",Mc.SPECULAR_STRENGTH="specularStrength",Mc.SPECULAR_INTENSITY="specularIntensity",Mc.SPECULAR_COLOR="specularColor",Mc.REFLECTIVITY="reflectivity",Mc.ROUGHNESS="roughness",Mc.METALNESS="metalness",Mc.NORMAL="normal",Mc.CLEARCOAT="clearcoat",Mc.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Mc.CLEARCOAT_NORMAL="clearcoatNormal",Mc.EMISSIVE="emissive",Mc.ROTATION="rotation",Mc.SHEEN="sheen",Mc.SHEEN_ROUGHNESS="sheenRoughness",Mc.ANISOTROPY="anisotropy",Mc.IRIDESCENCE="iridescence",Mc.IRIDESCENCE_IOR="iridescenceIOR",Mc.IRIDESCENCE_THICKNESS="iridescenceThickness",Mc.IOR="ior",Mc.TRANSMISSION="transmission",Mc.THICKNESS="thickness",Mc.ATTENUATION_DISTANCE="attenuationDistance",Mc.ATTENUATION_COLOR="attenuationColor",Mc.LINE_SCALE="scale",Mc.LINE_DASH_SIZE="dashSize",Mc.LINE_GAP_SIZE="gapSize",Mc.LINE_WIDTH="linewidth",Mc.LINE_DASH_OFFSET="dashOffset",Mc.POINT_SIZE="size",Mc.DISPERSION="dispersion",Mc.LIGHT_MAP="light",Mc.AO="ao";const Pc=Wi(Mc,Mc.ALPHA_TEST),Bc=Wi(Mc,Mc.COLOR),Lc=Wi(Mc,Mc.SHININESS),Fc=Wi(Mc,Mc.EMISSIVE),Ic=Wi(Mc,Mc.OPACITY),Dc=Wi(Mc,Mc.SPECULAR),Uc=Wi(Mc,Mc.SPECULAR_INTENSITY),Vc=Wi(Mc,Mc.SPECULAR_COLOR),Oc=Wi(Mc,Mc.SPECULAR_STRENGTH),Gc=Wi(Mc,Mc.REFLECTIVITY),kc=Wi(Mc,Mc.ROUGHNESS),zc=Wi(Mc,Mc.METALNESS),$c=Wi(Mc,Mc.NORMAL),Hc=Wi(Mc,Mc.CLEARCOAT),Wc=Wi(Mc,Mc.CLEARCOAT_ROUGHNESS),qc=Wi(Mc,Mc.CLEARCOAT_NORMAL),jc=Wi(Mc,Mc.ROTATION),Xc=Wi(Mc,Mc.SHEEN),Kc=Wi(Mc,Mc.SHEEN_ROUGHNESS),Yc=Wi(Mc,Mc.ANISOTROPY),Qc=Wi(Mc,Mc.IRIDESCENCE),Zc=Wi(Mc,Mc.IRIDESCENCE_IOR),Jc=Wi(Mc,Mc.IRIDESCENCE_THICKNESS),eh=Wi(Mc,Mc.TRANSMISSION),th=Wi(Mc,Mc.THICKNESS),rh=Wi(Mc,Mc.IOR),sh=Wi(Mc,Mc.ATTENUATION_DISTANCE),ih=Wi(Mc,Mc.ATTENUATION_COLOR),nh=Wi(Mc,Mc.LINE_SCALE),ah=Wi(Mc,Mc.LINE_DASH_SIZE),oh=Wi(Mc,Mc.LINE_GAP_SIZE),uh=Wi(Mc,Mc.LINE_WIDTH),lh=Wi(Mc,Mc.LINE_DASH_OFFSET),dh=Wi(Mc,Mc.POINT_SIZE),ch=Wi(Mc,Mc.DISPERSION),hh=Wi(Mc,Mc.LIGHT_MAP),ph=Wi(Mc,Mc.AO),gh=oa(new t).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),mh=Ki(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class fh extends Ys{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),r=this.scope;let s,i;if(r===fh.VERTEX)s=e.getVertexIndex();else if(r===fh.INSTANCE)s=e.getInstanceIndex();else if(r===fh.DRAW)s=e.getDrawIndex();else if(r===fh.INVOCATION_LOCAL)s=e.getInvocationLocalIndex();else if(r===fh.INVOCATION_SUBGROUP)s=e.getInvocationSubgroupIndex();else{if(r!==fh.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+r);s=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=s;else{i=bu(this).build(e,t)}return i}}fh.VERTEX="vertex",fh.INSTANCE="instance",fh.SUBGROUP="subgroup",fh.INVOCATION_LOCAL="invocationLocal",fh.INVOCATION_SUBGROUP="invocationSubgroup",fh.DRAW="draw";const yh=Wi(fh,fh.VERTEX),bh=Wi(fh,fh.INSTANCE),xh=Wi(fh,fh.SUBGROUP),Th=Wi(fh,fh.INVOCATION_SUBGROUP),_h=Wi(fh,fh.INVOCATION_LOCAL),vh=Wi(fh,fh.DRAW);class Nh extends Ys{static get type(){return"InstanceNode"}constructor(e,t,r=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=r,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=ks.FRAME,this.buffer=null,this.bufferColor=null}setup(e){const{instanceMatrix:t,instanceColor:r}=this,{count:s}=t;let{instanceMatrixNode:i,instanceColorNode:n}=this;if(null===i){if(s<=1e3)i=gl(t.array,"mat4",Math.max(s,1)).element(bh);else{const e=new B(t.array,16,1);this.buffer=e;const r=t.usage===y?Uu:Du,s=[r(e,"vec4",16,0),r(e,"vec4",16,4),r(e,"vec4",16,8),r(e,"vec4",16,12)];i=Tn(...s)}this.instanceMatrixNode=i}if(r&&null===n){const e=new L(r.array,3),t=r.usage===y?Uu:Du;this.bufferColor=e,n=dn(t(e,"vec3",3,0)),this.instanceColorNode=n}const a=i.mul(ld).xyz;if(ld.assign(a),e.hasGeometryAttribute("normal")){const e=Ad(Td,i);Td.assign(e)}null!==this.instanceColorNode&&En("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==y&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==y&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}const Sh=Hi(Nh).setParameterLength(2,3);class Eh extends Nh{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:r,instanceColor:s}=e;super(t,r,s),this.instancedMesh=e}}const Rh=Hi(Eh).setParameterLength(1);class Ah extends Ys{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=bh:this.batchingIdNode=vh);const t=Ki(([e])=>{const t=rn(nl(hl(this.batchMesh._indirectTexture),0).x),r=rn(e).mod(t),s=rn(e).div(t);return hl(this.batchMesh._indirectTexture,on(r,s)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),r=t(rn(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=rn(nl(hl(s),0).x),n=tn(r).mul(4).toInt().toVar(),a=n.mod(i),o=n.div(i),u=Tn(hl(s,on(a,o)),hl(s,on(a.add(1),o)),hl(s,on(a.add(2),o)),hl(s,on(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=Ki(([e])=>{const t=rn(nl(hl(l),0).x),r=e,s=r.mod(t),i=r.div(t);return hl(l,on(s,i)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(r);En("vec3","vBatchColor").assign(t)}const d=xn(u);ld.assign(u.mul(ld));const c=Td.div(dn(d[0].dot(d[0]),d[1].dot(d[1]),d[2].dot(d[2]))),h=d.mul(c).xyz;Td.assign(h),e.hasGeometryAttribute("tangent")&&hc.mulAssign(d)}}const wh=Hi(Ah).setParameterLength(1);class Ch extends Qs{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const r=this.storageBufferNode.structTypeNode;return r?r.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let r;const s=e.context.assign;if(r=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===s||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}const Mh=Hi(Ch).setParameterLength(2);class Ph extends pl{static get type(){return"StorageBufferNode"}constructor(e,t=null,r=0){let s,i=null;t&&t.isStruct?(s="struct",i=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(r=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(s=Cs(e.itemSize),r=e.count):s=t,super(e,s,r),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=$s.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return Mh(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess($s.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=Fu(this.value),this._varying=bu(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:r}=this.getAttributeData(),s=r.build(e);return e.registerTransform(s,t),s}}const Bh=(e,t=null,r=0)=>Gi(new Ph(e,t,r)),Lh=new WeakMap;class Fh extends Ys{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=ks.OBJECT,this.skinIndexNode=rl("skinIndex","uvec4"),this.skinWeightNode=rl("skinWeight","vec4"),this.bindMatrixNode=jd("bindMatrix","mat4"),this.bindMatrixInverseNode=jd("bindMatrixInverse","mat4"),this.boneMatricesNode=Xd("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=ld,this.toPositionNode=ld,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:r,skinWeightNode:s,bindMatrixNode:i,bindMatrixInverseNode:n}=this,a=e.element(r.x),o=e.element(r.y),u=e.element(r.z),l=e.element(r.w),d=i.mul(t),c=fa(a.mul(s.x).mul(d),o.mul(s.y).mul(d),u.mul(s.z).mul(d),l.mul(s.w).mul(d));return n.mul(c).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=Td){const{skinIndexNode:r,skinWeightNode:s,bindMatrixNode:i,bindMatrixInverseNode:n}=this,a=e.element(r.x),o=e.element(r.y),u=e.element(r.z),l=e.element(r.w);let d=fa(s.x.mul(a),s.y.mul(o),s.z.mul(u),s.w.mul(l));return d=n.mul(d).mul(i),d.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Xd("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,dd)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Ds(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&dd.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Td.assign(t),e.hasGeometryAttribute("tangent")&&hc.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;Lh.get(t)!==e.frameId&&(Lh.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}const Ih=e=>Gi(new Fh(e));class Dh extends Ys{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const r={};for(let e=0,t=this.params.length-1;eNumber(u)?">=":"<")),a)n=`while ( ${u} )`;else{const r={start:o,end:u},s=r.start,i=r.end;let a;const p=()=>c.includes("<")?"+=":"-=";if(null!=h)switch(typeof h){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=l+" "+p()+" "+e.generateConst(d,h);break;case"string":a=l+" "+h;break;default:h.isNode?a=l+" "+p()+" "+h.build(e):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),a="break /* invalid update */")}else h="int"===d||"uint"===d?c.includes("<")?"++":"--":p()+" 1.",a=l+" "+h;n=`for ( ${e.getVar(d,l)+" = "+s}; ${l+" "+c+" "+i}; ${a} )`}e.addFlowCode((0===s?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const i=s.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,r=this.params.length-1;tGi(new Dh($i(e,"int"))).toStack(),Vh=()=>Ku("break").toStack(),Oh=new WeakMap,Gh=new s,kh=Ki(({bufferMap:e,influence:t,stride:r,width:s,depth:i,offset:n})=>{const a=rn(yh).mul(r).add(n),o=a.div(s),u=a.sub(o.mul(s));return hl(e,on(u,o)).depth(i).xyz.mul(t)});class zh extends Ys{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=oa(1),this.updateType=ks.OBJECT}setup(e){const{geometry:r}=e,s=void 0!==r.morphAttributes.position,i=r.hasAttribute("normal")&&void 0!==r.morphAttributes.normal,n=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,a=void 0!==n?n.length:0,{texture:o,stride:u,size:l}=function(e){const r=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,n=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,a=void 0!==n?n.length:0;let o=Oh.get(e);if(void 0===o||o.count!==a){void 0!==o&&o.texture.dispose();const u=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],d=e.morphAttributes.color||[];let c=0;!0===r&&(c=1),!0===s&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,p=1;const g=4096;h>g&&(p=Math.ceil(h/g),h=g);const m=new Float32Array(h*p*4*a),f=new F(m,h,p,a);f.type=I,f.needsUpdate=!0;const y=4*c;for(let x=0;x{const t=tn(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(hl(this.mesh.morphTexture,on(rn(e).add(1),rn(bh))).r):t.assign(jd("morphTargetInfluences","float").element(e).toVar()),Zi(t.notEqual(0),()=>{!0===s&&ld.addAssign(kh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:rn(0)})),!0===i&&Td.addAssign(kh({bufferMap:o,influence:t,stride:u,width:d,depth:e,offset:rn(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const $h=Hi(zh).setParameterLength(1);class Hh extends Ys{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Wh extends Hh{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class qh extends nu{static get type(){return"LightingContextNode"}constructor(e,t=null,r=null,s=null){super(e),this.lightingModel=t,this.backdropNode=r,this.backdropAlphaNode=s,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,r={directDiffuse:dn().toVar("directDiffuse"),directSpecular:dn().toVar("directSpecular"),indirectDiffuse:dn().toVar("indirectDiffuse"),indirectSpecular:dn().toVar("indirectSpecular")};return{radiance:dn().toVar("radiance"),irradiance:dn().toVar("irradiance"),iblIrradiance:dn().toVar("iblIrradiance"),ambientOcclusion:tn(1).toVar("ambientOcclusion"),reflectedLight:r,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const jh=Hi(qh);class Xh extends Hh{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const Kh=new t;class Yh extends ll{static get type(){return"ViewportTextureNode"}constructor(e=Nl,t=null,r=null){let s=null;null===r?(s=new D,s.minFilter=U,r=s):s=r,super(r,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=s,this.isOutputTextureNode=!0,this.updateBeforeType=ks.FRAME,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,r;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,r=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,r=this._cacheTextures),null===e)return t;if(!1===r.has(e)){const s=t.clone();r.set(e,s)}return r.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,r=t.getRenderTarget();null===r?t.getDrawingBufferSize(Kh):Kh.set(r.width,r.height);const s=this.getTextureForReference(r);s.image.width===Kh.width&&s.image.height===Kh.height||(s.image.width=Kh.width,s.image.height=Kh.height,s.needsUpdate=!0);const i=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Qh=Hi(Yh).setParameterLength(0,3),Zh=Hi(Yh,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let Jh=null;class ep extends Yh{static get type(){return"ViewportDepthTextureNode"}constructor(e=Nl,t=null){null===Jh&&(Jh=new V),super(e,t,Jh)}getTextureForReference(){return Jh}}const tp=Hi(ep).setParameterLength(0,2);class rp extends Ys{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===rp.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,r=this.valueNode;let s=null;if(t===rp.DEPTH_BASE)null!==r&&(s=op().assign(r));else if(t===rp.DEPTH)s=e.isPerspectiveCamera?ip(pd.z,Bl,Ll):sp(pd.z,Bl,Ll);else if(t===rp.LINEAR_DEPTH)if(null!==r)if(e.isPerspectiveCamera){const e=np(r,Bl,Ll);s=sp(e,Bl,Ll)}else s=r;else s=sp(pd.z,Bl,Ll);return s}}rp.DEPTH_BASE="depthBase",rp.DEPTH="depth",rp.LINEAR_DEPTH="linearDepth";const sp=(e,t,r)=>e.add(t).div(t.sub(r)),ip=(e,t,r)=>t.add(e).mul(r).div(r.sub(t).mul(e)),np=(e,t,r)=>t.mul(r).div(r.sub(t).mul(e).sub(r)),ap=(e,t,r)=>{t=t.max(1e-6).toVar();const s=eo(e.negate().div(t)),i=eo(r.div(t));return s.div(i)},op=Hi(rp,rp.DEPTH_BASE),up=Wi(rp,rp.DEPTH),lp=Hi(rp,rp.LINEAR_DEPTH).setParameterLength(0,1),dp=lp(tp());up.assign=e=>op(e);class cp extends Ys{static get type(){return"ClippingNode"}constructor(e=cp.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:r,unionPlanes:s}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===cp.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(r,s):this.scope===cp.HARDWARE?this.setupHardwareClipping(s,e):this.setupDefault(r,s)}setupAlphaToCoverage(e,t){return Ki(()=>{const r=tn().toVar("distanceToPlane"),s=tn().toVar("distanceToGradient"),i=tn(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=yl(t).setGroup(ia);Uh(n,({i:t})=>{const n=e.element(t);r.assign(pd.dot(n.xyz).negate().add(n.w)),s.assign(r.fwidth().div(2)),i.mulAssign(Xo(s.negate(),s,r))})}const a=e.length;if(a>0){const t=yl(e).setGroup(ia),n=tn(1).toVar("intersectionClipOpacity");Uh(a,({i:e})=>{const i=t.element(e);r.assign(pd.dot(i.xyz).negate().add(i.w)),s.assign(r.fwidth().div(2)),n.mulAssign(Xo(s.negate(),s,r).oneMinus())}),i.mulAssign(n.oneMinus())}Rn.a.mulAssign(i),Rn.a.equal(0).discard()})()}setupDefault(e,t){return Ki(()=>{const r=t.length;if(!1===this.hardwareClipping&&r>0){const e=yl(t).setGroup(ia);Uh(r,({i:t})=>{const r=e.element(t);pd.dot(r.xyz).greaterThan(r.w).discard()})}const s=e.length;if(s>0){const t=yl(e).setGroup(ia),r=nn(!0).toVar("clipped");Uh(s,({i:e})=>{const s=t.element(e);r.assign(pd.dot(s.xyz).greaterThan(s.w).and(r))}),r.discard()}})()}setupHardwareClipping(e,t){const r=e.length;return t.enableHardwareClipping(r),Ki(()=>{const s=yl(e).setGroup(ia),i=bl(t.getClipDistance());Uh(r,({i:e})=>{const t=s.element(e),r=pd.dot(t.xyz).sub(t.w).negate();i.element(e).assign(r)})})()}}cp.ALPHA_TO_COVERAGE="alphaToCoverage",cp.DEFAULT="default",cp.HARDWARE="hardware";const hp=Ki(([e])=>ao(ba(1e4,oo(ba(17,e.x).add(ba(.1,e.y)))).mul(fa(.1,go(oo(ba(13,e.y).add(e.x))))))),pp=Ki(([e])=>hp(an(hp(e.xy),e.z))),gp=Ki(([e])=>{const t=Mo(fo(xo(e.xyz)),fo(To(e.xyz))),r=tn(1).div(tn(.05).mul(t)).toVar("pixScale"),s=an(Za(so(eo(r))),Za(io(eo(r)))),i=an(pp(so(s.x.mul(e.xyz))),pp(so(s.y.mul(e.xyz)))),n=ao(eo(r)),a=fa(ba(n.oneMinus(),i.x),ba(n,i.y)),o=Co(n,n.oneMinus()),u=dn(a.mul(a).div(ba(2,o).mul(ya(1,o))),a.sub(ba(.5,o)).div(ya(1,o)),ya(1,ya(1,a).mul(ya(1,a)).div(ba(2,o).mul(ya(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(u.x,u.y),u.z);return Wo(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class mp extends tl{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let r;return r=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new s(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const fp=(e=0)=>Gi(new mp(e)),yp=Ki(([e,t])=>Co(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),bp=Ki(([e,t])=>Co(e.div(t.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),xp=Ki(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),Tp=Ki(([e,t])=>Ho(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),Po(.5,e))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),_p=Ki(([e,t])=>{const r=t.a.add(e.a.mul(t.a.oneMinus()));return gn(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(r),r)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),vp=Ki(([e])=>gn(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),Np=Ki(([e])=>(Zi(e.a.equal(0),()=>gn(0)),gn(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class Sp extends O{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+Es(this)}build(e){this.setup(e)}setupObserver(e){return new Ts(e)}setup(e){e.context.setupNormal=()=>fu(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,r=t.getRenderTarget();e.addStack();const s=fu(this.setupVertex(e),"VERTEX"),i=this.vertexNode||s;let n;e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==r?!0===r.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const s=this.setupLighting(e);null!==a&&e.stack.add(a);const i=gn(s,Rn.a).max(0);n=this.setupOutput(e,i),Hn.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),null!==r){const e=t.getMRT(),r=this.mrtNode;null!==e?(o&&Hn.assign(n),n=e,null!==r&&(n=e.merge(r))):null!==r&&(n=r)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=gn(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:r}=e.clippingContext;let s=null;if(t.length>0||r.length>0){const t=e.renderer.samples;this.alphaToCoverage&&t>1?s=Gi(new cp(cp.ALPHA_TO_COVERAGE)):e.stack.add(Gi(new cp))}return s}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.add(Gi(new cp(cp.HARDWARE))),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:r}=e;let s=this.depthNode;if(null===s){const e=t.getMRT();e&&e.has("depth")?s=e.get("depth"):!0===t.logarithmicDepthBuffer&&(s=r.isPerspectiveCamera?ap(pd.z,Bl,Ll):sp(pd.z,Bl,Ll))}null!==s&&up.assign(s).toStack()}setupPositionView(){return id.mul(ld).xyz}setupModelViewProjection(){return Fl.mul(pd)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),mh}setupPosition(e){const{object:t,geometry:r}=e;if((r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color)&&$h(t).toStack(),!0===t.isSkinnedMesh&&Ih(t).toStack(),this.displacementMap){const e=Yd("displacementMap","texture"),t=Yd("displacementScale","float"),r=Yd("displacementBias","float");ld.addAssign(Td.normalize().mul(e.x.mul(t).add(r)))}return t.isBatchedMesh&&wh(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Rh(t).toStack(),null!==this.positionNode&&ld.assign(fu(this.positionNode,"POSITION","vec3")),ld}setupDiffuseColor({object:e,geometry:t}){null!==this.maskNode&&nn(this.maskNode).not().discard();let r=this.colorNode?gn(this.colorNode):Bc;if(!0===this.vertexColors&&t.hasAttribute("color")&&(r=r.mul(fp())),e.instanceColor){r=En("vec3","vInstanceColor").mul(r)}if(e.isBatchedMesh&&e._colorsTexture){r=En("vec3","vBatchColor").mul(r)}Rn.assign(r);const s=this.opacityNode?tn(this.opacityNode):Ic;Rn.a.assign(Rn.a.mul(s));let i=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(i=null!==this.alphaTestNode?tn(this.alphaTestNode):Pc,Rn.a.lessThanEqual(i).discard()),!0===this.alphaHash&&Rn.a.lessThan(gp(ld)).discard();!1===this.transparent&&this.blending===G&&!1===this.alphaToCoverage?Rn.a.assign(1):null===i&&Rn.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return!0===this.lights?dn(0):Rn.rgb}setupNormal(){return this.normalNode?dn(this.normalNode):$c}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Yd("envMap","cubeTexture"):Yd("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Xh(hh)),t}setupLights(e){const t=[],r=this.setupEnvironment(e);r&&r.isLightingNode&&t.push(r);const s=this.setupLightMap(e);if(s&&s.isLightingNode&&t.push(s),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:ph;t.push(new Wh(e))}let i=this.lightsNode||e.lightsNode;return t.length>0&&(i=e.renderer.lighting.createNode([...i.getLights(),...t])),i}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:r,backdropAlphaNode:s,emissiveNode:i}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=jh(n,t,r,s)}else null!==r&&(a=dn(null!==s?Ho(a,r,s):r));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(An.assign(dn(i||Fc)),a=a.add(An)),a}setupFog(e,t){const r=e.fogNode;return r&&(Hn.assign(t),t=gn(r.toVar())),t}setupPremultipliedAlpha(e,t){return vp(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const r=e[t];void 0===this[t]&&(this[t]=r,r&&r.clone&&(this[t]=r.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const r=O.prototype.toJSON.call(this,e),s=Rs(this);r.inputNodes={};for(const{property:t,childNode:i}of s)r.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const r in e){const s=e[r];delete s.metadata,t.push(s)}return t}if(t){const t=i(e.textures),s=i(e.images),n=i(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),n.length>0&&(r.nodes=n)}return r}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const Ep=new k;class Rp extends Sp{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Ep),this.setValues(e)}}const Ap=new z;class wp extends Sp{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Ap),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?tn(this.offsetNode):lh,t=this.dashScaleNode?tn(this.dashScaleNode):nh,r=this.dashSizeNode?tn(this.dashSizeNode):ah,s=this.gapSizeNode?tn(this.gapSizeNode):oh;Wn.assign(r),qn.assign(s);const i=bu(rl("lineDistance").mul(t));(e?i.add(e):i).mod(Wn.add(qn)).greaterThan(Wn).discard()}}let Cp=null;class Mp extends Yh{static get type(){return"ViewportSharedTextureNode"}constructor(e=Nl,t=null){null===Cp&&(Cp=new D),super(e,t,Cp)}getTextureForReference(){return Cp}updateReference(){return this}}const Pp=Hi(Mp).setParameterLength(0,2),Bp=new z;class Lp extends Sp{static get type(){return"Line2NodeMaterial"}constructor(e={}){super(),this.isLine2NodeMaterial=!0,this.setDefaultValues(Bp),this.useColor=e.vertexColors,this.dashOffset=0,this.lineColorNode=null,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.blending=$,this._useDash=e.dashed,this._useAlphaToCoverage=!0,this._useWorldUnits=!1,this.setValues(e)}setup(e){const{renderer:t}=e,r=this._useAlphaToCoverage,s=this.useColor,i=this._useDash,n=this._useWorldUnits,a=Ki(({start:e,end:t})=>{const r=Fl.element(2).element(2),s=Fl.element(3).element(2).mul(-.5).div(r).sub(e.z).div(t.z.sub(e.z));return gn(Ho(e.xyz,t.xyz,s),t.w)}).setLayout({name:"trimSegment",type:"vec4",inputs:[{name:"start",type:"vec4"},{name:"end",type:"vec4"}]});this.vertexNode=Ki(()=>{const e=rl("instanceStart"),t=rl("instanceEnd"),r=gn(id.mul(gn(e,1))).toVar("start"),s=gn(id.mul(gn(t,1))).toVar("end");if(i){const e=this.dashScaleNode?tn(this.dashScaleNode):nh,t=this.offsetNode?tn(this.offsetNode):lh,r=rl("instanceDistanceStart"),s=rl("instanceDistanceEnd");let i=ud.y.lessThan(.5).select(e.mul(r),e.mul(s));i=i.add(t),En("float","lineDistance").assign(i)}n&&(En("vec3","worldStart").assign(r.xyz),En("vec3","worldEnd").assign(s.xyz));const o=Rl.z.div(Rl.w),u=Fl.element(2).element(3).equal(-1);Zi(u,()=>{Zi(r.z.lessThan(0).and(s.z.greaterThan(0)),()=>{s.assign(a({start:r,end:s}))}).ElseIf(s.z.lessThan(0).and(r.z.greaterThanEqual(0)),()=>{r.assign(a({start:s,end:r}))})});const l=Fl.mul(r),d=Fl.mul(s),c=l.xyz.div(l.w),h=d.xyz.div(d.w),p=h.xy.sub(c.xy).toVar();p.x.assign(p.x.mul(o)),p.assign(p.normalize());const g=gn().toVar();if(n){const e=s.xyz.sub(r.xyz).normalize(),t=Ho(r.xyz,s.xyz,.5).normalize(),n=e.cross(t).normalize(),a=e.cross(n),o=En("vec4","worldPos");o.assign(ud.y.lessThan(.5).select(r,s));const u=uh.mul(.5);o.addAssign(gn(ud.x.lessThan(0).select(n.mul(u),n.mul(u).negate()),0)),i||(o.addAssign(gn(ud.y.lessThan(.5).select(e.mul(u).negate(),e.mul(u)),0)),o.addAssign(gn(a.mul(u),0)),Zi(ud.y.greaterThan(1).or(ud.y.lessThan(0)),()=>{o.subAssign(gn(a.mul(2).mul(u),0))})),g.assign(Fl.mul(o));const l=dn().toVar();l.assign(ud.y.lessThan(.5).select(c,h)),g.z.assign(l.z.mul(g.w))}else{const e=an(p.y,p.x.negate()).toVar("offset");p.x.assign(p.x.div(o)),e.x.assign(e.x.div(o)),e.assign(ud.x.lessThan(0).select(e.negate(),e)),Zi(ud.y.lessThan(0),()=>{e.assign(e.sub(p))}).ElseIf(ud.y.greaterThan(1),()=>{e.assign(e.add(p))}),e.assign(e.mul(uh)),e.assign(e.div(Rl.w)),g.assign(ud.y.lessThan(.5).select(l,d)),e.assign(e.mul(g.w)),g.assign(g.add(gn(e,0,0)))}return g})();const o=Ki(({p1:e,p2:t,p3:r,p4:s})=>{const i=e.sub(r),n=s.sub(r),a=t.sub(e),o=i.dot(n),u=n.dot(a),l=i.dot(a),d=n.dot(n),c=a.dot(a).mul(d).sub(u.mul(u)),h=o.mul(u).sub(l.mul(d)).div(c).clamp(),p=o.add(u.mul(h)).div(d).clamp();return an(h,p)});if(this.colorNode=Ki(()=>{const e=sl();if(i){const t=this.dashSizeNode?tn(this.dashSizeNode):ah,r=this.gapSizeNode?tn(this.gapSizeNode):oh;Wn.assign(t),qn.assign(r);const s=En("float","lineDistance");e.y.lessThan(-1).or(e.y.greaterThan(1)).discard(),s.mod(Wn.add(qn)).greaterThan(Wn).discard()}const a=tn(1).toVar("alpha");if(n){const e=En("vec3","worldStart"),s=En("vec3","worldEnd"),n=En("vec4","worldPos").xyz.normalize().mul(1e5),u=s.sub(e),l=o({p1:e,p2:s,p3:dn(0,0,0),p4:n}),d=e.add(u.mul(l.x)),c=n.mul(l.y),h=d.sub(c).length().div(uh);if(!i)if(r&&t.samples>1){const e=h.fwidth();a.assign(Xo(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(r&&t.samples>1){const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1)),s=t.mul(t).add(r.mul(r)),i=tn(s.fwidth()).toVar("dlen");Zi(e.y.abs().greaterThan(1),()=>{a.assign(Xo(i.oneMinus(),i.add(1),s).oneMinus())})}else Zi(e.y.abs().greaterThan(1),()=>{const t=e.x,r=e.y.greaterThan(0).select(e.y.sub(1),e.y.add(1));t.mul(t).add(r.mul(r)).greaterThan(1).discard()});let u;if(this.lineColorNode)u=this.lineColorNode;else if(s){const e=rl("instanceColorStart"),t=rl("instanceColorEnd");u=ud.y.lessThan(.5).select(e,t).mul(Bc)}else u=Bc;return gn(u,a)})(),this.transparent){const e=this.opacityNode?tn(this.opacityNode):Ic;this.outputNode=gn(this.colorNode.rgb.mul(e).add(Pp().rgb.mul(e.oneMinus())),this.colorNode.a)}super.setup(e)}get worldUnits(){return this._useWorldUnits}set worldUnits(e){this._useWorldUnits!==e&&(this._useWorldUnits=e,this.needsUpdate=!0)}get dashed(){return this._useDash}set dashed(e){this._useDash!==e&&(this._useDash=e,this.needsUpdate=!0)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const Fp=e=>Gi(e).mul(.5).add(.5),Ip=new H;class Dp extends Sp{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Ip),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?tn(this.opacityNode):Ic;Rn.assign(Eu(gn(Fp(Sd),e),W))}}const Up=Ki(([e=hd])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),r=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return an(t,r)});class Vp extends q{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const r=t.minFilter,s=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i=new j(5,5,5),n=Up(hd),a=new Sp;a.colorNode=cl(t,n,0),a.side=S,a.blending=$;const o=new X(i,a),u=new K;u.add(o),t.minFilter===U&&(t.minFilter=Y);const l=new Q(1,10,this),d=e.getMRT();return e.setMRT(null),l.update(e,u),e.setMRT(d),t.minFilter=r,t.currentGenerateMipmaps=s,o.geometry.dispose(),o.material.dispose(),this}}const Op=new WeakMap;class Gp extends Js{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Hd(null);const t=new A;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=ks.RENDER}updateBefore(e){const{renderer:t,material:r}=e,s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:r[s.property];if(e&&e.isTexture){const r=e.mapping;if(r===Z||r===J){if(Op.has(e)){const t=Op.get(e);zp(t,e.mapping),this._cubeTexture=t}else{const r=e.image;if(function(e){return null!=e&&e.height>0}(r)){const s=new Vp(r.height);s.fromEquirectangularTexture(t,e),zp(s.texture,e.mapping),this._cubeTexture=s.texture,Op.set(e,s.texture),e.addEventListener("dispose",kp)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function kp(e){const t=e.target;t.removeEventListener("dispose",kp);const r=Op.get(t);void 0!==r&&(Op.delete(t),r.dispose())}function zp(e,t){t===Z?e.mapping=w:t===J&&(e.mapping=C)}const $p=Hi(Gp).setParameterLength(1);class Hp extends Hh{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=$p(this.envNode)}}class Wp extends Hh{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=tn(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class qp{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class jp extends qp{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,r=e.reflectedLight,s=e.irradianceLightMap;r.indirectDiffuse.assign(gn(0)),s?r.indirectDiffuse.addAssign(s):r.indirectDiffuse.addAssign(gn(1,1,1,0)),r.indirectDiffuse.mulAssign(t),r.indirectDiffuse.mulAssign(Rn.rgb)}finish(e){const{material:t,context:r}=e,s=r.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case re:s.rgb.assign(Ho(s.rgb,s.rgb.mul(i.rgb),Oc.mul(Gc)));break;case te:s.rgb.assign(Ho(s.rgb,i.rgb,Oc.mul(Gc)));break;case ee:s.rgb.addAssign(i.rgb.mul(Oc.mul(Gc)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Xp=new se;class Kp extends Sp{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Xp),this.setValues(e)}setupNormal(){return bd(vd)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Hp(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Wp(hh)),t}setupOutgoingLight(){return Rn.rgb}setupLightingModel(){return new jp}}const Yp=Ki(({f0:e,f90:t,dotVH:r})=>{const s=r.mul(-5.55473).sub(6.98316).mul(r).exp2();return e.mul(s.oneMinus()).add(t.mul(s))}),Qp=Ki(e=>e.diffuseColor.mul(1/Math.PI)),Zp=Ki(({dotNH:e})=>$n.mul(tn(.5)).add(1).mul(tn(1/Math.PI)).mul(e.pow($n))),Jp=Ki(({lightDirection:e})=>{const t=e.add(gd).normalize(),r=Sd.dot(t).clamp(),s=gd.dot(t).clamp(),i=Yp({f0:kn,f90:1,dotVH:s}),n=tn(.25),a=Zp({dotNH:r});return i.mul(n).mul(a)});class eg extends jp{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sd.dot(e).clamp().mul(t);r.directDiffuse.addAssign(s.mul(Qp({diffuseColor:Rn.rgb}))),!0===this.specular&&r.directSpecular.addAssign(s.mul(Jp({lightDirection:e})).mul(Oc))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Qp({diffuseColor:Rn}))),s.indirectDiffuse.mulAssign(t)}}const tg=new ie;class rg extends Sp{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(tg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Hp(t):null}setupLightingModel(){return new eg(!1)}}const sg=new ne;class ig extends Sp{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(sg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Hp(t):null}setupLightingModel(){return new eg}setupVariants(){const e=(this.shininessNode?tn(this.shininessNode):Lc).max(1e-4);$n.assign(e);const t=this.specularNode||Dc;kn.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const ng=Ki(e=>{if(!1===e.geometry.hasAttribute("normal"))return tn(0);const t=vd.dFdx().abs().max(vd.dFdy().abs());return t.x.max(t.y).max(t.z)}),ag=Ki(e=>{const{roughness:t}=e,r=ng();let s=t.max(.0525);return s=s.add(r),s=s.min(1),s}),og=Ki(({alpha:e,dotNL:t,dotNV:r})=>{const s=e.pow2(),i=t.mul(s.add(s.oneMinus().mul(r.pow2())).sqrt()),n=r.mul(s.add(s.oneMinus().mul(t.pow2())).sqrt());return xa(.5,i.add(n).max($a))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),ug=Ki(({alphaT:e,alphaB:t,dotTV:r,dotBV:s,dotTL:i,dotBL:n,dotNV:a,dotNL:o})=>{const u=o.mul(dn(e.mul(r),t.mul(s),a).length()),l=a.mul(dn(e.mul(i),t.mul(n),o).length());return xa(.5,u.add(l)).saturate()}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),lg=Ki(({alpha:e,dotNH:t})=>{const r=e.pow2(),s=t.pow2().mul(r.oneMinus()).oneMinus();return r.div(s.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),dg=tn(1/Math.PI),cg=Ki(({alphaT:e,alphaB:t,dotNH:r,dotTH:s,dotBH:i})=>{const n=e.mul(t),a=dn(t.mul(s),e.mul(i),n.mul(r)),o=a.dot(a),u=n.div(o);return dg.mul(n.mul(u.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),hg=Ki(({lightDirection:e,f0:t,f90:r,roughness:s,f:i,normalView:n=Sd,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const u=s.pow2(),l=e.add(gd).normalize(),d=n.dot(e).clamp(),c=n.dot(gd).clamp(),h=n.dot(l).clamp(),p=gd.dot(l).clamp();let g,m,f=Yp({f0:t,f90:r,dotVH:p});if(Ui(a)&&(f=Fn.mix(f,i)),Ui(o)){const t=On.dot(e),r=On.dot(gd),s=On.dot(l),i=Gn.dot(e),n=Gn.dot(gd),a=Gn.dot(l);g=ug({alphaT:Un,alphaB:u,dotTV:r,dotBV:n,dotTL:t,dotBL:i,dotNV:c,dotNL:d}),m=cg({alphaT:Un,alphaB:u,dotNH:h,dotTH:s,dotBH:a})}else g=og({alpha:u,dotNL:d,dotNV:c}),m=lg({alpha:u,dotNH:h});return f.mul(g).mul(m)}),pg=Ki(({roughness:e,dotNV:t})=>{const r=gn(-1,-.0275,-.572,.022),s=gn(1,.0425,1.04,-.04),i=e.mul(r).add(s),n=i.x.mul(i.x).min(t.mul(-9.28).exp2()).mul(i.x).add(i.y);return an(-1.04,1.04).mul(n).add(i.zw)}).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),gg=Ki(e=>{const{dotNV:t,specularColor:r,specularF90:s,roughness:i}=e,n=pg({dotNV:t,roughness:i});return r.mul(n.x).add(s.mul(n.y))}),mg=Ki(({f:e,f90:t,dotVH:r})=>{const s=r.oneMinus().saturate(),i=s.mul(s),n=s.mul(i,i).clamp(0,.9999);return e.sub(dn(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),fg=Ki(({roughness:e,dotNH:t})=>{const r=e.pow2(),s=tn(1).div(r),i=t.pow2().oneMinus().max(.0078125);return tn(2).add(s).mul(i.pow(s.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),yg=Ki(({dotNV:e,dotNL:t})=>tn(1).div(tn(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),bg=Ki(({lightDirection:e})=>{const t=e.add(gd).normalize(),r=Sd.dot(e).clamp(),s=Sd.dot(gd).clamp(),i=Sd.dot(t).clamp(),n=fg({roughness:Ln,dotNH:i}),a=yg({dotNV:s,dotNL:r});return Bn.mul(n).mul(a)}),xg=Ki(({N:e,V:t,roughness:r})=>{const s=e.dot(t).saturate(),i=an(r,s.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),Tg=Ki(({f:e})=>{const t=e.length();return Mo(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),_g=Ki(({v1:e,v2:t})=>{const r=e.dot(t),s=r.abs().toVar(),i=s.mul(.0145206).add(.4965155).mul(s).add(.8543985).toVar(),n=s.add(4.1616724).mul(s).add(3.417594).toVar(),a=i.div(n),o=r.greaterThan(0).select(a,Mo(r.mul(r).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),vg=Ki(({N:e,V:t,P:r,mInv:s,p0:i,p1:n,p2:a,p3:o})=>{const u=n.sub(i).toVar(),l=o.sub(i).toVar(),d=u.cross(l),c=dn().toVar();return Zi(d.dot(r.sub(i)).greaterThanEqual(0),()=>{const u=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(u).negate(),d=s.mul(xn(u,l,e).transpose()).toVar(),h=d.mul(i.sub(r)).normalize().toVar(),p=d.mul(n.sub(r)).normalize().toVar(),g=d.mul(a.sub(r)).normalize().toVar(),m=d.mul(o.sub(r)).normalize().toVar(),f=dn(0).toVar();f.addAssign(_g({v1:h,v2:p})),f.addAssign(_g({v1:p,v2:g})),f.addAssign(_g({v1:g,v2:m})),f.addAssign(_g({v1:m,v2:h})),c.assign(dn(Tg({f:f})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Ng=Ki(({P:e,p0:t,p1:r,p2:s,p3:i})=>{const n=r.sub(t).toVar(),a=i.sub(t).toVar(),o=n.cross(a),u=dn().toVar();return Zi(o.dot(e.sub(t)).greaterThanEqual(0),()=>{const n=t.sub(e).normalize().toVar(),a=r.sub(e).normalize().toVar(),o=s.sub(e).normalize().toVar(),l=i.sub(e).normalize().toVar(),d=dn(0).toVar();d.addAssign(_g({v1:n,v2:a})),d.addAssign(_g({v1:a,v2:o})),d.addAssign(_g({v1:o,v2:l})),d.addAssign(_g({v1:l,v2:n})),u.assign(dn(Tg({f:d.abs()})))}),u}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"P",type:"vec3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),Sg=1/6,Eg=e=>ba(Sg,ba(e,ba(e,e.negate().add(3)).sub(3)).add(1)),Rg=e=>ba(Sg,ba(e,ba(e,ba(3,e).sub(6))).add(4)),Ag=e=>ba(Sg,ba(e,ba(e,ba(-3,e).add(3)).add(3)).add(1)),wg=e=>ba(Sg,Uo(e,3)),Cg=e=>Eg(e).add(Rg(e)),Mg=e=>Ag(e).add(wg(e)),Pg=e=>fa(-1,Rg(e).div(Eg(e).add(Rg(e)))),Bg=e=>fa(1,wg(e).div(Ag(e).add(wg(e)))),Lg=(e,t,r)=>{const s=e.uvNode,i=ba(s,t.zw).add(.5),n=so(i),a=ao(i),o=Cg(a.x),u=Mg(a.x),l=Pg(a.x),d=Bg(a.x),c=Pg(a.y),h=Bg(a.y),p=an(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=an(n.x.add(d),n.y.add(c)).sub(.5).mul(t.xy),m=an(n.x.add(l),n.y.add(h)).sub(.5).mul(t.xy),f=an(n.x.add(d),n.y.add(h)).sub(.5).mul(t.xy),y=Cg(a.y).mul(fa(o.mul(e.sample(p).level(r)),u.mul(e.sample(g).level(r)))),b=Mg(a.y).mul(fa(o.mul(e.sample(m).level(r)),u.mul(e.sample(f).level(r))));return y.add(b)},Fg=Ki(([e,t])=>{const r=an(e.size(rn(t))),s=an(e.size(rn(t.add(1)))),i=xa(1,r),n=xa(1,s),a=Lg(e,gn(i,r),so(t)),o=Lg(e,gn(n,s),io(t));return ao(t).mix(a,o)}),Ig=Ki(([e,t])=>{const r=t.mul(ol(e));return Fg(e,r)}),Dg=Ki(([e,t,r,s,i])=>{const n=dn(jo(t.negate(),no(e),xa(1,s))),a=dn(fo(i[0].xyz),fo(i[1].xyz),fo(i[2].xyz));return no(n).mul(r.mul(a))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),Ug=Ki(([e,t])=>e.mul(Wo(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Vg=Zh(),Og=Zh(),Gg=Ki(([e,t,r],{material:s})=>{const i=(s.side===S?Vg:Og).sample(e),n=eo(Sl.x).mul(Ug(t,r));return Fg(i,n)}),kg=Ki(([e,t,r])=>(Zi(r.notEqual(0),()=>{const s=Ja(t).negate().div(r);return Qa(s.negate().mul(e))}),dn(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),zg=Ki(([e,t,r,s,i,n,a,o,u,l,d,c,h,p,g])=>{let m,f;if(g){m=gn().toVar(),f=dn().toVar();const i=d.sub(1).mul(g.mul(.025)),n=dn(d.sub(i),d,d.add(i));Uh({start:0,end:3},({i:i})=>{const d=n.element(i),g=Dg(e,t,c,d,o),y=a.add(g),b=l.mul(u.mul(gn(y,1))),x=an(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(an(x.x,x.y.oneMinus()));const T=Gg(x,r,d);m.element(i).assign(T.element(i)),m.a.addAssign(T.a),f.element(i).assign(s.element(i).mul(kg(fo(g),h,p).element(i)))}),m.a.divAssign(3)}else{const i=Dg(e,t,c,d,o),n=a.add(i),g=l.mul(u.mul(gn(n,1))),y=an(g.xy.div(g.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(an(y.x,y.y.oneMinus())),m=Gg(y,r,d),f=s.mul(kg(fo(i),h,p))}const y=f.rgb.mul(m.rgb),b=e.dot(t).clamp(),x=dn(gg({dotNV:b,specularColor:i,specularF90:n,roughness:r})),T=f.r.add(f.g,f.b).div(3);return gn(x.oneMinus().mul(y),m.a.oneMinus().mul(T).oneMinus())}),$g=xn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Hg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),Wg=Ki(({outsideIOR:e,eta2:t,cosTheta1:r,thinFilmThickness:s,baseF0:i})=>{const n=Ho(e,t,Xo(0,.03,s)),a=e.div(n).pow2().mul(r.pow2().oneMinus()).oneMinus();Zi(a.lessThan(0),()=>dn(1));const o=a.sqrt(),u=Hg(n,e),l=Yp({f0:u,f90:1,dotVH:r}),d=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),h=tn(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return dn(1).add(t).div(dn(1).sub(t))})(i.clamp(0,.9999)),g=Hg(p,n.toVec3()),m=Yp({f0:g,f90:1,dotVH:o}),f=dn(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(s,o,2),b=dn(h).add(f),x=l.mul(m).clamp(1e-5,.9999),T=x.sqrt(),_=d.pow2().mul(m).div(dn(1).sub(x)),v=l.add(_).toVar(),N=_.sub(d).toVar();return Uh({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{N.mulAssign(T);const t=((e,t)=>{const r=e.mul(2*Math.PI*1e-9),s=dn(54856e-17,44201e-17,52481e-17),i=dn(1681e3,1795300,2208400),n=dn(43278e5,93046e5,66121e5),a=tn(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(r.mul(2239900).add(t.x).cos()).mul(r.pow2().mul(-45282e5).exp());let o=s.mul(n.mul(2*Math.PI).sqrt()).mul(i.mul(r).add(t).cos()).mul(r.pow2().negate().mul(n).exp());return o=dn(o.x.add(a),o.y,o.z).div(1.0685e-7),$g.mul(o)})(tn(e).mul(y),tn(e).mul(b)).mul(2);v.addAssign(N.mul(t))}),v.max(dn(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),qg=Ki(({normal:e,viewDir:t,roughness:r})=>{const s=e.dot(t).saturate(),i=r.pow2(),n=iu(r.lessThan(.25),tn(-339.2).mul(i).add(tn(161.4).mul(r)).sub(25.9),tn(-8.48).mul(i).add(tn(14.3).mul(r)).sub(9.95)),a=iu(r.lessThan(.25),tn(44).mul(i).sub(tn(23.7).mul(r)).add(3.26),tn(1.97).mul(i).sub(tn(3.27).mul(r)).add(.72));return iu(r.lessThan(.25),0,tn(.1).mul(r).sub(.025)).add(n.mul(s).add(a).exp()).mul(1/Math.PI).saturate()}),jg=dn(.04),Xg=tn(1);class Kg extends qp{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=r,this.anisotropy=s,this.transmission=i,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=dn().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=dn().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=dn().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=dn().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=dn().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Sd.dot(gd).clamp();this.iridescenceFresnel=Wg({outsideIOR:tn(1),eta2:In,cosTheta1:e,thinFilmThickness:Dn,baseF0:kn}),this.iridescenceF0=mg({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=cd,r=Ol.sub(cd).normalize(),s=Ed,i=e.context;i.backdrop=zg(s,r,wn,Rn,kn,zn,t,Ql,Dl,Fl,Xn,Yn,Zn,Qn,this.dispersion?Jn:null),i.backdropAlpha=Kn,Rn.a.mulAssign(Ho(1,i.backdrop.a,Kn))}super.start(e)}computeMultiscattering(e,t,r){const s=Sd.dot(gd).clamp(),i=pg({roughness:wn,dotNV:s}),n=(this.iridescenceF0?Fn.mix(kn,this.iridescenceF0):kn).mul(i.x).add(r.mul(i.y)),a=i.x.add(i.y).oneMinus(),o=kn.add(kn.oneMinus().mul(.047619)),u=n.mul(o).div(a.mul(o).oneMinus());e.addAssign(n),t.addAssign(u.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:r}){const s=Sd.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(s.mul(bg({lightDirection:e}))),!0===this.clearcoat){const r=Rd.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(r.mul(hg({lightDirection:e,f0:jg,f90:Xg,roughness:Pn,normalView:Rd})))}r.directDiffuse.addAssign(s.mul(Qp({diffuseColor:Rn.rgb}))),r.directSpecular.addAssign(s.mul(hg({lightDirection:e,f0:kn,f90:1,roughness:wn,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s,reflectedLight:i,ltc_1:n,ltc_2:a}){const o=t.add(r).sub(s),u=t.sub(r).sub(s),l=t.sub(r).add(s),d=t.add(r).add(s),c=Sd,h=gd,p=pd.toVar(),g=xg({N:c,V:h,roughness:wn}),m=n.sample(g).toVar(),f=a.sample(g).toVar(),y=xn(dn(m.x,0,m.y),dn(0,1,0),dn(m.z,0,m.w)).toVar(),b=kn.mul(f.x).add(kn.oneMinus().mul(f.y)).toVar();i.directSpecular.addAssign(e.mul(b).mul(vg({N:c,V:h,P:p,mInv:y,p0:o,p1:u,p2:l,p3:d}))),i.directDiffuse.addAssign(e.mul(Rn).mul(vg({N:c,V:h,P:p,mInv:xn(1,0,0,0,1,0,0,0,1),p0:o,p1:u,p2:l,p3:d})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(t.mul(Qp({diffuseColor:Rn})))}indirectSpecular(e){const{radiance:t,iblIrradiance:r,reflectedLight:s}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(r.mul(Bn,qg({normal:Sd,viewDir:gd,roughness:Ln}))),!0===this.clearcoat){const e=Rd.dot(gd).clamp(),t=gg({dotNV:e,specularColor:jg,specularF90:Xg,roughness:Pn});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=dn().toVar("singleScattering"),n=dn().toVar("multiScattering"),a=r.mul(1/Math.PI);this.computeMultiscattering(i,n,zn);const o=i.add(n),u=Rn.mul(o.r.max(o.g).max(o.b).oneMinus());s.indirectSpecular.addAssign(t.mul(i)),s.indirectSpecular.addAssign(n.mul(a)),s.indirectDiffuse.addAssign(u.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:r}=e.context,s=Sd.dot(gd).clamp().add(t),i=wn.mul(-16).oneMinus().negate().exp2(),n=t.sub(s.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),r.indirectDiffuse.mulAssign(t),r.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Rd.dot(gd).clamp(),r=Yp({dotVH:e,f0:jg,f90:Xg}),s=t.mul(Mn.mul(r).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Mn));t.assign(s)}if(!0===this.sheen){const e=Bn.r.max(Bn.g).max(Bn.b).mul(.157).oneMinus(),r=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(r)}}}const Yg=tn(1),Qg=tn(-2),Zg=tn(.8),Jg=tn(-1),em=tn(.4),tm=tn(2),rm=tn(.305),sm=tn(3),im=tn(.21),nm=tn(4),am=tn(4),om=tn(16),um=Ki(([e])=>{const t=dn(go(e)).toVar(),r=tn(-1).toVar();return Zi(t.x.greaterThan(t.z),()=>{Zi(t.x.greaterThan(t.y),()=>{r.assign(iu(e.x.greaterThan(0),0,3))}).Else(()=>{r.assign(iu(e.y.greaterThan(0),1,4))})}).Else(()=>{Zi(t.z.greaterThan(t.y),()=>{r.assign(iu(e.z.greaterThan(0),2,5))}).Else(()=>{r.assign(iu(e.y.greaterThan(0),1,4))})}),r}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),lm=Ki(([e,t])=>{const r=an().toVar();return Zi(t.equal(0),()=>{r.assign(an(e.z,e.y).div(go(e.x)))}).ElseIf(t.equal(1),()=>{r.assign(an(e.x.negate(),e.z.negate()).div(go(e.y)))}).ElseIf(t.equal(2),()=>{r.assign(an(e.x.negate(),e.y).div(go(e.z)))}).ElseIf(t.equal(3),()=>{r.assign(an(e.z.negate(),e.y).div(go(e.x)))}).ElseIf(t.equal(4),()=>{r.assign(an(e.x.negate(),e.z).div(go(e.y)))}).Else(()=>{r.assign(an(e.x,e.y).div(go(e.z)))}),ba(.5,r.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),dm=Ki(([e])=>{const t=tn(0).toVar();return Zi(e.greaterThanEqual(Zg),()=>{t.assign(Yg.sub(e).mul(Jg.sub(Qg)).div(Yg.sub(Zg)).add(Qg))}).ElseIf(e.greaterThanEqual(em),()=>{t.assign(Zg.sub(e).mul(tm.sub(Jg)).div(Zg.sub(em)).add(Jg))}).ElseIf(e.greaterThanEqual(rm),()=>{t.assign(em.sub(e).mul(sm.sub(tm)).div(em.sub(rm)).add(tm))}).ElseIf(e.greaterThanEqual(im),()=>{t.assign(rm.sub(e).mul(nm.sub(sm)).div(rm.sub(im)).add(sm))}).Else(()=>{t.assign(tn(-2).mul(eo(ba(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),cm=Ki(([e,t])=>{const r=e.toVar();r.assign(ba(2,r).sub(1));const s=dn(r,1).toVar();return Zi(t.equal(0),()=>{s.assign(s.zyx)}).ElseIf(t.equal(1),()=>{s.assign(s.xzy),s.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{s.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{s.assign(s.zyx),s.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{s.assign(s.xzy),s.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{s.z.mulAssign(-1)}),s}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),hm=Ki(([e,t,r,s,i,n])=>{const a=tn(r),o=dn(t),u=Wo(dm(a),Qg,n),l=ao(u),d=so(u),c=dn(pm(e,o,d,s,i,n)).toVar();return Zi(l.notEqual(0),()=>{const t=dn(pm(e,o,d.add(1),s,i,n)).toVar();c.assign(Ho(c,t,l))}),c}),pm=Ki(([e,t,r,s,i,n])=>{const a=tn(r).toVar(),o=dn(t),u=tn(um(o)).toVar(),l=tn(Mo(am.sub(a),0)).toVar();a.assign(Mo(a,am));const d=tn(Za(a)).toVar(),c=an(lm(o,u).mul(d.sub(2)).add(1)).toVar();return Zi(u.greaterThan(2),()=>{c.y.addAssign(d),u.subAssign(3)}),c.x.addAssign(u.mul(d)),c.x.addAssign(l.mul(ba(3,om))),c.y.addAssign(ba(4,Za(n).sub(d))),c.x.mulAssign(s),c.y.mulAssign(i),e.sample(c).grad(an(),an())}),gm=Ki(({envMap:e,mipInt:t,outputDirection:r,theta:s,axis:i,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const u=uo(s),l=r.mul(u).add(i.cross(r).mul(oo(s))).add(i.mul(i.dot(r).mul(u.oneMinus())));return pm(e,l,t,n,a,o)}),mm=Ki(({n:e,latitudinal:t,poleAxis:r,outputDirection:s,weights:i,samples:n,dTheta:a,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})=>{const h=dn(iu(t,r,Do(r,s))).toVar();Zi(h.equal(dn(0)),()=>{h.assign(dn(s.z,0,s.x.negate()))}),h.assign(no(h));const p=dn().toVar();return p.addAssign(i.element(0).mul(gm({theta:0,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),Uh({start:rn(1),end:e},({i:e})=>{Zi(e.greaterThanEqual(n),()=>{Vh()});const t=tn(a.mul(tn(e))).toVar();p.addAssign(i.element(e).mul(gm({theta:t.mul(-1),axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c}))),p.addAssign(i.element(e).mul(gm({theta:t,axis:h,outputDirection:s,mipInt:o,envMap:u,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:c})))}),gn(p,1)}),fm=[.125,.215,.35,.446,.526,.582],ym=20,bm=new ae(-1,1,1,-1,0,1),xm=new oe(90,1),Tm=new e;let _m=null,vm=0,Nm=0;const Sm=(1+Math.sqrt(5))/2,Em=1/Sm,Rm=[new r(-Sm,Em,0),new r(Sm,Em,0),new r(-Em,0,Sm),new r(Em,0,Sm),new r(0,Sm,-Em),new r(0,Sm,Em),new r(-1,1,-1),new r(1,1,-1),new r(-1,1,1),new r(1,1,1)],Am=new r,wm=new WeakMap,Cm=[3,1,5,0,4,2],Mm=cm(sl(),rl("faceIndex")).normalize(),Pm=dn(Mm.x,Mm.y,Mm.z);class Bm{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,r=.1,s=100,i={}){const{size:n=256,position:a=Am,renderTarget:o=null}=i;if(this._setSize(n),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const n=o||this._allocateTarget();return i.renderTarget=n,this.fromSceneAsync(e,t,r,s,i),n}_m=this._renderer.getRenderTarget(),vm=this._renderer.getActiveCubeFace(),Nm=this._renderer.getActiveMipmapLevel();const u=o||this._allocateTarget();return u.depthBuffer=!0,this._init(u),this._sceneToCubeUV(e,r,s,u,a),t>0&&this._blur(u,0,0,t),this._applyPMREM(u),this._cleanup(u),u}async fromSceneAsync(e,t=0,r=.1,s=100,i={}){return!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,r,s,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromEquirectangularAsync(e,r),r}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const r=t||this._allocateTarget();return this.fromCubemapAsync(e,t),r}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Dm(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Um(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===w||e.mapping===C?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?u=fm[o-e+4-1]:0===o&&(u=0),s.push(u);const l=1/(a-2),d=-l,c=1+l,h=[d,d,c,d,c,c,d,d,c,c,d,c],p=6,g=6,m=3,f=2,y=1,b=new Float32Array(m*g*p),x=new Float32Array(f*g*p),T=new Float32Array(y*g*p);for(let e=0;e2?0:-1,s=[t,r,0,t+2/3,r,0,t+2/3,r+1,0,t,r,0,t+2/3,r+1,0,t,r+1,0],i=Cm[e];b.set(s,m*g*i),x.set(h,f*g*i);const n=[i,i,i,i,i,i];T.set(n,y*g*i)}const _=new pe;_.setAttribute("position",new ge(b,m)),_.setAttribute("uv",new ge(x,f)),_.setAttribute("faceIndex",new ge(T,y)),t.push(_),i.push(new X(_,null)),n>4&&n--}return{lodPlanes:t,sizeLods:r,sigmas:s,lodMeshes:i}}(t)),this._blurMaterial=function(e,t,s){const i=yl(new Array(ym).fill(0)),n=oa(new r(0,1,0)),a=oa(0),o=tn(ym),u=oa(0),l=oa(1),d=cl(null),c=oa(0),h=tn(1/t),p=tn(1/s),g=tn(e),m={n:o,latitudinal:u,weights:i,poleAxis:n,outputDirection:Pm,dTheta:a,samples:l,envMap:d,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:p,CUBEUV_MAX_MIP:g},f=Im("blur");return f.fragmentNode=mm({...m,latitudinal:u.equal(1)}),wm.set(f,m),f}(t,e.width,e.height)}}async _compileMaterial(e){const t=new X(this._lodPlanes[0],e);await this._renderer.compile(t,bm)}_sceneToCubeUV(e,t,r,s,i){const n=xm;n.near=t,n.far=r;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],u=this._renderer,l=u.autoClear;u.getClearColor(Tm),u.autoClear=!1;let d=this._backgroundBox;if(null===d){const e=new se({name:"PMREM.Background",side:S,depthWrite:!1,depthTest:!1});d=new X(new j,e)}let c=!1;const h=e.background;h?h.isColor&&(d.material.color.copy(h),e.background=null,c=!0):(d.material.color.copy(Tm),c=!0),u.setRenderTarget(s),u.clear(),c&&u.render(d,n);for(let t=0;t<6;t++){const r=t%3;0===r?(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x+o[t],i.y,i.z)):1===r?(n.up.set(0,0,a[t]),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y+o[t],i.z)):(n.up.set(0,a[t],0),n.position.set(i.x,i.y,i.z),n.lookAt(i.x,i.y,i.z+o[t]));const l=this._cubeSize;Fm(s,r*l,t>2?l:0,l,l),u.render(e,n)}u.autoClear=l,e.background=h}_textureToCubeUV(e,t){const r=this._renderer,s=e.mapping===w||e.mapping===C;s?null===this._cubemapMaterial&&(this._cubemapMaterial=Dm(e)):null===this._equirectMaterial&&(this._equirectMaterial=Um(e));const i=s?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=i;const a=this._cubeSize;Fm(t,0,0,3*a,2*a),r.setRenderTarget(t),r.render(n,bm)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let t=1;tym&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${g} samples when the maximum is set to 20`);const m=[];let f=0;for(let e=0;ey-4?s-y+4:0),4*(this._cubeSize-b),3*b,2*b),o.setRenderTarget(t),o.render(l,bm)}}function Lm(e,t){const r=new ue(e,t,{magFilter:Y,minFilter:Y,generateMipmaps:!1,type:ce,format:de,colorSpace:le});return r.texture.mapping=he,r.texture.name="PMREM.cubeUv",r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function Fm(e,t,r,s,i){e.viewport.set(t,r,s,i),e.scissor.set(t,r,s,i)}function Im(e){const t=new Sp;return t.depthTest=!1,t.depthWrite=!1,t.blending=$,t.name=`PMREM_${e}`,t}function Dm(e){const t=Im("cubemap");return t.fragmentNode=Hd(e,Pm),t}function Um(e){const t=Im("equirect");return t.fragmentNode=cl(e,Up(Pm),0),t}const Vm=new WeakMap;function Om(e,t,r){const s=function(e){let t=Vm.get(e);void 0===t&&(t=new WeakMap,Vm.set(e,t));return t}(t);let i=s.get(e);if((void 0!==i?i.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const r=6;for(let s=0;s0}(t))return null;i=r.fromEquirectangular(e,i)}i.pmremVersion=e.pmremVersion,s.set(e,i)}return i.texture}class Gm extends Js{static get type(){return"PMREMNode"}constructor(e,t=null,r=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=r,this._generator=null;const s=new x;s.isRenderTargetTexture=!0,this._texture=cl(s),this._width=oa(0),this._height=oa(0),this._maxMip=oa(0),this.updateBeforeType=ks.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:r,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const r=t?t.pmremVersion:-1,s=this._value;r!==s.pmremVersion&&(t=!0===s.isPMREMTexture?s:Om(s,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Bm(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=Dd.mul(dn(t.x,t.y.negate(),t.z));let r=this.levelNode;return null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),hm(this._texture,t,r,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const km=Hi(Gm).setParameterLength(1,3),zm=new WeakMap;class $m extends Hh{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const e=r.isTextureNode?r.value:t[r.property];let s=zm.get(e);void 0===s&&(s=km(e),zm.set(e,s)),r=s}const s=!0===t.useAnisotropy||t.anisotropy>0?vc:Sd,i=r.context(Hm(wn,s)).mul(Id),n=r.context(Wm(Ed)).mul(Math.PI).mul(Id),a=zu(i),o=zu(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const u=e.context.lightingModel.clearcoatRadiance;if(u){const e=r.context(Hm(Pn,Rd)).mul(Id),t=zu(e);u.addAssign(t)}}}const Hm=(e,t)=>{let r=null;return{getUV:()=>(null===r&&(r=gd.negate().reflect(t),r=e.mul(e).mix(r,t).normalize(),r=r.transformDirection(Dl)),r),getTextureLevel:()=>e}},Wm=e=>({getUV:()=>e,getTextureLevel:()=>tn(1)}),qm=new me;class jm extends Sp{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(qm),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new $m(t):null}setupLightingModel(){return new Kg}setupSpecular(){const e=Ho(dn(.04),Rn.rgb,Cn);kn.assign(e),zn.assign(1)}setupVariants(){const e=this.metalnessNode?tn(this.metalnessNode):zc;Cn.assign(e);let t=this.roughnessNode?tn(this.roughnessNode):kc;t=ag({roughness:t}),wn.assign(t),this.setupSpecular(),Rn.assign(gn(Rn.rgb.mul(e.oneMinus()),Rn.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Xm=new fe;class Km extends jm{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(Xm),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?tn(this.iorNode):rh;Xn.assign(e),kn.assign(Ho(Co(Vo(Xn.sub(1).div(Xn.add(1))).mul(Vc),dn(1)).mul(Uc),Rn.rgb,Cn)),zn.assign(Ho(Uc,1,Cn))}setupLightingModel(){return new Kg(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?tn(this.clearcoatNode):Hc,t=this.clearcoatRoughnessNode?tn(this.clearcoatRoughnessNode):Wc;Mn.assign(e),Pn.assign(ag({roughness:t}))}if(this.useSheen){const e=this.sheenNode?dn(this.sheenNode):Xc,t=this.sheenRoughnessNode?tn(this.sheenRoughnessNode):Kc;Bn.assign(e),Ln.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?tn(this.iridescenceNode):Qc,t=this.iridescenceIORNode?tn(this.iridescenceIORNode):Zc,r=this.iridescenceThicknessNode?tn(this.iridescenceThicknessNode):Jc;Fn.assign(e),In.assign(t),Dn.assign(r)}if(this.useAnisotropy){const e=(this.anisotropyNode?an(this.anisotropyNode):Yc).toVar();Vn.assign(e.length()),Zi(Vn.equal(0),()=>{e.assign(an(1,0))}).Else(()=>{e.divAssign(an(Vn)),Vn.assign(Vn.saturate())}),Un.assign(Vn.pow2().mix(wn.pow2(),1)),On.assign(Tc[0].mul(e.x).add(Tc[1].mul(e.y))),Gn.assign(Tc[1].mul(e.x).sub(Tc[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?tn(this.transmissionNode):eh,t=this.thicknessNode?tn(this.thicknessNode):th,r=this.attenuationDistanceNode?tn(this.attenuationDistanceNode):sh,s=this.attenuationColorNode?dn(this.attenuationColorNode):ih;if(Kn.assign(e),Yn.assign(t),Qn.assign(r),Zn.assign(s),this.useDispersion){const e=this.dispersionNode?tn(this.dispersionNode):ch;Jn.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?dn(this.clearcoatNormalNode):qc}setup(e){e.context.setupClearcoatNormal=()=>fu(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}class Ym extends Kg{constructor(e=!1,t=!1,r=!1,s=!1,i=!1,n=!1,a=!1){super(e,t,r,s,i,n),this.useSSS=a}direct({lightDirection:e,lightColor:t,reflectedLight:r},s){if(!0===this.useSSS){const i=s.material,{thicknessColorNode:n,thicknessDistortionNode:a,thicknessAmbientNode:o,thicknessAttenuationNode:u,thicknessPowerNode:l,thicknessScaleNode:d}=i,c=e.add(Sd.mul(a)).normalize(),h=tn(gd.dot(c.negate()).saturate().pow(l).mul(d)),p=dn(h.add(o).mul(n));r.directDiffuse.addAssign(p.mul(u.mul(t)))}super.direct({lightDirection:e,lightColor:t,reflectedLight:r},s)}}class Qm extends Km{static get type(){return"MeshSSSNodeMaterial"}constructor(e){super(e),this.thicknessColorNode=null,this.thicknessDistortionNode=tn(.1),this.thicknessAmbientNode=tn(0),this.thicknessAttenuationNode=tn(.1),this.thicknessPowerNode=tn(2),this.thicknessScaleNode=tn(10)}get useSSS(){return null!==this.thicknessColorNode}setupLightingModel(){return new Ym(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useSSS)}copy(e){return this.thicknessColorNode=e.thicknessColorNode,this.thicknessDistortionNode=e.thicknessDistortionNode,this.thicknessAmbientNode=e.thicknessAmbientNode,this.thicknessAttenuationNode=e.thicknessAttenuationNode,this.thicknessPowerNode=e.thicknessPowerNode,this.thicknessScaleNode=e.thicknessScaleNode,super.copy(e)}}const Zm=Ki(({normal:e,lightDirection:t,builder:r})=>{const s=e.dot(t),i=an(s.mul(.5).add(.5),0);if(r.material.gradientMap){const e=Yd("gradientMap","texture").context({getUV:()=>i});return dn(e.r)}{const e=i.fwidth().mul(.5);return Ho(dn(.7),dn(1),Xo(tn(.7).sub(e.x),tn(.7).add(e.x),i.x))}});class Jm extends qp{direct({lightDirection:e,lightColor:t,reflectedLight:r},s){const i=Zm({normal:xd,lightDirection:e,builder:s}).mul(t);r.directDiffuse.addAssign(i.mul(Qp({diffuseColor:Rn.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:r,reflectedLight:s}=e.context;s.indirectDiffuse.addAssign(r.mul(Qp({diffuseColor:Rn}))),s.indirectDiffuse.mulAssign(t)}}const ef=new ye;class tf extends Sp{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(ef),this.setValues(e)}setupLightingModel(){return new Jm}}const rf=Ki(()=>{const e=dn(gd.z,0,gd.x.negate()).normalize(),t=gd.cross(e);return an(e.dot(Sd),t.dot(Sd)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),sf=new be;class nf extends Sp{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(sf),this.setValues(e)}setupVariants(e){const t=rf;let r;r=e.material.matcap?Yd("matcap","texture").context({getUV:()=>t}):dn(Ho(.2,.8,t.y)),Rn.rgb.mulAssign(r.rgb)}}class af extends Js{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:r}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),s=t.sin();return bn(e,s,s.negate(),e).mul(r)}{const e=t,s=Tn(gn(1,0,0,0),gn(0,uo(e.x),oo(e.x).negate(),0),gn(0,oo(e.x),uo(e.x),0),gn(0,0,0,1)),i=Tn(gn(uo(e.y),0,oo(e.y),0),gn(0,1,0,0),gn(oo(e.y).negate(),0,uo(e.y),0),gn(0,0,0,1)),n=Tn(gn(uo(e.z),oo(e.z).negate(),0,0),gn(oo(e.z),uo(e.z),0,0),gn(0,0,1,0),gn(0,0,0,1));return s.mul(i).mul(n).mul(gn(r,1)).xyz}}}const of=Hi(af).setParameterLength(2),uf=new xe;class lf extends Sp{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(uf),this.setValues(e)}setupPositionView(e){const{object:t,camera:r}=e,{positionNode:s,rotationNode:i,scaleNode:n,sizeAttenuation:a}=this,o=id.mul(dn(s||0));let u=an(Ql[0].xyz.length(),Ql[1].xyz.length());null!==n&&(u=u.mul(an(n))),r.isPerspectiveCamera&&!1===a&&(u=u.mul(o.z.negate()));let l=ud.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,r)=>Gi(new Au(e,t,r)))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(u);const d=tn(i||jc),c=of(l,d);return gn(o.xy.add(c),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const df=new Te,cf=new t;class hf extends lf{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(df),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return id.mul(dn(e||ld)).xyz}setupVertexSprite(e){const{material:t,camera:r}=e,{rotationNode:s,scaleNode:i,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let u=null!==n?an(n):dh;u=u.mul(vl),r.isPerspectiveCamera&&!0===a&&(u=u.mul(pf.div(pd.z.negate()))),i&&i.isNode&&(u=u.mul(an(i)));let l=ud.xy;if(s&&s.isNode){const e=tn(s);l=of(l,e)}return l=l.mul(u),l=l.div(Al.div(2)),l=l.mul(o.w),o=o.add(gn(l,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const pf=oa(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(cf);this.value=.5*t.y});class gf extends qp{constructor(){super(),this.shadowNode=tn(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Rn.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Rn.rgb)}}const mf=new _e;class ff extends Sp{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(mf),this.setValues(e)}setupLightingModel(){return new gf}}const yf=Sn("vec3"),bf=Sn("vec3"),xf=Sn("vec3");class Tf extends qp{constructor(){super()}start(e){const{material:t,context:r}=e,s=Sn("vec3"),i=Sn("vec3");Zi(Ol.sub(cd).length().greaterThan(td.mul(2)),()=>{s.assign(Ol),i.assign(cd)}).Else(()=>{s.assign(cd),i.assign(Ol)});const n=i.sub(s),a=oa("int").onRenderUpdate(({material:e})=>e.steps),o=n.length().div(a).toVar(),u=n.normalize().toVar(),l=tn(0).toVar(),d=dn(1).toVar();t.offsetNode&&l.addAssign(t.offsetNode.mul(o)),Uh(a,()=>{const i=s.add(u.mul(l)),n=Dl.mul(gn(i,1)).xyz;let a;null!==t.depthNode&&(bf.assign(lp(ip(n.z,Bl,Ll))),r.sceneDepthNode=lp(t.depthNode).toVar()),r.positionWorld=i,r.shadowPositionWorld=i,r.positionView=n,yf.assign(0),t.scatteringNode&&(a=t.scatteringNode({positionRay:i})),super.start(e),a&&yf.mulAssign(a);const c=yf.mul(.01).negate().mul(o).exp();d.mulAssign(c),l.addAssign(o)}),xf.addAssign(d.saturate().oneMinus())}scatteringLight(e,t){const r=t.context.sceneDepthNode;r?Zi(r.greaterThanEqual(bf),()=>{yf.addAssign(e)}):yf.addAssign(e)}direct({lightNode:e,lightColor:t},r){if(void 0===e.light.distance)return;const s=t.xyz.toVar();s.mulAssign(e.shadowNode),this.scatteringLight(s,r)}directRectArea({lightColor:e,lightPosition:t,halfWidth:r,halfHeight:s},i){const n=t.add(r).sub(s),a=t.sub(r).sub(s),o=t.sub(r).add(s),u=t.add(r).add(s),l=i.context.positionView,d=e.xyz.mul(Ng({P:l,p0:n,p1:a,p2:o,p3:u})).pow(1.5);this.scatteringLight(d,i)}finish(e){e.context.outgoingLight.assign(xf)}}class _f extends Sp{static get type(){return"VolumeNodeMaterial"}constructor(e){super(),this.isVolumeNodeMaterial=!0,this.steps=25,this.offsetNode=null,this.scatteringNode=null,this.lights=!0,this.transparent=!0,this.side=S,this.depthTest=!1,this.depthWrite=!1,this.setValues(e)}setupLightingModel(){return new Tf}}class vf{constructor(e,t){this.nodes=e,this.info=t,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,r)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,null!==this._animationLoop&&this._animationLoop(t,r)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class Nf{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let r=0;r{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,r=[],s=new Set,i={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),i[n.name]=e.version),void 0===e)continue;r.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;s.add(a)}return this.attributes=r,this.attributesId=i,this.vertexBuffers=Array.from(s.values()),r}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:r,group:s,drawRange:i}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let u=1;if(!0===r.isInstancedBufferGeometry?u=r.instanceCount:void 0!==e.count&&(u=Math.max(0,e.count)),0===u)return null;if(n.instanceCount=u,!0===e.isBatchedMesh)return n;let l=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(l=2);let d=i.start*l,c=(i.start+i.count)*l;null!==s&&(d=Math.max(d,s.start*l),c=Math.min(c,(s.start+s.count)*l));const h=r.attributes.position;let p=1/0;o?p=a.count:null!=h&&(p=h.count),d=Math.max(d,0),c=Math.min(c,p);const g=c-d;return g<0||g===1/0?null:(n.vertexCount=g,n.firstVertex=d,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const r of Object.keys(e.attributes).sort()){const s=e.attributes[r];t+=r+",",s.data&&(t+=s.data.stride+","),s.offset&&(t+=s.offset+","),s.itemSize&&(t+=s.itemSize+","),s.normalized&&(t+="n,")}for(const r of Object.keys(e.morphAttributes).sort()){const s=e.morphAttributes[r];t+="morph-"+r+",";for(let e=0,r=s.length;e1)&&(s+=e.uuid+","),s+=e.receiveShadow+",",vs(s)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const r=this.geometry.getAttribute(t);if(void 0===r||e[t]!==r.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Ss(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Ss(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const Rf=[];class Af{constructor(e,t,r,s,i,n){this.renderer=e,this.nodes=t,this.geometries=r,this.pipelines=s,this.bindings=i,this.info=n,this.chainMaps={}}get(e,t,r,s,i,n,a,o){const u=this.getChainMap(o);Rf[0]=e,Rf[1]=t,Rf[2]=n,Rf[3]=i;let l=u.get(Rf);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,r,s,i,n,a,o),u.set(Rf,l)):(l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,r,s,i,n,a,o)):l.version=t.version)),Rf.length=0,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Nf)}dispose(){this.chainMaps={}}createRenderObject(e,t,r,s,i,n,a,o,u,l,d){const c=this.getChainMap(d),h=new Ef(e,t,r,s,i,n,a,o,u,l);return h.onDispose=()=>{this.pipelines.delete(h),this.bindings.delete(h),this.nodes.delete(h),c.delete(h.getChainArray())},h}}class wf{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const Cf=1,Mf=2,Pf=3,Bf=4,Lf=16;class Ff extends wf{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const r=this.get(e);if(void 0===r.version)t===Cf?this.backend.createAttribute(e):t===Mf?this.backend.createIndexAttribute(e):t===Pf?this.backend.createStorageAttribute(e):t===Bf&&this.backend.createIndirectStorageAttribute(e),r.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(r.version{this.info.memory.geometries--;const s=t.index,i=e.getAttributes();null!==s&&this.attributes.delete(s);for(const e of i)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",r)};t.addEventListener("dispose",r)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,Pf):this.updateAttribute(e,Cf);const r=this.getIndex(e);null!==r&&this.updateAttribute(r,Mf);const s=e.geometry.indirect;null!==s&&this.updateAttribute(s,Bf)}updateAttribute(e,t){const r=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,r)):this.attributeCall.get(e.data)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e.data,r),this.attributeCall.set(e,r)):this.attributeCall.get(e)!==r&&(this.attributes.update(e,t),this.attributeCall.set(e,r))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:r}=e;let s=t.index;if(!0===r.wireframe){const e=this.wireframes;let r=e.get(t);void 0===r?(r=Df(t),e.set(t,r)):r.version!==If(t)&&(this.attributes.delete(r),r=Df(t),e.set(t,r)),s=r}return s}}class Vf{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,r){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=r*(t/3):e.isPoints?this.render.points+=r*t:e.isLineSegments?this.render.lines+=r*(t/2):e.isLine?this.render.lines+=r*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class Of{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Gf extends Of{constructor(e,t,r){super(e),this.vertexProgram=t,this.fragmentProgram=r}}class kf extends Of{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let zf=0;class $f{constructor(e,t,r,s=null,i=null){this.id=zf++,this.code=e,this.stage=t,this.name=r,this.transforms=s,this.attributes=i,this.usedTimes=0}}class Hf extends wf{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:r}=this,s=this.get(e);if(this._needsComputeUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let a=this.programs.compute.get(n.computeShader);void 0===a&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),a=new $f(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),r.createProgram(a));const o=this._getComputeCacheKey(e,a);let u=this.caches.get(o);void 0===u&&(i&&0===i.usedTimes&&this._releasePipeline(i),u=this._getComputePipeline(e,a,o,t)),u.usedTimes++,a.usedTimes++,s.version=e.version,s.pipeline=u}return s.pipeline}getForRender(e,t=null){const{backend:r}=this,s=this.get(e);if(this._needsRenderUpdate(e)){const i=s.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new $f(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),r.createProgram(o));let u=this.programs.fragment.get(n.fragmentShader);void 0===u&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),u=new $f(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,u),r.createProgram(u));const l=this._getRenderCacheKey(e,o,u);let d=this.caches.get(l);void 0===d?(i&&0===i.usedTimes&&this._releasePipeline(i),d=this._getRenderPipeline(e,o,u,l,t)):e.pipeline=d,d.usedTimes++,o.usedTimes++,u.usedTimes++,s.pipeline=d}return s.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,r,s){r=r||this._getComputeCacheKey(e,t);let i=this.caches.get(r);return void 0===i&&(i=new kf(r,t),this.caches.set(r,i),this.backend.createComputePipeline(i,s)),i}_getRenderPipeline(e,t,r,s,i){s=s||this._getRenderCacheKey(e,t,r);let n=this.caches.get(s);return void 0===n&&(n=new Gf(s,t,r),this.caches.set(s,n),e.pipeline=n,this.backend.createRenderPipeline(e,i)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,r){return t.id+","+r.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,r=e.stage;this.programs[r].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class Wf extends wf{constructor(e,t,r,s,i,n){super(),this.backend=e,this.textures=r,this.pipelines=i,this.attributes=s,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const r=this.get(e);void 0===r.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),r.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?Bf:Pf;this.attributes.update(e,r)}}_update(e,t){const{backend:r}=this;let s=!1,i=!0,n=0,a=0;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?Bf:Pf;this.attributes.update(e,r)}if(t.isUniformBuffer){t.update()&&r.updateBinding(t)}else if(t.isSampledTexture){const e=t.update(),o=t.texture,u=this.textures.get(o);e&&(this.textures.updateTexture(o),t.generation!==u.generation&&(t.generation=u.generation,s=!0,i=!1));if(void 0!==r.get(o).externalTexture||u.isDefaultTexture?i=!1:(n=10*n+o.id,a+=o.version),!0===o.isStorageTexture){const e=this.get(o);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(o)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(o),e.needsMipmap=!1)}}else t.isSampler&&t.update()}!0===s&&this.backend.updateBindings(e,t,i?n:0,a)}}function qf(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function jf(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function Xf(e){return(e.transmission>0||e.transmissionNode)&&e.side===E&&!1===e.forceSinglePass}class Kf{constructor(e,t,r){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,r),this.lightsArray=[],this.scene=t,this.camera=r,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,r,s,i,n,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:r,groupOrder:s,renderOrder:e.renderOrder,z:i,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=r,o.groupOrder=s,o.renderOrder=e.renderOrder,o.z=i,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===r.transparent||r.transmission>0?(Xf(r)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,r,s,i,n,a){const o=this.getNextRenderItem(e,t,r,s,i,n,a);!0===r.transparent||r.transmission>0?(Xf(r)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||qf),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||jf),this.transparent.length>1&&this.transparent.sort(t||jf)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,u=a.height>>t;let l=e.depthTexture||i[t];const d=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===l&&d&&(l=new V,l.format=e.stencilBuffer?Re:Ae,l.type=e.stencilBuffer?we:T,l.image.width=o,l.image.height=u,l.image.depth=a.depth,l.isArrayTexture=!0===e.multiview&&a.depth>1,i[t]=l),r.width===a.width&&a.height===r.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=o,l.image.height=u,l.image.depth=l.isArrayTexture?l.image.depth:1)),r.width=a.width,r.height=a.height,r.textures=n,r.depthTexture=l||null,r.depth=e.depthBuffer,r.stencil=e.stencilBuffer,r.renderTarget=e,r.sampleCount!==s&&(c=!0,l&&(l.needsUpdate=!0),r.sampleCount=s);const h={sampleCount:s};if(!0!==e.isXRRenderTarget){for(let e=0;e{e.removeEventListener("dispose",t);for(let e=0;e0&&t.levels++,s||!0===e.isStorageTexture||!0===e.isExternalTexture)i.createSampler(e),i.createTexture(e,t),r.generation=e.version;else{if(!0!==r.initialized&&i.createSampler(e),e.version>0){const s=e.image;if(void 0===s)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===s.complete)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const r=[];for(const t of e.images)r.push(t);t.images=r}else t.image=s;void 0!==r.isDefaultTexture&&!0!==r.isDefaultTexture||(i.createTexture(e,t),r.isDefaultTexture=!1,r.generation=e.version),!0===e.source.dataReady&&i.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.createDefaultTexture(e),r.isDefaultTexture=!0,r.generation=e.version}if(!0!==r.initialized){r.initialized=!0,r.generation=e.version,this.info.memory.textures++,e.isVideoTexture&&c.getTransfer(e.colorSpace)!==h&&console.warn("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.");const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e)};e.addEventListener("dispose",t)}r.version=e.version}getSize(e,t=ny){let r=e.images?e.images[0]:e.image;return r?(void 0!==r.image&&(r=r.image),"undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement?(t.width=r.videoWidth||1,t.height=r.videoHeight||1,t.depth=1):r instanceof VideoFrame?(t.width=r.displayWidth||1,t.height=r.displayHeight||1,t.depth=1):(t.width=r.width||1,t.height=r.height||1,t.depth=e.isCubeTexture?6:r.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,r){let s;return s=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,r)))+1,s}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyTexture(e){!0===this.has(e)&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class oy extends e{constructor(e,t,r,s=1){super(e,t,r),this.a=s}set(e,t,r,s=1){return this.a=s,super.set(e,t,r)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class uy extends Nn{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class ly extends Ys{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.hasOutput?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput?this.outputNode.getMemberType(e,t):"void"}add(e){return!0!==e.isNode?(console.error("THREE.TSL: Invalid node added to stack."),this):(this.nodes.push(e),this)}If(e,t){const r=new Oi(t);return this._currentCond=iu(e,r),this.add(this._currentCond)}ElseIf(e,t){const r=new Oi(t),s=iu(e,r);return this._currentCond.elseNode=s,this._currentCond=s,this}Else(e){return this._currentCond.elseNode=new Oi(e),this}Switch(e){return this._expressionNode=Gi(e),this}Case(...e){const t=[];if(e.length>=2)for(let r=0;r"string"==typeof t?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})),this.name=t,this.isStructLayoutNode=!0}getLength(){const e=Float32Array.BYTES_PER_ELEMENT;let t=0;for(const r of this.membersLayout){const s=r.type,i=Bs(s)*e,n=t%8,a=n%Ls(s),o=n+a;t+=a,0!==o&&8-oe.name===t);return r?r.type:"void"}getNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class hy extends Ys{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}getNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}generate(e){const t=e.getVarFromNode(this),r=t.type,s=e.getPropertyName(t);return e.addLineFlowCode(`${s} = ${e.generateStruct(r,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}class py extends Ys{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}getNodeType(e){const t=e.getNodeProperties(this);if(void 0===t.membersLayout){const r=this.members,s=[];for(let t=0;t{const t=e.toUint().mul(747796405).add(2891336453),r=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return r.shiftRight(22).bitXor(r).toFloat().mul(1/2**32)}),_y=(e,t)=>Uo(ba(4,e.mul(ya(1,e))),t),vy=Ki(([e])=>e.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),Ny=Ki(([e])=>dn(vy(e.z.add(vy(e.y.mul(1)))),vy(e.z.add(vy(e.x.mul(1)))),vy(e.y.add(vy(e.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Sy=Ki(([e,t,r])=>{const s=dn(e).toVar(),i=tn(1.4).toVar(),n=tn(0).toVar(),a=dn(s).toVar();return Uh({start:tn(0),end:tn(3),type:"float",condition:"<="},()=>{const e=dn(Ny(a.mul(2))).toVar();s.addAssign(e.add(r.mul(tn(.1).mul(t)))),a.mulAssign(1.8),i.mulAssign(1.5),s.mulAssign(1.2);const o=tn(vy(s.z.add(vy(s.x.add(vy(s.y)))))).toVar();n.addAssign(o.div(i)),a.addAssign(.14)}),n}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class Ey extends Ys{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFnCall=null,this.global=!0}getNodeType(){return this.functionNodes[0].shaderNode.layout.type}setup(e){const t=this.parametersNodes;let r=this._candidateFnCall;if(null===r){let s=null,i=-1;for(const r of this.functionNodes){const n=r.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const a=n.inputs;if(t.length===a.length){let n=0;for(let r=0;ri&&(s=r,i=n)}}this._candidateFnCall=r=s(...t)}return r}}const Ry=Hi(Ey),Ay=e=>(...t)=>Ry(e,...t),wy=oa(0).setGroup(ia).onRenderUpdate(e=>e.time),Cy=oa(0).setGroup(ia).onRenderUpdate(e=>e.deltaTime),My=oa(0,"uint").setGroup(ia).onRenderUpdate(e=>e.frameId),Py=Ki(([e,t,r=an(.5)])=>of(e.sub(r),t).add(r)),By=Ki(([e,t,r=an(.5)])=>{const s=e.sub(r),i=s.dot(s),n=i.mul(i).mul(t);return e.add(s.mul(n))}),Ly=Ki(({position:e=null,horizontal:t=!0,vertical:r=!1})=>{let s;null!==e?(s=Ql.toVar(),s[3][0]=e.x,s[3][1]=e.y,s[3][2]=e.z):s=Ql;const i=Dl.mul(s);return Ui(t)&&(i[0][0]=Ql[0].length(),i[0][1]=0,i[0][2]=0),Ui(r)&&(i[1][0]=0,i[1][1]=Ql[1].length(),i[1][2]=0),i[2][0]=0,i[2][1]=0,i[2][2]=1,Fl.mul(i).mul(ld)}),Fy=Ki(([e=null])=>{const t=lp();return lp(tp(e)).sub(t).lessThan(0).select(Nl,e)});class Iy extends Ys{static get type(){return"SpriteSheetUVNode"}constructor(e,t=sl(),r=tn(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=r}setup(){const{frameNode:e,uvNode:t,countNode:r}=this,{width:s,height:i}=r,n=e.mod(s.mul(i)).floor(),a=n.mod(s),o=i.sub(n.add(1).div(s).ceil()),u=r.reciprocal(),l=an(a,o);return t.add(l).mul(u)}}const Dy=Hi(Iy).setParameterLength(3),Uy=Ki(([e,t=null,r=null,s=tn(1),i=ld,n=Td])=>{let a=n.abs().normalize();a=a.div(a.dot(dn(1)));const o=i.yz.mul(s),u=i.zx.mul(s),l=i.xy.mul(s),d=e.value,c=null!==t?t.value:d,h=null!==r?r.value:d,p=cl(d,o).mul(a.x),g=cl(c,u).mul(a.y),m=cl(h,l).mul(a.z);return fa(p,g,m)}),Vy=new Me,Oy=new r,Gy=new r,ky=new r,zy=new a,$y=new r(0,0,-1),Hy=new s,Wy=new r,qy=new r,jy=new s,Xy=new t,Ky=new ue,Yy=Nl.flipX();Ky.depthTexture=new V(1,1);let Qy=!1;class Zy extends ll{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||Ky.texture,Yy),this._reflectorBaseNode=e.reflector||new Jy(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(null===this._depthNode){if(!0!==this._reflectorBaseNode.depth)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=Gi(new Zy({defaultTexture:Ky.depthTexture,reflector:this._reflectorBaseNode}))}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class Jy extends Ys{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:r=new Pe,resolutionScale:s=1,generateMipmaps:i=!1,bounces:n=!0,depth:a=!1,samples:o=0}=t;this.textureNode=e,this.target=r,this.resolutionScale=s,void 0!==t.resolution&&(Be('THREE.ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=i,this.bounces=n,this.depth=a,this.samples=o,this.updateBeforeType=n?ks.RENDER:ks.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const r=this.resolutionScale;t.getDrawingBufferSize(Xy),e.setSize(Math.round(Xy.width*r),Math.round(Xy.height*r))}setup(e){return this._updateResolution(Ky,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return void 0===t&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return void 0===t&&(t=new ue(0,0,{type:ce,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=Le,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new V),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&Qy)return!1;Qy=!0;const{scene:t,camera:r,renderer:s,material:i}=e,{target:n}=this,a=this.getVirtualCamera(r),o=this.getRenderTarget(a);s.getDrawingBufferSize(Xy),this._updateResolution(o,s),Gy.setFromMatrixPosition(n.matrixWorld),ky.setFromMatrixPosition(r.matrixWorld),zy.extractRotation(n.matrixWorld),Oy.set(0,0,1),Oy.applyMatrix4(zy),Wy.subVectors(Gy,ky);let u=!1;if(!0===Wy.dot(Oy)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(Qy=!1);u=!0}Wy.reflect(Oy).negate(),Wy.add(Gy),zy.extractRotation(r.matrixWorld),$y.set(0,0,-1),$y.applyMatrix4(zy),$y.add(ky),qy.subVectors(Gy,$y),qy.reflect(Oy).negate(),qy.add(Gy),a.coordinateSystem=r.coordinateSystem,a.position.copy(Wy),a.up.set(0,1,0),a.up.applyMatrix4(zy),a.up.reflect(Oy),a.lookAt(qy),a.near=r.near,a.far=r.far,a.updateMatrixWorld(),a.projectionMatrix.copy(r.projectionMatrix),Vy.setFromNormalAndCoplanarPoint(Oy,Gy),Vy.applyMatrix4(a.matrixWorldInverse),Hy.set(Vy.normal.x,Vy.normal.y,Vy.normal.z,Vy.constant);const l=a.projectionMatrix;jy.x=(Math.sign(Hy.x)+l.elements[8])/l.elements[0],jy.y=(Math.sign(Hy.y)+l.elements[9])/l.elements[5],jy.z=-1,jy.w=(1+l.elements[10])/l.elements[14],Hy.multiplyScalar(1/Hy.dot(jy));l.elements[2]=Hy.x,l.elements[6]=Hy.y,l.elements[10]=s.coordinateSystem===d?Hy.z-0:Hy.z+1-0,l.elements[14]=Hy.w,this.textureNode.value=o.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=o.depthTexture),i.visible=!1;const c=s.getRenderTarget(),h=s.getMRT(),p=s.autoClear;s.setMRT(null),s.setRenderTarget(o),s.autoClear=!0,u?(s.clear(),this.hasOutput=!1):(s.render(t,a),this.hasOutput=!0),s.setMRT(h),s.setRenderTarget(c),s.autoClear=p,i.visible=!0,Qy=!1,this.forceUpdate=!1}get resolution(){return Be('THREE.ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){Be('THREE.ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const eb=new ae(-1,1,1,-1,0,1);class tb extends pe{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Fe([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Fe(t,2))}}const rb=new tb;class sb extends X{constructor(e=null){super(rb,e),this.camera=eb,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,eb)}render(e){e.render(this,eb)}}const ib=new t;class nb extends ll{static get type(){return"RTTNode"}constructor(e,t=null,r=null,s={type:ce}){const i=new ue(t,r,s);super(i.texture,sl()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=r,this.pixelRatio=1,this.renderTarget=i,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._rttNode=null,this._quadMesh=new sb(new Sp),this.updateBeforeType=ks.RENDER}get autoResize(){return null===this.width}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){this.width=e,this.height=t;const r=e*this.pixelRatio,s=t*this.pixelRatio;this.renderTarget.setSize(r,s),this.textureNeedsUpdate=!0}setPixelRatio(e){this.pixelRatio=e,this.setSize(this.width,this.height)}updateBefore({renderer:e}){if(!1===this.textureNeedsUpdate&&!1===this.autoUpdate)return;if(this.textureNeedsUpdate=!1,!0===this.autoResize){const t=e.getPixelRatio(),r=e.getSize(ib),s=r.width*t,i=r.height*t;s===this.renderTarget.width&&i===this.renderTarget.height||(this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0)}this._quadMesh.material.fragmentNode=this._rttNode;const t=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(t)}clone(){const e=new ll(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const ab=(e,...t)=>Gi(new nb(Gi(e),...t)),ob=Ki(([e,t,r],s)=>{let i;s.renderer.coordinateSystem===d?(e=an(e.x,e.y.oneMinus()).mul(2).sub(1),i=gn(dn(e,t),1)):i=gn(dn(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=gn(r.mul(i));return n.xyz.div(n.w)}),ub=Ki(([e,t])=>{const r=t.mul(gn(e,1)),s=r.xy.div(r.w).mul(.5).add(.5).toVar();return an(s.x,s.y.oneMinus())}),lb=Ki(([e,t,r])=>{const s=nl(hl(t)),i=on(e.mul(s)).toVar(),n=hl(t,i).toVar(),a=hl(t,i.sub(on(2,0))).toVar(),o=hl(t,i.sub(on(1,0))).toVar(),u=hl(t,i.add(on(1,0))).toVar(),l=hl(t,i.add(on(2,0))).toVar(),d=hl(t,i.add(on(0,2))).toVar(),c=hl(t,i.add(on(0,1))).toVar(),h=hl(t,i.sub(on(0,1))).toVar(),p=hl(t,i.sub(on(0,2))).toVar(),g=go(ya(tn(2).mul(o).sub(a),n)).toVar(),m=go(ya(tn(2).mul(u).sub(l),n)).toVar(),f=go(ya(tn(2).mul(c).sub(d),n)).toVar(),y=go(ya(tn(2).mul(h).sub(p),n)).toVar(),b=ob(e,n,r).toVar(),x=g.lessThan(m).select(b.sub(ob(e.sub(an(tn(1).div(s.x),0)),o,r)),b.negate().add(ob(e.add(an(tn(1).div(s.x),0)),u,r))),T=f.lessThan(y).select(b.sub(ob(e.add(an(0,tn(1).div(s.y))),c,r)),b.negate().add(ob(e.sub(an(0,tn(1).div(s.y))),h,r)));return no(Do(x,T))});class db extends Ys{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(sl())}sample(e){return this.callback(e)}}class cb extends Ys{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===cb.OBJECT?this.updateType=ks.OBJECT:e===cb.MATERIAL&&(this.updateType=ks.RENDER)}update(e){this.callback(e)}}cb.OBJECT="object",cb.MATERIAL="material";const hb=(e,t)=>Gi(new cb(e,t)).toStack();class pb extends L{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class gb extends ge{constructor(e,t,r=Float32Array){super(ArrayBuffer.isView(e)?e:new r(e*t),t),this.isStorageBufferAttribute=!0}}class mb extends Ys{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const fb=Wi(mb),yb=new R,bb=new a;class xb extends Ys{static get type(){return"SceneNode"}constructor(e=xb.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,r=null!==this.scene?this.scene:e.scene;let s;return t===xb.BACKGROUND_BLURRINESS?s=jd("backgroundBlurriness","float",r):t===xb.BACKGROUND_INTENSITY?s=jd("backgroundIntensity","float",r):t===xb.BACKGROUND_ROTATION?s=oa("mat4").setName("backgroundRotation").setGroup(ia).onRenderUpdate(()=>{const e=r.background;return null!==e&&e.isTexture&&e.mapping!==Ie?(yb.copy(r.backgroundRotation),yb.x*=-1,yb.y*=-1,yb.z*=-1,bb.makeRotationFromEuler(yb)):bb.identity(),bb}):console.error("THREE.SceneNode: Unknown scope:",t),s}}xb.BACKGROUND_BLURRINESS="backgroundBlurriness",xb.BACKGROUND_INTENSITY="backgroundIntensity",xb.BACKGROUND_ROTATION="backgroundRotation";const Tb=Wi(xb,xb.BACKGROUND_BLURRINESS),_b=Wi(xb,xb.BACKGROUND_INTENSITY),vb=Wi(xb,xb.BACKGROUND_ROTATION);class Nb extends ll{static get type(){return"StorageTextureNode"}constructor(e,t,r=null){super(e,t),this.storeNode=r,this.isStorageTextureNode=!0,this.access=$s.WRITE_ONLY}getInputType(){return"storageTexture"}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}generate(e,t){let r;return r=null!==this.storeNode?this.generateStore(e):super.generate(e,t),r}toReadWrite(){return this.setAccess($s.READ_WRITE)}toReadOnly(){return this.setAccess($s.READ_ONLY)}toWriteOnly(){return this.setAccess($s.WRITE_ONLY)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:r,storeNode:s,depthNode:i}=t,n=super.generate(e,"property"),a=r.build(e,!0===this.value.is3DTexture?"uvec3":"uvec2"),o=s.build(e,"vec4"),u=i?i.build(e,"int"):null,l=e.generateTextureStore(e,n,a,u,o);e.addLineFlowCode(l,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e}}const Sb=Hi(Nb).setParameterLength(1,3),Eb=Ki(({texture:e,uv:t})=>{const r=1e-4,s=dn().toVar();return Zi(t.x.lessThan(r),()=>{s.assign(dn(1,0,0))}).ElseIf(t.y.lessThan(r),()=>{s.assign(dn(0,1,0))}).ElseIf(t.z.lessThan(r),()=>{s.assign(dn(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{s.assign(dn(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{s.assign(dn(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{s.assign(dn(0,0,-1))}).Else(()=>{const r=.01,i=e.sample(t.add(dn(-.01,0,0))).r.sub(e.sample(t.add(dn(r,0,0))).r),n=e.sample(t.add(dn(0,-.01,0))).r.sub(e.sample(t.add(dn(0,r,0))).r),a=e.sample(t.add(dn(0,0,-.01))).r.sub(e.sample(t.add(dn(0,0,r))).r);s.assign(dn(i,n,a))}),s.normalize()});class Rb extends ll{static get type(){return"Texture3DNode"}constructor(e,t=null,r=null){super(e,t,r),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return dn(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const r=this.value;return!e.isFlipY()||!0!==r.isRenderTargetTexture&&!0!==r.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(rn(nl(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return Eb({texture:this,uv:e})}}const Ab=Hi(Rb).setParameterLength(1,3);class wb extends qd{static get type(){return"UserDataNode"}constructor(e,t,r=null){super(e,t,r),this.userData=r}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const Cb=new WeakMap;class Mb extends Js{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=ks.OBJECT,this.updateAfterType=ks.OBJECT,this.previousModelWorldMatrix=oa(new a),this.previousProjectionMatrix=oa(new a).setGroup(ia),this.previousCameraViewMatrix=oa(new a)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:r}){const s=Bb(r);this.previousModelWorldMatrix.value.copy(s);const i=Pb(t);i.frameId!==e&&(i.frameId=e,void 0===i.previousProjectionMatrix?(i.previousProjectionMatrix=new a,i.previousCameraViewMatrix=new a,i.currentProjectionMatrix=new a,i.currentCameraViewMatrix=new a,i.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(i.previousProjectionMatrix.copy(i.currentProjectionMatrix),i.previousCameraViewMatrix.copy(i.currentCameraViewMatrix)),i.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),i.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(i.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(i.previousCameraViewMatrix))}updateAfter({object:e}){Bb(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?Fl:oa(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),r=e.mul(id).mul(ld),s=this.previousProjectionMatrix.mul(t).mul(dd),i=r.xy.div(r.w),n=s.xy.div(s.w);return ya(i,n)}}function Pb(e){let t=Cb.get(e);return void 0===t&&(t={},Cb.set(e,t)),t}function Bb(e,t=0){const r=Pb(e);let s=r[t];return void 0===s&&(r[t]=s=new a,r[t].copy(e.matrixWorld)),s}const Lb=Wi(Mb),Fb=Ki(([e])=>Vb(e.rgb)),Ib=Ki(([e,t=tn(1)])=>t.mix(Vb(e.rgb),e.rgb)),Db=Ki(([e,t=tn(1)])=>{const r=fa(e.r,e.g,e.b).div(3),s=e.r.max(e.g.max(e.b)),i=s.sub(r).mul(t).mul(-3);return Ho(e.rgb,s,i)}),Ub=Ki(([e,t=tn(1)])=>{const r=dn(.57735,.57735,.57735),s=t.cos();return dn(e.rgb.mul(s).add(r.cross(e.rgb).mul(t.sin()).add(r.mul(Io(r,e.rgb).mul(s.oneMinus())))))}),Vb=(e,t=dn(c.getLuminanceCoefficients(new r)))=>Io(e,t),Ob=Ki(([e,t=dn(1),s=dn(0),i=dn(1),n=tn(1),a=dn(c.getLuminanceCoefficients(new r,le))])=>{const o=e.rgb.dot(dn(a)),u=Mo(e.rgb.mul(t).add(s),0).toVar(),l=u.pow(i).toVar();return Zi(u.r.greaterThan(0),()=>{u.r.assign(l.r)}),Zi(u.g.greaterThan(0),()=>{u.g.assign(l.g)}),Zi(u.b.greaterThan(0),()=>{u.b.assign(l.b)}),u.assign(o.add(u.sub(o).mul(n))),gn(u.rgb,e.a)});class Gb extends Js{static get type(){return"PosterizeNode"}constructor(e,t){super(),this.sourceNode=e,this.stepsNode=t}setup(){const{sourceNode:e,stepsNode:t}=this;return e.mul(t).floor().div(t)}}const kb=Hi(Gb).setParameterLength(2),zb=new t;class $b extends ll{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Hb extends $b{static get type(){return"PassMultipleTextureNode"}constructor(e,t,r=!1){super(e,null),this.textureName=t,this.previousTexture=r}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e}}class Wb extends Js{static get type(){return"PassNode"}constructor(e,t,r,s={}){super("vec4"),this.scope=e,this.scene=t,this.camera=r,this.options=s,this._pixelRatio=1,this._width=1,this._height=1;const i=new V;i.isRenderTargetTexture=!0,i.name="depth";const n=new ue(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ce,...s});n.texture.name="output",n.depthTexture=i,this.renderTarget=n,this._textures={output:n.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=oa(0),this._cameraFar=oa(0),this._mrt=null,this._layers=null,this._resolution=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=ks.FRAME,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const r=this._textures[e],s=this.renderTarget.textures.indexOf(r);this.renderTarget.textures[s]=t,this._textures[e]=t,this._previousTextures[e]=r,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=Gi(new Hb(this,e)),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=Gi(new Hb(this,e,!0)),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar;this._viewZNodes[e]=t=np(this.getTextureNode(e),r,s)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const r=this._cameraNear,s=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=sp(i,r,s)}return t}async compileAsync(e){const t=e.getRenderTarget(),r=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(r)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getColorBufferType(),this.scope===Wb.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:r}=this;let s,i;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(i=1,s=t.xr.getCamera(),t.xr.updateCamera(s),zb.set(n.width,n.height)):(s=this.camera,i=t.getPixelRatio(),t.getSize(zb)),this._pixelRatio=i,this.setSize(zb.width,zb.height);const a=t.getRenderTarget(),o=t.getMRT(),u=s.layers.mask;this._cameraNear.value=s.near,this._cameraFar.value=s.far,null!==this._layers&&(s.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(r,s),t.setRenderTarget(a),t.setMRT(o),s.layers.mask=u}setSize(e,t){this._width=e,this._height=t;const r=this._width*this._pixelRatio*this._resolution,s=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(r,s),null!==this._scissor&&this.renderTarget.scissor.copy(this._scissor),null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,r,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new s),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,r,i),this._scissor.multiplyScalar(this._pixelRatio*this._resolution).floor())}setViewport(e,t,r,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new s),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,r,i),this._viewport.multiplyScalar(this._pixelRatio*this._resolution).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Wb.COLOR="color",Wb.DEPTH="depth";class qb extends Wb{static get type(){return"ToonOutlinePassNode"}constructor(e,t,r,s,i){super(Wb.COLOR,e,t),this.colorNode=r,this.thicknessNode=s,this.alphaNode=i,this._materialCache=new WeakMap}updateBefore(e){const{renderer:t}=e,r=t.getRenderObjectFunction();t.setRenderObjectFunction((e,r,s,i,n,a,o,u)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const l=this._getOutlineMaterial(n);t.renderObject(e,r,s,i,l,a,o,u)}t.renderObject(e,r,s,i,n,a,o,u)}),super.updateBefore(e),t.setRenderObjectFunction(r)}_createMaterial(){const e=new Sp;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=S;const t=Td.negate(),r=Fl.mul(id),s=tn(1),i=r.mul(gn(ld,1)),n=r.mul(gn(ld.add(t),1)),a=no(i.sub(n));return e.vertexNode=i.add(a.mul(this.thicknessNode).mul(i.w).mul(s)),e.colorNode=gn(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return void 0===t&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const jb=Ki(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Xb=Ki(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp()).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Kb=Ki(([e,t])=>{const r=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),s=e.mul(e.mul(6.2).add(1.7)).add(.06);return r.div(s).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Yb=Ki(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),r=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(r)}),Qb=Ki(([e,t])=>{const r=xn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),s=xn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=r.mul(e),e=Yb(e),(e=s.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Zb=xn(dn(1.6605,-.1246,-.0182),dn(-.5876,1.1329,-.1006),dn(-.0728,-.0083,1.1187)),Jb=xn(dn(.6274,.0691,.0164),dn(.3293,.9195,.088),dn(.0433,.0113,.8956)),ex=Ki(([e])=>{const t=dn(e).toVar(),r=dn(t.mul(t)).toVar(),s=dn(r.mul(r)).toVar();return tn(15.5).mul(s.mul(r)).sub(ba(40.14,s.mul(t))).add(ba(31.96,s).sub(ba(6.868,r.mul(t))).add(ba(.4298,r).add(ba(.1191,t).sub(.00232))))}),tx=Ki(([e,t])=>{const r=dn(e).toVar(),s=xn(dn(.856627153315983,.137318972929847,.11189821299995),dn(.0951212405381588,.761241990602591,.0767994186031903),dn(.0482516061458583,.101439036467562,.811302368396859)),i=xn(dn(1.1271005818144368,-.1413297634984383,-.14132976349843826),dn(-.11060664309660323,1.157823702216272,-.11060664309660294),dn(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=tn(-12.47393),a=tn(4.026069);return r.mulAssign(t),r.assign(Jb.mul(r)),r.assign(s.mul(r)),r.assign(Mo(r,1e-10)),r.assign(eo(r)),r.assign(r.sub(n).div(a.sub(n))),r.assign(Wo(r,0,1)),r.assign(ex(r)),r.assign(i.mul(r)),r.assign(Uo(Mo(dn(0),r),dn(2.2))),r.assign(Zb.mul(r)),r.assign(Wo(r,0,1)),r}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),rx=Ki(([e,t])=>{const r=tn(.76),s=tn(.15);e=e.mul(t);const i=Co(e.r,Co(e.g,e.b)),n=iu(i.lessThan(.08),i.sub(ba(6.25,i.mul(i))),.04);e.subAssign(n);const a=Mo(e.r,Mo(e.g,e.b));Zi(a.lessThan(r),()=>e);const o=ya(1,r),u=ya(1,o.mul(o).div(a.add(o.sub(r))));e.mulAssign(u.div(a));const l=ya(1,xa(1,s.mul(a.sub(u)).add(1)));return Ho(e,dn(u),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class sx extends Ys{static get type(){return"CodeNode"}constructor(e="",t=[],r=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=r}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const r of t)r.build(e);const r=e.getCodeFromNode(this,this.getNodeType(e));return r.code=this.code,r.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}const ix=Hi(sx).setParameterLength(1,3);class nx extends sx{static get type(){return"FunctionNode"}constructor(e="",t=[],r=""){super(e,t,r)}getNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const r=this.getNodeType(e);return e.getStructTypeNode(r).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let r=t.nodeFunction;return void 0===r&&(r=e.parser.parseFunction(this.code),t.nodeFunction=r),r}generate(e,t){super.generate(e);const r=this.getNodeFunction(e),s=r.name,i=r.type,n=e.getCodeFromNode(this,i);""!==s&&(n.name=s);const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,i,t)}}const ax=(e,t=[],r="")=>{for(let e=0;es.call(...e);return i.functionNode=s,i};class ox extends Ys{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outputType=null,this.events=new o,this.isScriptableValueNode=!0}get isScriptableOutputNode(){return null!==this.outputType}set value(e){this._value!==e&&(this._cache&&"URL"===this.inputType&&this.value.value instanceof ArrayBuffer&&(URL.revokeObjectURL(this._cache),this._cache=null),this._value=e,this.events.dispatchEvent({type:"change"}),this.refresh())}get value(){return this._value}refresh(){this.events.dispatchEvent({type:"refresh"})}getValue(){const e=this.value;if(e&&null===this._cache&&"URL"===this.inputType&&e.value instanceof ArrayBuffer)this._cache=URL.createObjectURL(new Blob([e.value]));else if(e&&null!==e.value&&void 0!==e.value&&(("URL"===this.inputType||"String"===this.inputType)&&"string"==typeof e.value||"Number"===this.inputType&&"number"==typeof e.value||"Vector2"===this.inputType&&e.value.isVector2||"Vector3"===this.inputType&&e.value.isVector3||"Vector4"===this.inputType&&e.value.isVector4||"Color"===this.inputType&&e.value.isColor||"Matrix3"===this.inputType&&e.value.isMatrix3||"Matrix4"===this.inputType&&e.value.isMatrix4))return e.value;return this._cache||e}getNodeType(e){return this.value&&this.value.isNode?this.value.getNodeType(e):"float"}setup(){return this.value&&this.value.isNode?this.value:tn()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=Us(this.value):e.value=this.value?this.value.toJSON(e.meta).uuid:null:e.value=null,e.inputType=this.inputType,e.outputType=this.outputType}deserialize(e){super.deserialize(e);let t=null;null!==e.value&&(t="ArrayBuffer"===e.inputType?Vs(e.value):"Texture"===e.inputType?e.meta.textures[e.value]:e.meta.nodes[e.value]||null),this.value=t,this.inputType=e.inputType,this.outputType=e.outputType}}const ux=Hi(ox).setParameterLength(1);class lx extends Map{get(e,t=null,...r){if(this.has(e))return super.get(e);if(null!==t){const s=t(...r);return this.set(e,s),s}}}class dx{constructor(e){this.scriptableNode=e}get parameters(){return this.scriptableNode.parameters}get layout(){return this.scriptableNode.getLayout()}getInputLayout(e){return this.scriptableNode.getInputLayout(e)}get(e){const t=this.parameters[e];return t?t.getValue():null}}const cx=new lx;class hx extends Ys{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new lx,this._output=ux(null),this._outputs={},this._source=this.source,this._method=null,this._object=null,this._value=null,this._needsOutputUpdate=!0,this.onRefresh=this.onRefresh.bind(this),this.isScriptableNode=!0}get source(){return this.codeNode?this.codeNode.code:""}setLocal(e,t){return this._local.set(e,t)}getLocal(e){return this._local.get(e)}onRefresh(){this._refresh()}getInputLayout(e){for(const t of this.getLayout())if(t.inputType&&(t.id===e||t.name===e))return t}getOutputLayout(e){for(const t of this.getLayout())if(t.outputType&&(t.id===e||t.name===e))return t}setOutput(e,t){const r=this._outputs;return void 0===r[e]?r[e]=ux(t):r[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const r=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),r[e]=t,r[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),r[e]=t,r[e].events.addEventListener("refresh",this.onRefresh)):void 0===r[e]?(r[e]=ux(t),r[e].events.addEventListener("refresh",this.onRefresh)):r[e].value=t,this}getValue(){return this.getDefaultOutput().getValue()}deleteParameter(e){let t=this.parameters[e];return t&&(t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.removeEventListener("refresh",this.onRefresh)),this}clearParameters(){for(const e of Object.keys(this.parameters))this.deleteParameter(e);return this.needsUpdate=!0,this}call(e,...t){const r=this.getObject()[e];if("function"==typeof r)return r(...t)}async callAsync(e,...t){const r=this.getObject()[e];if("function"==typeof r)return"AsyncFunction"===r.constructor.name?await r(...t):r(...t)}getNodeType(e){return this.getDefaultOutputNode().getNodeType(e)}refresh(e=null){null!==e?this.getOutput(e).refresh():this._refresh()}getObject(){if(this.needsUpdate&&this.dispose(),null!==this._object)return this._object;const e=new dx(this),t=cx.get("THREE"),r=cx.get("TSL"),s=this.getMethod(),i=[e,this._local,cx,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,r];this._object=s(...i);const n=this._object.layout;if(n&&(!1===n.cache&&this._local.clear(),this._output.outputType=n.outputType||null,Array.isArray(n.elements)))for(const e of n.elements){const t=e.id||e.name;e.inputType&&(void 0===this.getParameter(t)&&this.setParameter(t,null),this.getParameter(t).inputType=e.inputType),e.outputType&&(void 0===this.getOutput(t)&&this.setOutput(t,null),this.getOutput(t).outputType=e.outputType)}return this._object}deserialize(e){super.deserialize(e);for(const e in this.parameters){let t=this.parameters[e];t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.addEventListener("refresh",this.onRefresh)}}getLayout(){return this.getObject().layout}getDefaultOutputNode(){const e=this.getDefaultOutput().value;return e&&e.isNode?e:tn()}getDefaultOutput(){return this._exec()._output}getMethod(){if(this.needsUpdate&&this.dispose(),null!==this._method)return this._method;const e=["layout","init","main","dispose"].join(", "),t="\nreturn { ...output, "+e+" };",r="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],r),this._method}dispose(){null!==this._method&&(this._object&&"function"==typeof this._object.dispose&&this._object.dispose(),this._method=null,this._object=null,this._source=null,this._value=null,this._needsOutputUpdate=!0,this._output.value=null,this._outputs={})}setup(){return this.getDefaultOutputNode()}getCacheKey(e){const t=[vs(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const r in this.parameters)t.push(this.parameters[r].getCacheKey(e));return Ns(t)}set needsUpdate(e){!0===e&&this.dispose()}get needsUpdate(){return this.source!==this._source}_exec(){return null===this.codeNode||(!0===this._needsOutputUpdate&&(this._value=this.call("main"),this._needsOutputUpdate=!1),this._output.value=this._value),this}_refresh(){this.needsUpdate=!0,this._exec(),this._output.refresh()}}const px=Hi(hx).setParameterLength(1,2);function gx(e){let t;const r=e.context.getViewZ;return void 0!==r&&(t=r(this)),(t||pd.z).negate()}const mx=Ki(([e,t],r)=>{const s=gx(r);return Xo(e,t,s)}),fx=Ki(([e],t)=>{const r=gx(t);return e.mul(e,r,r).negate().exp().oneMinus()}),yx=Ki(([e,t])=>gn(t.toFloat().mix(Hn.rgb,e.toVec3()),Hn.a));let bx=null,xx=null;class Tx extends Ys{static get type(){return"RangeNode"}constructor(e=tn(),t=tn()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=e.getTypeLength(Fs(this.minNode.value)),r=e.getTypeLength(Fs(this.maxNode.value));return t>r?t:r}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}setup(e){const t=e.object;let r=null;if(t.count>1){const i=this.minNode.value,n=this.maxNode.value,a=e.getTypeLength(Fs(i)),o=e.getTypeLength(Fs(n));bx=bx||new s,xx=xx||new s,bx.setScalar(0),xx.setScalar(0),1===a?bx.setScalar(i):i.isColor?bx.set(i.r,i.g,i.b,1):bx.set(i.x,i.y,i.z||0,i.w||0),1===o?xx.setScalar(n):n.isColor?xx.set(n.r,n.g,n.b,1):xx.set(n.x,n.y,n.z||0,n.w||0);const l=4,d=l*t.count,c=new Float32Array(d);for(let e=0;eGi(new vx(e,t)),Sx=Nx("numWorkgroups","uvec3"),Ex=Nx("workgroupId","uvec3"),Rx=Nx("globalId","uvec3"),Ax=Nx("localId","uvec3"),wx=Nx("subgroupSize","uint");const Cx=Hi(class extends Ys{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:r}=e;!0===r.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class Mx extends Qs{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let r;const s=e.context.assign;if(r=super.generate(e),!0!==s){const s=this.getNodeType(e);r=e.format(r,s,t)}return r}}class Px extends Ys{constructor(e,t,r=0){super(t),this.bufferType=t,this.bufferCount=r,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return console.warn('THREE.TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return Gi(new Mx(this,e))}generate(e){const t=""!==this.name?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class Bx extends Ys{static get type(){return"AtomicFunctionNode"}constructor(e,t,r){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=r,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),r=t.parents,s=this.method,i=this.getNodeType(e),n=this.getInputType(e),a=this.pointerNode,o=this.valueNode,u=[];u.push(`&${a.build(e,n)}`),null!==o&&u.push(o.build(e,n));const l=`${e.getMethod(s,i)}( ${u.join(", ")} )`;if(!(!!r&&(1===r.length&&!0===r[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Ku(l,i).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}Bx.ATOMIC_LOAD="atomicLoad",Bx.ATOMIC_STORE="atomicStore",Bx.ATOMIC_ADD="atomicAdd",Bx.ATOMIC_SUB="atomicSub",Bx.ATOMIC_MAX="atomicMax",Bx.ATOMIC_MIN="atomicMin",Bx.ATOMIC_AND="atomicAnd",Bx.ATOMIC_OR="atomicOr",Bx.ATOMIC_XOR="atomicXor";const Lx=Hi(Bx),Fx=(e,t,r)=>Lx(e,t,r).toStack();class Ix extends Js{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,r=null){super(),this.method=e,this.aNode=t,this.bNode=r}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,r=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(r)?0:e.getTypeLength(r))?t:r}getNodeType(e){const t=this.method;return t===Ix.SUBGROUP_ELECT?"bool":t===Ix.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const r=this.method,s=this.getNodeType(e),i=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(r===Ix.SUBGROUP_BROADCAST||r===Ix.SUBGROUP_SHUFFLE||r===Ix.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,s),a.build(e,"float"===t?"int":s))}else r===Ix.SUBGROUP_SHUFFLE_XOR||r===Ix.SUBGROUP_SHUFFLE_DOWN||r===Ix.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,s),a.build(e,"uint")):(null!==n&&o.push(n.build(e,i)),null!==a&&o.push(a.build(e,i)));const u=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(r,s)}${u}`,s,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Ix.SUBGROUP_ELECT="subgroupElect",Ix.SUBGROUP_BALLOT="subgroupBallot",Ix.SUBGROUP_ADD="subgroupAdd",Ix.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",Ix.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",Ix.SUBGROUP_MUL="subgroupMul",Ix.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",Ix.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",Ix.SUBGROUP_AND="subgroupAnd",Ix.SUBGROUP_OR="subgroupOr",Ix.SUBGROUP_XOR="subgroupXor",Ix.SUBGROUP_MIN="subgroupMin",Ix.SUBGROUP_MAX="subgroupMax",Ix.SUBGROUP_ALL="subgroupAll",Ix.SUBGROUP_ANY="subgroupAny",Ix.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",Ix.QUAD_SWAP_X="quadSwapX",Ix.QUAD_SWAP_Y="quadSwapY",Ix.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",Ix.SUBGROUP_BROADCAST="subgroupBroadcast",Ix.SUBGROUP_SHUFFLE="subgroupShuffle",Ix.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",Ix.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",Ix.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",Ix.QUAD_BROADCAST="quadBroadcast";const Dx=qi(Ix,Ix.SUBGROUP_ELECT).setParameterLength(0),Ux=qi(Ix,Ix.SUBGROUP_BALLOT).setParameterLength(1),Vx=qi(Ix,Ix.SUBGROUP_ADD).setParameterLength(1),Ox=qi(Ix,Ix.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),Gx=qi(Ix,Ix.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),kx=qi(Ix,Ix.SUBGROUP_MUL).setParameterLength(1),zx=qi(Ix,Ix.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),$x=qi(Ix,Ix.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),Hx=qi(Ix,Ix.SUBGROUP_AND).setParameterLength(1),Wx=qi(Ix,Ix.SUBGROUP_OR).setParameterLength(1),qx=qi(Ix,Ix.SUBGROUP_XOR).setParameterLength(1),jx=qi(Ix,Ix.SUBGROUP_MIN).setParameterLength(1),Xx=qi(Ix,Ix.SUBGROUP_MAX).setParameterLength(1),Kx=qi(Ix,Ix.SUBGROUP_ALL).setParameterLength(0),Yx=qi(Ix,Ix.SUBGROUP_ANY).setParameterLength(0),Qx=qi(Ix,Ix.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),Zx=qi(Ix,Ix.QUAD_SWAP_X).setParameterLength(1),Jx=qi(Ix,Ix.QUAD_SWAP_Y).setParameterLength(1),eT=qi(Ix,Ix.QUAD_SWAP_DIAGONAL).setParameterLength(1),tT=qi(Ix,Ix.SUBGROUP_BROADCAST).setParameterLength(2),rT=qi(Ix,Ix.SUBGROUP_SHUFFLE).setParameterLength(2),sT=qi(Ix,Ix.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),iT=qi(Ix,Ix.SUBGROUP_SHUFFLE_UP).setParameterLength(2),nT=qi(Ix,Ix.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),aT=qi(Ix,Ix.QUAD_BROADCAST).setParameterLength(1);let oT;function uT(e){oT=oT||new WeakMap;let t=oT.get(e);return void 0===t&&oT.set(e,t={}),t}function lT(e){const t=uT(e);return t.shadowMatrix||(t.shadowMatrix=oa("mat4").setGroup(ia).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||e.shadow.updateMatrices(e),e.shadow.matrix)))}function dT(e,t=cd){const r=lT(e).mul(t);return r.xyz.div(r.w)}function cT(e){const t=uT(e);return t.position||(t.position=oa(new r).setGroup(ia).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.matrixWorld)))}function hT(e){const t=uT(e);return t.targetPosition||(t.targetPosition=oa(new r).setGroup(ia).onRenderUpdate((t,r)=>r.value.setFromMatrixPosition(e.target.matrixWorld)))}function pT(e){const t=uT(e);return t.viewPosition||(t.viewPosition=oa(new r).setGroup(ia).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new r,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const gT=e=>Dl.transformDirection(cT(e).sub(hT(e))),mT=(e,t)=>{for(const r of t)if(r.isAnalyticLightNode&&r.light.id===e)return r;return null},fT=new WeakMap,yT=[];class bT extends Ys{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Sn("vec3","totalDiffuse"),this.totalSpecularNode=Sn("vec3","totalSpecular"),this.outgoingLightNode=Sn("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;te.sort((e,t)=>e.id-t.id))(this._lights),i=e.renderer.library;for(const e of s)if(e.isNode)t.push(Gi(e));else{let s=null;if(null!==r&&(s=mT(e.id,r)),null===s){const r=i.getLightNodeClass(e.constructor);if(null===r){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let s=null;fT.has(e)?s=fT.get(e):(s=Gi(new r(e)),fT.set(e,s)),t.push(s)}}this._lightNodes=t}setupDirectLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.direct({...r,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,r){const{lightingModel:s,reflectedLight:i}=e.context;s.directRectArea({...r,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(const r of t)r.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let r=this.outgoingLightNode;const s=e.context,i=s.lightingModel,n=e.getNodeProperties(this);if(i){const{totalDiffuseNode:t,totalSpecularNode:a}=this;s.outgoingLight=r;const o=e.addStack();n.nodes=o.nodes,i.start(e);const{backdrop:u,backdropAlpha:l}=s,{directDiffuse:d,directSpecular:c,indirectDiffuse:h,indirectSpecular:p}=s.reflectedLight;let g=d.add(h);null!==u&&(g=dn(null!==l?l.mix(g,u):u),s.material.transparent=!0),t.assign(g),a.assign(c.add(p)),r.assign(t.add(a)),i.finish(e),r=r.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,r}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class xT extends Ys{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=ks.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){TT.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||cd)}}const TT=Sn("vec3","shadowPositionWorld");function _T(t,r={}){return r.toneMapping=t.toneMapping,r.toneMappingExposure=t.toneMappingExposure,r.outputColorSpace=t.outputColorSpace,r.renderTarget=t.getRenderTarget(),r.activeCubeFace=t.getActiveCubeFace(),r.activeMipmapLevel=t.getActiveMipmapLevel(),r.renderObjectFunction=t.getRenderObjectFunction(),r.pixelRatio=t.getPixelRatio(),r.mrt=t.getMRT(),r.clearColor=t.getClearColor(r.clearColor||new e),r.clearAlpha=t.getClearAlpha(),r.autoClear=t.autoClear,r.scissorTest=t.getScissorTest(),r}function vT(e,t){return t=_T(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function NT(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}function ST(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function ET(e,t){return t=ST(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function RT(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function AT(e,t,r){return r=ET(t,r=vT(e,r))}function wT(e,t,r){NT(e,r),RT(t,r)}var CT=Object.freeze({__proto__:null,resetRendererAndSceneState:AT,resetRendererState:vT,resetSceneState:ET,restoreRendererAndSceneState:wT,restoreRendererState:NT,restoreSceneState:RT,saveRendererAndSceneState:function(e,t,r={}){return r=ST(t,r=_T(e,r))},saveRendererState:_T,saveSceneState:ST});const MT=new WeakMap,PT=Ki(({depthTexture:e,shadowCoord:t,depthLayer:r})=>{let s=cl(e,t.xy).setName("t_basic");return e.isArrayTexture&&(s=s.depth(r)),s.compare(t.z)}),BT=Ki(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=cl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=jd("mapSize","vec2",r).setGroup(ia),a=jd("radius","float",r).setGroup(ia),o=an(1).div(n),u=o.x.negate().mul(a),l=o.y.negate().mul(a),d=o.x.mul(a),c=o.y.mul(a),h=u.div(2),p=l.div(2),g=d.div(2),m=c.div(2);return fa(i(t.xy.add(an(u,l)),t.z),i(t.xy.add(an(0,l)),t.z),i(t.xy.add(an(d,l)),t.z),i(t.xy.add(an(h,p)),t.z),i(t.xy.add(an(0,p)),t.z),i(t.xy.add(an(g,p)),t.z),i(t.xy.add(an(u,0)),t.z),i(t.xy.add(an(h,0)),t.z),i(t.xy,t.z),i(t.xy.add(an(g,0)),t.z),i(t.xy.add(an(d,0)),t.z),i(t.xy.add(an(h,m)),t.z),i(t.xy.add(an(0,m)),t.z),i(t.xy.add(an(g,m)),t.z),i(t.xy.add(an(u,c)),t.z),i(t.xy.add(an(0,c)),t.z),i(t.xy.add(an(d,c)),t.z)).mul(1/17)}),LT=Ki(({depthTexture:e,shadowCoord:t,shadow:r,depthLayer:s})=>{const i=(t,r)=>{let i=cl(e,t);return e.isArrayTexture&&(i=i.depth(s)),i.compare(r)},n=jd("mapSize","vec2",r).setGroup(ia),a=an(1).div(n),o=a.x,u=a.y,l=t.xy,d=ao(l.mul(n).add(.5));return l.subAssign(d.mul(a)),fa(i(l,t.z),i(l.add(an(o,0)),t.z),i(l.add(an(0,u)),t.z),i(l.add(a),t.z),Ho(i(l.add(an(o.negate(),0)),t.z),i(l.add(an(o.mul(2),0)),t.z),d.x),Ho(i(l.add(an(o.negate(),u)),t.z),i(l.add(an(o.mul(2),u)),t.z),d.x),Ho(i(l.add(an(0,u.negate())),t.z),i(l.add(an(0,u.mul(2))),t.z),d.y),Ho(i(l.add(an(o,u.negate())),t.z),i(l.add(an(o,u.mul(2))),t.z),d.y),Ho(Ho(i(l.add(an(o.negate(),u.negate())),t.z),i(l.add(an(o.mul(2),u.negate())),t.z),d.x),Ho(i(l.add(an(o.negate(),u.mul(2))),t.z),i(l.add(an(o.mul(2),u.mul(2))),t.z),d.x),d.y)).mul(1/9)}),FT=Ki(({depthTexture:e,shadowCoord:t,depthLayer:r})=>{const s=tn(1).toVar();let i=cl(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(r)),i=i.rg;const n=Po(t.z,i.x);return Zi(n.notEqual(tn(1)),()=>{const e=t.z.sub(i.x),r=Mo(0,i.y.mul(i.y));let a=r.div(r.add(e.mul(e)));a=Wo(ya(a,.3).div(.95-.3)),s.assign(Wo(Mo(n,a)))}),s}),IT=Ki(([e,t,r])=>{let s=cd.sub(e).length();return s=s.sub(t).div(r.sub(t)),s=s.saturate(),s}),DT=e=>{let t=MT.get(e);if(void 0===t){const r=e.isPointLight?(e=>{const t=e.shadow.camera,r=jd("near","float",t).setGroup(ia),s=jd("far","float",t).setGroup(ia),i=Wl(e);return IT(i,r,s)})(e):null;t=new Sp,t.colorNode=gn(0,0,0,1),t.depthNode=r,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,MT.set(e,t)}return t},UT=new Nf,VT=[],OT=(e,t,r,s)=>{VT[0]=e,VT[1]=t;let i=UT.get(VT);return void 0!==i&&i.shadowType===r&&i.useVelocity===s||(i=(i,n,a,o,u,l,...d)=>{(!0===i.castShadow||i.receiveShadow&&r===De)&&(s&&(Ds(i).useVelocity=!0),i.onBeforeShadow(e,i,a,t.camera,o,n.overrideMaterial,l),e.renderObject(i,n,a,o,u,l,...d),i.onAfterShadow(e,i,a,t.camera,o,n.overrideMaterial,l))},i.shadowType=r,i.useVelocity=s,UT.set(VT,i)),VT[0]=null,VT[1]=null,i},GT=Ki(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=tn(0).toVar("meanVertical"),a=tn(0).toVar("squareMeanVertical"),o=e.lessThanEqual(tn(1)).select(tn(0),tn(2).div(e.sub(1))),u=e.lessThanEqual(tn(1)).select(tn(0),tn(-1));Uh({start:rn(0),end:rn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(tn(e).mul(o));let d=s.sample(fa(El.xy,an(0,l).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),d=d.x,n.addAssign(d),a.addAssign(d.mul(d))}),n.divAssign(e),a.divAssign(e);const l=to(a.sub(n.mul(n)));return an(n,l)}),kT=Ki(({samples:e,radius:t,size:r,shadowPass:s,depthLayer:i})=>{const n=tn(0).toVar("meanHorizontal"),a=tn(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(tn(1)).select(tn(0),tn(2).div(e.sub(1))),u=e.lessThanEqual(tn(1)).select(tn(0),tn(-1));Uh({start:rn(0),end:rn(e),type:"int",condition:"<"},({i:e})=>{const l=u.add(tn(e).mul(o));let d=s.sample(fa(El.xy,an(l,0).mul(t)).div(r));s.value.isArrayTexture&&(d=d.depth(i)),n.addAssign(d.x),a.addAssign(fa(d.y.mul(d.y),d.x.mul(d.x)))}),n.divAssign(e),a.divAssign(e);const l=to(a.sub(n.mul(n)));return an(n,l)}),zT=[PT,BT,LT,FT];let $T;const HT=new sb;class WT extends xT{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n}){const a=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1)).and(s.z.lessThanEqual(1)),o=t({depthTexture:r,shadowCoord:s,shadow:i,depthLayer:n});return a.select(o,tn(1))}setupShadowCoord(e,t){const{shadow:r}=this,{renderer:s}=e,i=jd("bias","float",r).setGroup(ia);let n,a=t;if(r.camera.isOrthographicCamera||!0!==s.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z,s.coordinateSystem===d&&(n=n.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=jd("near","float",r.camera).setGroup(ia),s=jd("far","float",r.camera).setGroup(ia);n=ap(e.negate(),t,s)}return a=dn(a.x,a.y.oneMinus(),n.add(i)),a}getShadowFilterFn(e){return zT[e]}setupRenderTarget(e,t){const r=new V(e.mapSize.width,e.mapSize.height);r.name="ShadowDepthTexture",r.compareFunction=Ue;const s=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return s.texture.name="ShadowMap",s.texture.type=e.mapType,s.depthTexture=r,{shadowMap:s,depthTexture:r}}setupShadow(e){const{renderer:t}=e,{light:r,shadow:s}=this,i=t.shadowMap.type,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(s,e);if(s.camera.updateProjectionMatrix(),i===De&&!0!==s.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Ve,type:ce,depthBuffer:!1}));let t=cl(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let r=cl(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(r=r.depth(this.depthLayer));const i=jd("blurSamples","float",s).setGroup(ia),o=jd("radius","float",s).setGroup(ia),u=jd("mapSize","vec2",s).setGroup(ia);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Sp);l.fragmentNode=GT({samples:i,radius:o,size:u,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Sp),l.fragmentNode=kT({samples:i,radius:o,size:u,shadowPass:r,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const o=jd("intensity","float",s).setGroup(ia),u=jd("normalBias","float",s).setGroup(ia),l=lT(r).mul(TT.add(Ed.mul(u))),d=this.setupShadowCoord(e,l),c=s.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===c)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const h=i===De&&!0!==s.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,p=this.setupShadowFilter(e,{filterFn:c,shadowTexture:a.texture,depthTexture:h,shadowCoord:d,shadow:s,depthLayer:this.depthLayer});let g=cl(a.texture,d);n.isArrayTexture&&(g=g.depth(this.depthLayer));const m=Ho(1,p.rgb.mix(g,1),o.mul(g.a)).toVar();return this.shadowMap=a,this.shadow.map=a,m}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Ki(()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t})()}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e;t.updateMatrices(s),r.setSize(t.mapSize.width,t.mapSize.height,r.depth),i.render(n,t.camera)}updateShadow(e){const{shadowMap:t,light:r,shadow:s}=this,{renderer:i,scene:n,camera:a}=e,o=i.shadowMap.type,u=t.depthTexture.version;this._depthVersionCached=u;const l=s.camera.layers.mask;4294967294&s.camera.layers.mask||(s.camera.layers.mask=a.layers.mask);const d=i.getRenderObjectFunction(),c=i.getMRT(),h=!!c&&c.has("velocity");$T=AT(i,n,$T),n.overrideMaterial=DT(r),i.setRenderObjectFunction(OT(i,s,o,h)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(d),o===De&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,wT(i,n,$T)}vsmPass(e){const{shadow:t}=this,r=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,r),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,r),e.setRenderTarget(this.vsmShadowMapVertical),HT.material=this.vsmMaterialVertical,HT.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),HT.material=this.vsmMaterialHorizontal,HT.render(e)}dispose(){this.shadowMap.dispose(),this.shadowMap=null,null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null),super.dispose()}updateBefore(e){const{shadow:t}=this;let r=t.needsUpdate||t.autoUpdate;r&&(this._cameraFrameId[e.camera]===e.frameId&&(r=!1),this._cameraFrameId[e.camera]=e.frameId),r&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const qT=(e,t)=>Gi(new WT(e,t)),jT=new e,XT=Ki(([e,t])=>{const r=e.toVar(),s=go(r),i=xa(1,Mo(s.x,Mo(s.y,s.z)));s.mulAssign(i),r.mulAssign(i.mul(t.mul(2).oneMinus()));const n=an(r.xy).toVar(),a=t.mul(1.5).oneMinus();return Zi(s.z.greaterThanEqual(a),()=>{Zi(r.z.greaterThan(0),()=>{n.x.assign(ya(4,r.x))})}).ElseIf(s.x.greaterThanEqual(a),()=>{const e=mo(r.x);n.x.assign(r.z.mul(e).add(e.mul(2)))}).ElseIf(s.y.greaterThanEqual(a),()=>{const e=mo(r.y);n.x.assign(r.x.add(e.mul(2)).add(2)),n.y.assign(r.z.mul(e).sub(2))}),an(.125,.25).mul(n).add(an(.375,.75)).flipY()}).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),KT=Ki(({depthTexture:e,bd3D:t,dp:r,texelSize:s})=>cl(e,XT(t,s.y)).compare(r)),YT=Ki(({depthTexture:e,bd3D:t,dp:r,texelSize:s,shadow:i})=>{const n=jd("radius","float",i).setGroup(ia),a=an(-1,1).mul(n).mul(s.y);return cl(e,XT(t.add(a.xyy),s.y)).compare(r).add(cl(e,XT(t.add(a.yyy),s.y)).compare(r)).add(cl(e,XT(t.add(a.xyx),s.y)).compare(r)).add(cl(e,XT(t.add(a.yyx),s.y)).compare(r)).add(cl(e,XT(t,s.y)).compare(r)).add(cl(e,XT(t.add(a.xxy),s.y)).compare(r)).add(cl(e,XT(t.add(a.yxy),s.y)).compare(r)).add(cl(e,XT(t.add(a.xxx),s.y)).compare(r)).add(cl(e,XT(t.add(a.yxx),s.y)).compare(r)).mul(1/9)}),QT=Ki(({filterFn:e,depthTexture:t,shadowCoord:r,shadow:s})=>{const i=r.xyz.toVar(),n=i.length(),a=oa("float").setGroup(ia).onRenderUpdate(()=>s.camera.near),o=oa("float").setGroup(ia).onRenderUpdate(()=>s.camera.far),u=jd("bias","float",s).setGroup(ia),l=oa(s.mapSize).setGroup(ia),d=tn(1).toVar();return Zi(n.sub(o).lessThanEqual(0).and(n.sub(a).greaterThanEqual(0)),()=>{const r=n.sub(a).div(o.sub(a)).toVar();r.addAssign(u);const c=i.normalize(),h=an(1).div(l.mul(an(4,2)));d.assign(e({depthTexture:t,bd3D:c,dp:r,texelSize:h,shadow:s}))}),d}),ZT=new s,JT=new t,e_=new t;class t_ extends WT{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===Oe?KT:YT}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n}){return QT({filterFn:t,shadowTexture:r,depthTexture:s,shadowCoord:i,shadow:n})}renderShadow(e){const{shadow:t,shadowMap:r,light:s}=this,{renderer:i,scene:n}=e,a=t.getFrameExtents();e_.copy(t.mapSize),e_.multiply(a),r.setSize(e_.width,e_.height),JT.copy(t.mapSize);const o=i.autoClear,u=i.getClearColor(jT),l=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha),i.clear();const d=t.getViewportCount();for(let e=0;eGi(new t_(e,t));class s_ extends Hh{static get type(){return"AnalyticLightNode"}constructor(t=null){super(),this.light=t,this.color=new e,this.colorNode=t&&t.colorNode||oa(this.color).setGroup(ia),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=ks.FRAME}getHash(){return this.light.uuid}getLightVector(e){return pT(this.light).sub(e.context.positionView||pd)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return qT(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let r=this.shadowColorNode;if(null===r){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?Gi(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=r=this.colorNode.mul(t),this.baseColorNode=this.colorNode}this.colorNode=r}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),r=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),r&&e.lightsNode.setupDirectRectAreaLight(e,this,r)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const i_=Ki(({lightDistance:e,cutoffDistance:t,decayExponent:r})=>{const s=e.pow(r).max(.01).reciprocal();return t.greaterThan(0).select(s.mul(e.div(t).pow4().oneMinus().clamp().pow2()),s)}),n_=({color:e,lightVector:t,cutoffDistance:r,decayExponent:s})=>{const i=t.normalize(),n=t.length(),a=i_({lightDistance:n,cutoffDistance:r,decayExponent:s});return{lightDirection:i,lightColor:e.mul(a)}};class a_ extends s_{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=oa(0).setGroup(ia),this.decayExponentNode=oa(2).setGroup(ia)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return r_(this.light)}setupDirect(e){return n_({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const o_=Ki(([e=sl()])=>{const t=e.mul(2),r=t.x.floor(),s=t.y.floor();return r.add(s).mod(2).sign()}),u_=Ki(([e=sl()],{renderer:t,material:r})=>{const s=$o(e.mul(2).sub(1));let i;if(r.alphaToCoverage&&t.samples>1){const e=tn(s.fwidth()).toVar();i=Xo(e.oneMinus(),e.add(1),s).oneMinus()}else i=iu(s.greaterThan(1),0,1);return i}),l_=Ki(([e,t,r])=>{const s=tn(r).toVar(),i=tn(t).toVar(),n=nn(e).toVar();return iu(n,i,s)}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),d_=Ki(([e,t])=>{const r=nn(t).toVar(),s=tn(e).toVar();return iu(r,s.negate(),s)}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),c_=Ki(([e])=>{const t=tn(e).toVar();return rn(so(t))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),h_=Ki(([e,t])=>{const r=tn(e).toVar();return t.assign(c_(r)),r.sub(tn(t))}),p_=Ay([Ki(([e,t,r,s,i,n])=>{const a=tn(n).toVar(),o=tn(i).toVar(),u=tn(s).toVar(),l=tn(r).toVar(),d=tn(t).toVar(),c=tn(e).toVar(),h=tn(ya(1,o)).toVar();return ya(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),Ki(([e,t,r,s,i,n])=>{const a=tn(n).toVar(),o=tn(i).toVar(),u=dn(s).toVar(),l=dn(r).toVar(),d=dn(t).toVar(),c=dn(e).toVar(),h=tn(ya(1,o)).toVar();return ya(1,a).mul(c.mul(h).add(d.mul(o))).add(a.mul(l.mul(h).add(u.mul(o))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]})]),g_=Ay([Ki(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=tn(d).toVar(),h=tn(l).toVar(),p=tn(u).toVar(),g=tn(o).toVar(),m=tn(a).toVar(),f=tn(n).toVar(),y=tn(i).toVar(),b=tn(s).toVar(),x=tn(r).toVar(),T=tn(t).toVar(),_=tn(e).toVar(),v=tn(ya(1,p)).toVar(),N=tn(ya(1,h)).toVar();return tn(ya(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),Ki(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=tn(d).toVar(),h=tn(l).toVar(),p=tn(u).toVar(),g=dn(o).toVar(),m=dn(a).toVar(),f=dn(n).toVar(),y=dn(i).toVar(),b=dn(s).toVar(),x=dn(r).toVar(),T=dn(t).toVar(),_=dn(e).toVar(),v=tn(ya(1,p)).toVar(),N=tn(ya(1,h)).toVar();return tn(ya(1,c)).toVar().mul(N.mul(_.mul(v).add(T.mul(p))).add(h.mul(x.mul(v).add(b.mul(p))))).add(c.mul(N.mul(y.mul(v).add(f.mul(p))).add(h.mul(m.mul(v).add(g.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]})]),m_=Ki(([e,t,r])=>{const s=tn(r).toVar(),i=tn(t).toVar(),n=sn(e).toVar(),a=sn(n.bitAnd(sn(7))).toVar(),o=tn(l_(a.lessThan(sn(4)),i,s)).toVar(),u=tn(ba(2,l_(a.lessThan(sn(4)),s,i))).toVar();return d_(o,nn(a.bitAnd(sn(1)))).add(d_(u,nn(a.bitAnd(sn(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),f_=Ki(([e,t,r,s])=>{const i=tn(s).toVar(),n=tn(r).toVar(),a=tn(t).toVar(),o=sn(e).toVar(),u=sn(o.bitAnd(sn(15))).toVar(),l=tn(l_(u.lessThan(sn(8)),a,n)).toVar(),d=tn(l_(u.lessThan(sn(4)),n,l_(u.equal(sn(12)).or(u.equal(sn(14))),a,i))).toVar();return d_(l,nn(u.bitAnd(sn(1)))).add(d_(d,nn(u.bitAnd(sn(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),y_=Ay([m_,f_]),b_=Ki(([e,t,r])=>{const s=tn(r).toVar(),i=tn(t).toVar(),n=hn(e).toVar();return dn(y_(n.x,i,s),y_(n.y,i,s),y_(n.z,i,s))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),x_=Ki(([e,t,r,s])=>{const i=tn(s).toVar(),n=tn(r).toVar(),a=tn(t).toVar(),o=hn(e).toVar();return dn(y_(o.x,a,n,i),y_(o.y,a,n,i),y_(o.z,a,n,i))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]}),T_=Ay([b_,x_]),__=Ki(([e])=>{const t=tn(e).toVar();return ba(.6616,t)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),v_=Ki(([e])=>{const t=tn(e).toVar();return ba(.982,t)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),N_=Ay([__,Ki(([e])=>{const t=dn(e).toVar();return ba(.6616,t)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),S_=Ay([v_,Ki(([e])=>{const t=dn(e).toVar();return ba(.982,t)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),E_=Ki(([e,t])=>{const r=rn(t).toVar(),s=sn(e).toVar();return s.shiftLeft(r).bitOr(s.shiftRight(rn(32).sub(r)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),R_=Ki(([e,t,r])=>{e.subAssign(r),e.bitXorAssign(E_(r,rn(4))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(E_(e,rn(6))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(E_(t,rn(8))),t.addAssign(e),e.subAssign(r),e.bitXorAssign(E_(r,rn(16))),r.addAssign(t),t.subAssign(e),t.bitXorAssign(E_(e,rn(19))),e.addAssign(r),r.subAssign(t),r.bitXorAssign(E_(t,rn(4))),t.addAssign(e)}),A_=Ki(([e,t,r])=>{const s=sn(r).toVar(),i=sn(t).toVar(),n=sn(e).toVar();return s.bitXorAssign(i),s.subAssign(E_(i,rn(14))),n.bitXorAssign(s),n.subAssign(E_(s,rn(11))),i.bitXorAssign(n),i.subAssign(E_(n,rn(25))),s.bitXorAssign(i),s.subAssign(E_(i,rn(16))),n.bitXorAssign(s),n.subAssign(E_(s,rn(4))),i.bitXorAssign(n),i.subAssign(E_(n,rn(14))),s.bitXorAssign(i),s.subAssign(E_(i,rn(24))),s}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),w_=Ki(([e])=>{const t=sn(e).toVar();return tn(t).div(tn(sn(rn(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),C_=Ki(([e])=>{const t=tn(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),M_=Ay([Ki(([e])=>{const t=rn(e).toVar(),r=sn(sn(1)).toVar(),s=sn(sn(rn(3735928559)).add(r.shiftLeft(sn(2))).add(sn(13))).toVar();return A_(s.add(sn(t)),s,s)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),Ki(([e,t])=>{const r=rn(t).toVar(),s=rn(e).toVar(),i=sn(sn(2)).toVar(),n=sn().toVar(),a=sn().toVar(),o=sn().toVar();return n.assign(a.assign(o.assign(sn(rn(3735928559)).add(i.shiftLeft(sn(2))).add(sn(13))))),n.addAssign(sn(s)),a.addAssign(sn(r)),A_(n,a,o)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Ki(([e,t,r])=>{const s=rn(r).toVar(),i=rn(t).toVar(),n=rn(e).toVar(),a=sn(sn(3)).toVar(),o=sn().toVar(),u=sn().toVar(),l=sn().toVar();return o.assign(u.assign(l.assign(sn(rn(3735928559)).add(a.shiftLeft(sn(2))).add(sn(13))))),o.addAssign(sn(n)),u.addAssign(sn(i)),l.addAssign(sn(s)),A_(o,u,l)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Ki(([e,t,r,s])=>{const i=rn(s).toVar(),n=rn(r).toVar(),a=rn(t).toVar(),o=rn(e).toVar(),u=sn(sn(4)).toVar(),l=sn().toVar(),d=sn().toVar(),c=sn().toVar();return l.assign(d.assign(c.assign(sn(rn(3735928559)).add(u.shiftLeft(sn(2))).add(sn(13))))),l.addAssign(sn(o)),d.addAssign(sn(a)),c.addAssign(sn(n)),R_(l,d,c),l.addAssign(sn(i)),A_(l,d,c)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),Ki(([e,t,r,s,i])=>{const n=rn(i).toVar(),a=rn(s).toVar(),o=rn(r).toVar(),u=rn(t).toVar(),l=rn(e).toVar(),d=sn(sn(5)).toVar(),c=sn().toVar(),h=sn().toVar(),p=sn().toVar();return c.assign(h.assign(p.assign(sn(rn(3735928559)).add(d.shiftLeft(sn(2))).add(sn(13))))),c.addAssign(sn(l)),h.addAssign(sn(u)),p.addAssign(sn(o)),R_(c,h,p),c.addAssign(sn(a)),h.addAssign(sn(n)),A_(c,h,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]})]),P_=Ay([Ki(([e,t])=>{const r=rn(t).toVar(),s=rn(e).toVar(),i=sn(M_(s,r)).toVar(),n=hn().toVar();return n.x.assign(i.bitAnd(rn(255))),n.y.assign(i.shiftRight(rn(8)).bitAnd(rn(255))),n.z.assign(i.shiftRight(rn(16)).bitAnd(rn(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Ki(([e,t,r])=>{const s=rn(r).toVar(),i=rn(t).toVar(),n=rn(e).toVar(),a=sn(M_(n,i,s)).toVar(),o=hn().toVar();return o.x.assign(a.bitAnd(rn(255))),o.y.assign(a.shiftRight(rn(8)).bitAnd(rn(255))),o.z.assign(a.shiftRight(rn(16)).bitAnd(rn(255))),o}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),B_=Ay([Ki(([e])=>{const t=an(e).toVar(),r=rn().toVar(),s=rn().toVar(),i=tn(h_(t.x,r)).toVar(),n=tn(h_(t.y,s)).toVar(),a=tn(C_(i)).toVar(),o=tn(C_(n)).toVar(),u=tn(p_(y_(M_(r,s),i,n),y_(M_(r.add(rn(1)),s),i.sub(1),n),y_(M_(r,s.add(rn(1))),i,n.sub(1)),y_(M_(r.add(rn(1)),s.add(rn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return N_(u)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),Ki(([e])=>{const t=dn(e).toVar(),r=rn().toVar(),s=rn().toVar(),i=rn().toVar(),n=tn(h_(t.x,r)).toVar(),a=tn(h_(t.y,s)).toVar(),o=tn(h_(t.z,i)).toVar(),u=tn(C_(n)).toVar(),l=tn(C_(a)).toVar(),d=tn(C_(o)).toVar(),c=tn(g_(y_(M_(r,s,i),n,a,o),y_(M_(r.add(rn(1)),s,i),n.sub(1),a,o),y_(M_(r,s.add(rn(1)),i),n,a.sub(1),o),y_(M_(r.add(rn(1)),s.add(rn(1)),i),n.sub(1),a.sub(1),o),y_(M_(r,s,i.add(rn(1))),n,a,o.sub(1)),y_(M_(r.add(rn(1)),s,i.add(rn(1))),n.sub(1),a,o.sub(1)),y_(M_(r,s.add(rn(1)),i.add(rn(1))),n,a.sub(1),o.sub(1)),y_(M_(r.add(rn(1)),s.add(rn(1)),i.add(rn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return S_(c)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),L_=Ay([Ki(([e])=>{const t=an(e).toVar(),r=rn().toVar(),s=rn().toVar(),i=tn(h_(t.x,r)).toVar(),n=tn(h_(t.y,s)).toVar(),a=tn(C_(i)).toVar(),o=tn(C_(n)).toVar(),u=dn(p_(T_(P_(r,s),i,n),T_(P_(r.add(rn(1)),s),i.sub(1),n),T_(P_(r,s.add(rn(1))),i,n.sub(1)),T_(P_(r.add(rn(1)),s.add(rn(1))),i.sub(1),n.sub(1)),a,o)).toVar();return N_(u)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Ki(([e])=>{const t=dn(e).toVar(),r=rn().toVar(),s=rn().toVar(),i=rn().toVar(),n=tn(h_(t.x,r)).toVar(),a=tn(h_(t.y,s)).toVar(),o=tn(h_(t.z,i)).toVar(),u=tn(C_(n)).toVar(),l=tn(C_(a)).toVar(),d=tn(C_(o)).toVar(),c=dn(g_(T_(P_(r,s,i),n,a,o),T_(P_(r.add(rn(1)),s,i),n.sub(1),a,o),T_(P_(r,s.add(rn(1)),i),n,a.sub(1),o),T_(P_(r.add(rn(1)),s.add(rn(1)),i),n.sub(1),a.sub(1),o),T_(P_(r,s,i.add(rn(1))),n,a,o.sub(1)),T_(P_(r.add(rn(1)),s,i.add(rn(1))),n.sub(1),a,o.sub(1)),T_(P_(r,s.add(rn(1)),i.add(rn(1))),n,a.sub(1),o.sub(1)),T_(P_(r.add(rn(1)),s.add(rn(1)),i.add(rn(1))),n.sub(1),a.sub(1),o.sub(1)),u,l,d)).toVar();return S_(c)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),F_=Ay([Ki(([e])=>{const t=tn(e).toVar(),r=rn(c_(t)).toVar();return w_(M_(r))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),Ki(([e])=>{const t=an(e).toVar(),r=rn(c_(t.x)).toVar(),s=rn(c_(t.y)).toVar();return w_(M_(r,s))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),Ki(([e])=>{const t=dn(e).toVar(),r=rn(c_(t.x)).toVar(),s=rn(c_(t.y)).toVar(),i=rn(c_(t.z)).toVar();return w_(M_(r,s,i))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),Ki(([e])=>{const t=gn(e).toVar(),r=rn(c_(t.x)).toVar(),s=rn(c_(t.y)).toVar(),i=rn(c_(t.z)).toVar(),n=rn(c_(t.w)).toVar();return w_(M_(r,s,i,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),I_=Ay([Ki(([e])=>{const t=tn(e).toVar(),r=rn(c_(t)).toVar();return dn(w_(M_(r,rn(0))),w_(M_(r,rn(1))),w_(M_(r,rn(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),Ki(([e])=>{const t=an(e).toVar(),r=rn(c_(t.x)).toVar(),s=rn(c_(t.y)).toVar();return dn(w_(M_(r,s,rn(0))),w_(M_(r,s,rn(1))),w_(M_(r,s,rn(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Ki(([e])=>{const t=dn(e).toVar(),r=rn(c_(t.x)).toVar(),s=rn(c_(t.y)).toVar(),i=rn(c_(t.z)).toVar();return dn(w_(M_(r,s,i,rn(0))),w_(M_(r,s,i,rn(1))),w_(M_(r,s,i,rn(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Ki(([e])=>{const t=gn(e).toVar(),r=rn(c_(t.x)).toVar(),s=rn(c_(t.y)).toVar(),i=rn(c_(t.z)).toVar(),n=rn(c_(t.w)).toVar();return dn(w_(M_(r,s,i,n,rn(0))),w_(M_(r,s,i,n,rn(1))),w_(M_(r,s,i,n,rn(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),D_=Ki(([e,t,r,s])=>{const i=tn(s).toVar(),n=tn(r).toVar(),a=rn(t).toVar(),o=dn(e).toVar(),u=tn(0).toVar(),l=tn(1).toVar();return Uh(a,()=>{u.addAssign(l.mul(B_(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),U_=Ki(([e,t,r,s])=>{const i=tn(s).toVar(),n=tn(r).toVar(),a=rn(t).toVar(),o=dn(e).toVar(),u=dn(0).toVar(),l=tn(1).toVar();return Uh(a,()=>{u.addAssign(l.mul(L_(o))),l.mulAssign(i),o.mulAssign(n)}),u}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),V_=Ki(([e,t,r,s])=>{const i=tn(s).toVar(),n=tn(r).toVar(),a=rn(t).toVar(),o=dn(e).toVar();return an(D_(o,a,n,i),D_(o.add(dn(rn(19),rn(193),rn(17))),a,n,i))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),O_=Ki(([e,t,r,s])=>{const i=tn(s).toVar(),n=tn(r).toVar(),a=rn(t).toVar(),o=dn(e).toVar(),u=dn(U_(o,a,n,i)).toVar(),l=tn(D_(o.add(dn(rn(19),rn(193),rn(17))),a,n,i)).toVar();return gn(u,l)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),G_=Ay([Ki(([e,t,r,s,i,n,a])=>{const o=rn(a).toVar(),u=tn(n).toVar(),l=rn(i).toVar(),d=rn(s).toVar(),c=rn(r).toVar(),h=rn(t).toVar(),p=an(e).toVar(),g=dn(I_(an(h.add(d),c.add(l)))).toVar(),m=an(g.x,g.y).toVar();m.subAssign(.5),m.mulAssign(u),m.addAssign(.5);const f=an(an(tn(h),tn(c)).add(m)).toVar(),y=an(f.sub(p)).toVar();return Zi(o.equal(rn(2)),()=>go(y.x).add(go(y.y))),Zi(o.equal(rn(3)),()=>Mo(go(y.x),go(y.y))),Io(y,y)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Ki(([e,t,r,s,i,n,a,o,u])=>{const l=rn(u).toVar(),d=tn(o).toVar(),c=rn(a).toVar(),h=rn(n).toVar(),p=rn(i).toVar(),g=rn(s).toVar(),m=rn(r).toVar(),f=rn(t).toVar(),y=dn(e).toVar(),b=dn(I_(dn(f.add(p),m.add(h),g.add(c)))).toVar();b.subAssign(.5),b.mulAssign(d),b.addAssign(.5);const x=dn(dn(tn(f),tn(m),tn(g)).add(b)).toVar(),T=dn(x.sub(y)).toVar();return Zi(l.equal(rn(2)),()=>go(T.x).add(go(T.y)).add(go(T.z))),Zi(l.equal(rn(3)),()=>Mo(go(T.x),go(T.y),go(T.z))),Io(T,T)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),k_=Ki(([e,t,r])=>{const s=rn(r).toVar(),i=tn(t).toVar(),n=an(e).toVar(),a=rn().toVar(),o=rn().toVar(),u=an(h_(n.x,a),h_(n.y,o)).toVar(),l=tn(1e6).toVar();return Uh({start:-1,end:rn(1),name:"x",condition:"<="},({x:e})=>{Uh({start:-1,end:rn(1),name:"y",condition:"<="},({y:t})=>{const r=tn(G_(u,e,t,a,o,i,s)).toVar();l.assign(Co(l,r))})}),Zi(s.equal(rn(0)),()=>{l.assign(to(l))}),l}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),z_=Ki(([e,t,r])=>{const s=rn(r).toVar(),i=tn(t).toVar(),n=an(e).toVar(),a=rn().toVar(),o=rn().toVar(),u=an(h_(n.x,a),h_(n.y,o)).toVar(),l=an(1e6,1e6).toVar();return Uh({start:-1,end:rn(1),name:"x",condition:"<="},({x:e})=>{Uh({start:-1,end:rn(1),name:"y",condition:"<="},({y:t})=>{const r=tn(G_(u,e,t,a,o,i,s)).toVar();Zi(r.lessThan(l.x),()=>{l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.y.assign(r)})})}),Zi(s.equal(rn(0)),()=>{l.assign(to(l))}),l}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),$_=Ki(([e,t,r])=>{const s=rn(r).toVar(),i=tn(t).toVar(),n=an(e).toVar(),a=rn().toVar(),o=rn().toVar(),u=an(h_(n.x,a),h_(n.y,o)).toVar(),l=dn(1e6,1e6,1e6).toVar();return Uh({start:-1,end:rn(1),name:"x",condition:"<="},({x:e})=>{Uh({start:-1,end:rn(1),name:"y",condition:"<="},({y:t})=>{const r=tn(G_(u,e,t,a,o,i,s)).toVar();Zi(r.lessThan(l.x),()=>{l.z.assign(l.y),l.y.assign(l.x),l.x.assign(r)}).ElseIf(r.lessThan(l.y),()=>{l.z.assign(l.y),l.y.assign(r)}).ElseIf(r.lessThan(l.z),()=>{l.z.assign(r)})})}),Zi(s.equal(rn(0)),()=>{l.assign(to(l))}),l}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),H_=Ay([k_,Ki(([e,t,r])=>{const s=rn(r).toVar(),i=tn(t).toVar(),n=dn(e).toVar(),a=rn().toVar(),o=rn().toVar(),u=rn().toVar(),l=dn(h_(n.x,a),h_(n.y,o),h_(n.z,u)).toVar(),d=tn(1e6).toVar();return Uh({start:-1,end:rn(1),name:"x",condition:"<="},({x:e})=>{Uh({start:-1,end:rn(1),name:"y",condition:"<="},({y:t})=>{Uh({start:-1,end:rn(1),name:"z",condition:"<="},({z:r})=>{const n=tn(G_(l,e,t,r,a,o,u,i,s)).toVar();d.assign(Co(d,n))})})}),Zi(s.equal(rn(0)),()=>{d.assign(to(d))}),d}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),W_=Ay([z_,Ki(([e,t,r])=>{const s=rn(r).toVar(),i=tn(t).toVar(),n=dn(e).toVar(),a=rn().toVar(),o=rn().toVar(),u=rn().toVar(),l=dn(h_(n.x,a),h_(n.y,o),h_(n.z,u)).toVar(),d=an(1e6,1e6).toVar();return Uh({start:-1,end:rn(1),name:"x",condition:"<="},({x:e})=>{Uh({start:-1,end:rn(1),name:"y",condition:"<="},({y:t})=>{Uh({start:-1,end:rn(1),name:"z",condition:"<="},({z:r})=>{const n=tn(G_(l,e,t,r,a,o,u,i,s)).toVar();Zi(n.lessThan(d.x),()=>{d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.y.assign(n)})})})}),Zi(s.equal(rn(0)),()=>{d.assign(to(d))}),d}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),q_=Ay([$_,Ki(([e,t,r])=>{const s=rn(r).toVar(),i=tn(t).toVar(),n=dn(e).toVar(),a=rn().toVar(),o=rn().toVar(),u=rn().toVar(),l=dn(h_(n.x,a),h_(n.y,o),h_(n.z,u)).toVar(),d=dn(1e6,1e6,1e6).toVar();return Uh({start:-1,end:rn(1),name:"x",condition:"<="},({x:e})=>{Uh({start:-1,end:rn(1),name:"y",condition:"<="},({y:t})=>{Uh({start:-1,end:rn(1),name:"z",condition:"<="},({z:r})=>{const n=tn(G_(l,e,t,r,a,o,u,i,s)).toVar();Zi(n.lessThan(d.x),()=>{d.z.assign(d.y),d.y.assign(d.x),d.x.assign(n)}).ElseIf(n.lessThan(d.y),()=>{d.z.assign(d.y),d.y.assign(n)}).ElseIf(n.lessThan(d.z),()=>{d.z.assign(n)})})})}),Zi(s.equal(rn(0)),()=>{d.assign(to(d))}),d}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),j_=Ki(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=rn(e).toVar(),h=an(t).toVar(),p=an(r).toVar(),g=an(s).toVar(),m=tn(i).toVar(),f=tn(n).toVar(),y=tn(a).toVar(),b=nn(o).toVar(),x=rn(u).toVar(),T=tn(l).toVar(),_=tn(d).toVar(),v=h.mul(p).add(g),N=tn(0).toVar();return Zi(c.equal(rn(0)),()=>{N.assign(L_(v))}),Zi(c.equal(rn(1)),()=>{N.assign(I_(v))}),Zi(c.equal(rn(2)),()=>{N.assign(q_(v,m,rn(0)))}),Zi(c.equal(rn(3)),()=>{N.assign(U_(dn(v,0),x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),Zi(b,()=>{N.assign(Wo(N,f,y))}),N}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),X_=Ki(([e,t,r,s,i,n,a,o,u,l,d])=>{const c=rn(e).toVar(),h=dn(t).toVar(),p=dn(r).toVar(),g=dn(s).toVar(),m=tn(i).toVar(),f=tn(n).toVar(),y=tn(a).toVar(),b=nn(o).toVar(),x=rn(u).toVar(),T=tn(l).toVar(),_=tn(d).toVar(),v=h.mul(p).add(g),N=tn(0).toVar();return Zi(c.equal(rn(0)),()=>{N.assign(L_(v))}),Zi(c.equal(rn(1)),()=>{N.assign(I_(v))}),Zi(c.equal(rn(2)),()=>{N.assign(q_(v,m,rn(0)))}),Zi(c.equal(rn(3)),()=>{N.assign(U_(v,x,T,_))}),N.assign(N.mul(y.sub(f)).add(f)),Zi(b,()=>{N.assign(Wo(N,f,y))}),N}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),K_=Ki(([e])=>{const t=e.y,r=e.z,s=dn().toVar();return Zi(t.lessThan(1e-4),()=>{s.assign(dn(r,r,r))}).Else(()=>{let i=e.x;i=i.sub(so(i)).mul(6).toVar();const n=rn(No(i)),a=i.sub(tn(n)),o=r.mul(t.oneMinus()),u=r.mul(t.mul(a).oneMinus()),l=r.mul(t.mul(a.oneMinus()).oneMinus());Zi(n.equal(rn(0)),()=>{s.assign(dn(r,l,o))}).ElseIf(n.equal(rn(1)),()=>{s.assign(dn(u,r,o))}).ElseIf(n.equal(rn(2)),()=>{s.assign(dn(o,r,l))}).ElseIf(n.equal(rn(3)),()=>{s.assign(dn(o,u,r))}).ElseIf(n.equal(rn(4)),()=>{s.assign(dn(l,o,r))}).Else(()=>{s.assign(dn(r,o,u))})}),s}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),Y_=Ki(([e])=>{const t=dn(e).toVar(),r=tn(t.x).toVar(),s=tn(t.y).toVar(),i=tn(t.z).toVar(),n=tn(Co(r,Co(s,i))).toVar(),a=tn(Mo(r,Mo(s,i))).toVar(),o=tn(a.sub(n)).toVar(),u=tn().toVar(),l=tn().toVar(),d=tn().toVar();return d.assign(a),Zi(a.greaterThan(0),()=>{l.assign(o.div(a))}).Else(()=>{l.assign(0)}),Zi(l.lessThanEqual(0),()=>{u.assign(0)}).Else(()=>{Zi(r.greaterThanEqual(a),()=>{u.assign(s.sub(i).div(o))}).ElseIf(s.greaterThanEqual(a),()=>{u.assign(fa(2,i.sub(r).div(o)))}).Else(()=>{u.assign(fa(4,r.sub(s).div(o)))}),u.mulAssign(1/6),Zi(u.lessThan(0),()=>{u.addAssign(1)})}),dn(u,l,d)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),Q_=Ki(([e])=>{const t=dn(e).toVar(),r=pn(Sa(t,dn(.04045))).toVar(),s=dn(t.div(12.92)).toVar(),i=dn(Uo(Mo(t.add(dn(.055)),dn(0)).div(1.055),dn(2.4))).toVar();return Ho(s,i,r)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Z_=(e,t)=>{e=tn(e),t=tn(t);const r=an(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Xo(e.sub(r),e.add(r),t)},J_=(e,t,r,s)=>Ho(e,t,r[s].clamp()),ev=(e,t,r,s,i)=>Ho(e,t,Z_(r,s[i])),tv=Ki(([e,t,r])=>{const s=no(e).toVar(),i=ya(tn(.5).mul(t.sub(r)),cd).div(s).toVar(),n=ya(tn(-.5).mul(t.sub(r)),cd).div(s).toVar(),a=dn().toVar();a.x=s.x.greaterThan(tn(0)).select(i.x,n.x),a.y=s.y.greaterThan(tn(0)).select(i.y,n.y),a.z=s.z.greaterThan(tn(0)).select(i.z,n.z);const o=Co(a.x,a.y,a.z).toVar();return cd.add(s.mul(o)).toVar().sub(r)}),rv=Ki(([e,t])=>{const r=e.x,s=e.y,i=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(s)),n=n.add(t.element(2).mul(1.023328).mul(i)),n=n.add(t.element(3).mul(1.023328).mul(r)),n=n.add(t.element(4).mul(.858086).mul(r).mul(s)),n=n.add(t.element(5).mul(.858086).mul(s).mul(i)),n=n.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(r).mul(i)),n=n.add(t.element(8).mul(.429043).mul(ba(r,r).sub(ba(s,s)))),n});var sv=Object.freeze({__proto__:null,BRDF_GGX:hg,BRDF_Lambert:Qp,BasicPointShadowFilter:KT,BasicShadowFilter:PT,Break:Vh,Const:pu,Continue:()=>Ku("continue").toStack(),DFGApprox:pg,D_GGX:lg,Discard:Yu,EPSILON:$a,F_Schlick:Yp,Fn:Ki,INFINITY:Ha,If:Zi,Loop:Uh,NodeAccess:$s,NodeShaderStage:Gs,NodeType:zs,NodeUpdateType:ks,OnMaterialUpdate:e=>hb(cb.MATERIAL,e),OnObjectUpdate:e=>hb(cb.OBJECT,e),PCFShadowFilter:BT,PCFSoftShadowFilter:LT,PI:Wa,PI2:qa,PointShadowFilter:YT,Return:()=>Ku("return").toStack(),Schlick_to_F0:mg,ScriptableNodeResources:cx,ShaderNode:Oi,Stack:Ji,Switch:(...e)=>li.Switch(...e),TBNViewMatrix:Tc,VSMShadowFilter:FT,V_GGX_SmithCorrelated:og,Var:hu,VarIntent:gu,abs:go,acesFilmicToneMapping:Qb,acos:ho,add:fa,addMethodChaining:ci,addNodeElement:function(e){console.warn("THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:tx,all:ja,alphaT:Un,and:Aa,anisotropy:Vn,anisotropyB:Gn,anisotropyT:On,any:Xa,append:e=>(console.warn("THREE.TSL: append() has been renamed to Stack()."),Ji(e)),array:la,arrayBuffer:e=>Gi(new oi(e,"ArrayBuffer")),asin:co,assign:ca,atan:po,atan2:eu,atomicAdd:(e,t)=>Fx(Bx.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>Fx(Bx.ATOMIC_AND,e,t),atomicFunc:Fx,atomicLoad:e=>Fx(Bx.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>Fx(Bx.ATOMIC_MAX,e,t),atomicMin:(e,t)=>Fx(Bx.ATOMIC_MIN,e,t),atomicOr:(e,t)=>Fx(Bx.ATOMIC_OR,e,t),atomicStore:(e,t)=>Fx(Bx.ATOMIC_STORE,e,t),atomicSub:(e,t)=>Fx(Bx.ATOMIC_SUB,e,t),atomicXor:(e,t)=>Fx(Bx.ATOMIC_XOR,e,t),attenuationColor:Zn,attenuationDistance:Qn,attribute:rl,attributeArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Ms("float")):(r=Ps(t),s=Ms(t));const i=new gb(e,r,s);return Bh(i,t,e)},backgroundBlurriness:Tb,backgroundIntensity:_b,backgroundRotation:vb,batch:wh,bentNormalView:vc,billboarding:Ly,bitAnd:Pa,bitNot:Ba,bitOr:La,bitXor:Fa,bitangentGeometry:fc,bitangentLocal:yc,bitangentView:bc,bitangentWorld:xc,bitcast:xy,blendBurn:yp,blendColor:_p,blendDodge:bp,blendOverlay:Tp,blendScreen:xp,blur:mm,bool:nn,buffer:gl,bufferAttribute:Fu,builtin:bl,bumpMap:wc,burn:(...e)=>(console.warn('THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.'),yp(e)),bvec2:ln,bvec3:pn,bvec4:yn,bypass:Hu,cache:zu,call:pa,cameraFar:Ll,cameraIndex:Pl,cameraNear:Bl,cameraNormalMatrix:Vl,cameraPosition:Ol,cameraProjectionMatrix:Fl,cameraProjectionMatrixInverse:Il,cameraViewMatrix:Dl,cameraViewport:Gl,cameraWorldMatrix:Ul,cbrt:zo,cdl:Ob,ceil:io,checker:o_,cineonToneMapping:Kb,clamp:Wo,clearcoat:Mn,clearcoatNormalView:Rd,clearcoatRoughness:Pn,code:ix,color:en,colorSpaceToWorking:Eu,colorToDirection:e=>Gi(e).mul(2).sub(1),compute:Gu,computeKernel:Ou,computeSkinning:(e,t=null)=>{const r=new Fh(e);return r.positionNode=Bh(new L(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(bh).toVar(),r.skinIndexNode=Bh(new L(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(bh).toVar(),r.skinWeightNode=Bh(new L(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(bh).toVar(),r.bindMatrixNode=oa(e.bindMatrix,"mat4"),r.bindMatrixInverseNode=oa(e.bindMatrixInverse,"mat4"),r.boneMatricesNode=gl(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),r.toPositionNode=t,Gi(r)},context:au,convert:vn,convertColorSpace:(e,t,r)=>Gi(new Nu(Gi(e),t,r)),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():ab(e,...t),cos:uo,cross:Do,cubeTexture:Hd,cubeTextureBase:$d,cubeToUV:XT,dFdx:xo,dFdy:To,dashSize:Wn,debug:el,decrement:Ga,decrementBefore:Va,defaultBuildStages:Ws,defaultShaderStages:Hs,defined:Ui,degrees:Ya,deltaTime:Cy,densityFog:function(e,t){return console.warn('THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.'),yx(e,fx(t))},densityFogFactor:fx,depth:up,depthPass:(e,t,r)=>Gi(new Wb(Wb.DEPTH,e,t,r)),determinant:Ro,difference:Fo,diffuseColor:Rn,directPointLight:n_,directionToColor:Fp,directionToFaceDirection:bd,dispersion:Jn,distance:Lo,div:xa,dodge:(...e)=>(console.warn('THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.'),bp(e)),dot:Io,drawIndex:vh,dynamicBufferAttribute:Iu,element:_n,emissive:An,equal:_a,equals:wo,equirectUV:Up,exp:Qa,exp2:Za,expression:Ku,faceDirection:yd,faceForward:Ko,faceforward:tu,float:tn,floatBitsToInt:e=>new by(e,"int","float"),floatBitsToUint:e=>new by(e,"uint","float"),floor:so,fog:yx,fract:ao,frameGroup:sa,frameId:My,frontFacing:fd,fwidth:So,gain:(e,t)=>e.lessThan(.5)?_y(e.mul(2),t).div(2):ya(1,_y(ba(ya(1,e),2),t).div(2)),gapSize:qn,getConstNodeType:Vi,getCurrentStack:Qi,getDirection:cm,getDistanceAttenuation:i_,getGeometryRoughness:ng,getNormalFromDepth:lb,getParallaxCorrectNormal:tv,getRoughness:ag,getScreenPosition:ub,getShIrradianceAt:rv,getShadowMaterial:DT,getShadowRenderObjectFunction:OT,getTextureIndex:my,getViewPosition:ob,globalId:Rx,glsl:(e,t)=>ix(e,t,"glsl"),glslFn:(e,t)=>ax(e,t,"glsl"),grayscale:Fb,greaterThan:Sa,greaterThanEqual:Ra,hash:Ty,highpModelNormalViewMatrix:od,highpModelViewMatrix:ad,hue:Ub,increment:Oa,incrementBefore:Ua,instance:Sh,instanceIndex:bh,instancedArray:(e,t="float")=>{let r,s;!0===t.isStruct?(r=t.layout.getLength(),s=Ms("float")):(r=Ps(t),s=Ms(t));const i=new pb(e,r,s);return Bh(i,t,e)},instancedBufferAttribute:Du,instancedDynamicBufferAttribute:Uu,instancedMesh:Rh,int:rn,intBitsToFloat:e=>new by(e,"float","int"),inverse:Ao,inverseSqrt:ro,inversesqrt:ru,invocationLocalIndex:_h,invocationSubgroupIndex:Th,ior:Xn,iridescence:Fn,iridescenceIOR:In,iridescenceThickness:Dn,ivec2:on,ivec3:cn,ivec4:mn,js:(e,t)=>ix(e,t,"js"),label:lu,length:fo,lengthSq:$o,lessThan:Na,lessThanEqual:Ea,lightPosition:cT,lightProjectionUV:dT,lightShadowMatrix:lT,lightTargetDirection:gT,lightTargetPosition:hT,lightViewPosition:pT,lightingContext:jh,lights:(e=[])=>Gi(new bT).setLights(e),linearDepth:lp,linearToneMapping:jb,localId:Ax,log:Ja,log2:eo,logarithmicDepthToViewZ:(e,t,r)=>{const s=e.mul(Ja(r.div(t)));return tn(Math.E).pow(s).mul(t).negate()},luminance:Vb,mat2:bn,mat3:xn,mat4:Tn,matcapUV:rf,materialAO:ph,materialAlphaTest:Pc,materialAnisotropy:Yc,materialAnisotropyVector:gh,materialAttenuationColor:ih,materialAttenuationDistance:sh,materialClearcoat:Hc,materialClearcoatNormal:qc,materialClearcoatRoughness:Wc,materialColor:Bc,materialDispersion:ch,materialEmissive:Fc,materialEnvIntensity:Id,materialEnvRotation:Dd,materialIOR:rh,materialIridescence:Qc,materialIridescenceIOR:Zc,materialIridescenceThickness:Jc,materialLightMap:hh,materialLineDashOffset:lh,materialLineDashSize:ah,materialLineGapSize:oh,materialLineScale:nh,materialLineWidth:uh,materialMetalness:zc,materialNormal:$c,materialOpacity:Ic,materialPointSize:dh,materialReference:Yd,materialReflectivity:Gc,materialRefractionRatio:Fd,materialRotation:jc,materialRoughness:kc,materialSheen:Xc,materialSheenRoughness:Kc,materialShininess:Lc,materialSpecular:Dc,materialSpecularColor:Vc,materialSpecularIntensity:Uc,materialSpecularStrength:Oc,materialThickness:th,materialTransmission:eh,max:Mo,maxMipLevel:ol,mediumpModelViewMatrix:nd,metalness:Cn,min:Co,mix:Ho,mixElement:Qo,mod:Ta,modInt:ka,modelDirection:Yl,modelNormalMatrix:rd,modelPosition:Zl,modelRadius:td,modelScale:Jl,modelViewMatrix:id,modelViewPosition:ed,modelViewProjection:mh,modelWorldMatrix:Ql,modelWorldMatrixInverse:sd,morphReference:$h,mrt:yy,mul:ba,mx_aastep:Z_,mx_add:(e,t=tn(0))=>fa(e,t),mx_atan2:(e=tn(0),t=tn(1))=>po(e,t),mx_cell_noise_float:(e=sl())=>F_(e.convert("vec2|vec3")),mx_contrast:(e,t=1,r=.5)=>tn(e).sub(r).mul(t).add(r),mx_divide:(e,t=tn(1))=>xa(e,t),mx_fractal_noise_float:(e=sl(),t=3,r=2,s=.5,i=1)=>D_(e,rn(t),r,s).mul(i),mx_fractal_noise_vec2:(e=sl(),t=3,r=2,s=.5,i=1)=>V_(e,rn(t),r,s).mul(i),mx_fractal_noise_vec3:(e=sl(),t=3,r=2,s=.5,i=1)=>U_(e,rn(t),r,s).mul(i),mx_fractal_noise_vec4:(e=sl(),t=3,r=2,s=.5,i=1)=>O_(e,rn(t),r,s).mul(i),mx_frame:()=>My,mx_heighttonormal:(e,t)=>(e=dn(e),t=tn(t),wc(e,t)),mx_hsvtorgb:K_,mx_ifequal:(e,t,r,s)=>e.equal(t).mix(r,s),mx_ifgreater:(e,t,r,s)=>e.greaterThan(t).mix(r,s),mx_ifgreatereq:(e,t,r,s)=>e.greaterThanEqual(t).mix(r,s),mx_invert:(e,t=tn(1))=>ya(t,e),mx_modulo:(e,t=tn(1))=>Ta(e,t),mx_multiply:(e,t=tn(1))=>ba(e,t),mx_noise_float:(e=sl(),t=1,r=0)=>B_(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec3:(e=sl(),t=1,r=0)=>L_(e.convert("vec2|vec3")).mul(t).add(r),mx_noise_vec4:(e=sl(),t=1,r=0)=>{e=e.convert("vec2|vec3");return gn(L_(e),B_(e.add(an(19,73)))).mul(t).add(r)},mx_place2d:(e,t=an(.5,.5),r=an(1,1),s=tn(0),i=an(0,0))=>{let n=e;if(t&&(n=n.sub(t)),r&&(n=n.mul(r)),s){const e=s.mul(Math.PI/180),t=e.cos(),r=e.sin();n=an(n.x.mul(t).sub(n.y.mul(r)),n.x.mul(r).add(n.y.mul(t)))}return t&&(n=n.add(t)),i&&(n=n.add(i)),n},mx_power:(e,t=tn(1))=>Uo(e,t),mx_ramp4:(e,t,r,s,i=sl())=>{const n=i.x.clamp(),a=i.y.clamp(),o=Ho(e,t,n),u=Ho(r,s,n);return Ho(o,u,a)},mx_ramplr:(e,t,r=sl())=>J_(e,t,r,"x"),mx_ramptb:(e,t,r=sl())=>J_(e,t,r,"y"),mx_rgbtohsv:Y_,mx_rotate2d:(e,t)=>{e=an(e);const r=(t=tn(t)).mul(Math.PI/180);return of(e,r)},mx_rotate3d:(e,t,r)=>{e=dn(e),t=tn(t),r=dn(r);const s=t.mul(Math.PI/180),i=r.normalize(),n=s.cos(),a=s.sin(),o=tn(1).sub(n);return e.mul(n).add(i.cross(e).mul(a)).add(i.mul(i.dot(e)).mul(o))},mx_safepower:(e,t=1)=>(e=tn(e)).abs().pow(t).mul(e.sign()),mx_separate:(e,t=null)=>{if("string"==typeof t){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},s=t.replace(/^out/,"").toLowerCase();if(void 0!==r[s])return e.element(r[s])}if("number"==typeof t)return e.element(t);if("string"==typeof t&&1===t.length){const r={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(void 0!==r[t])return e.element(r[t])}return e},mx_splitlr:(e,t,r,s=sl())=>ev(e,t,r,s,"x"),mx_splittb:(e,t,r,s=sl())=>ev(e,t,r,s,"y"),mx_srgb_texture_to_lin_rec709:Q_,mx_subtract:(e,t=tn(0))=>ya(e,t),mx_timer:()=>wy,mx_transform_uv:(e=1,t=0,r=sl())=>r.mul(e).add(t),mx_unifiednoise2d:(e,t=sl(),r=an(1,1),s=an(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>j_(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_unifiednoise3d:(e,t=sl(),r=an(1,1),s=an(0,0),i=1,n=0,a=1,o=!1,u=1,l=2,d=.5)=>X_(e,t.convert("vec2|vec3"),r,s,i,n,a,o,u,l,d),mx_worley_noise_float:(e=sl(),t=1)=>H_(e.convert("vec2|vec3"),t,rn(1)),mx_worley_noise_vec2:(e=sl(),t=1)=>W_(e.convert("vec2|vec3"),t,rn(1)),mx_worley_noise_vec3:(e=sl(),t=1)=>q_(e.convert("vec2|vec3"),t,rn(1)),negate:yo,neutralToneMapping:rx,nodeArray:$i,nodeImmutable:Wi,nodeObject:Gi,nodeObjectIntent:ki,nodeObjects:zi,nodeProxy:Hi,nodeProxyIntent:qi,normalFlat:_d,normalGeometry:xd,normalLocal:Td,normalMap:Sc,normalView:Sd,normalViewGeometry:vd,normalWorld:Ed,normalWorldGeometry:Nd,normalize:no,not:Ca,notEqual:va,numWorkgroups:Sx,objectDirection:$l,objectGroup:na,objectPosition:Wl,objectRadius:Xl,objectScale:ql,objectViewPosition:jl,objectWorldMatrix:Hl,oneMinus:bo,or:wa,orthographicDepthToViewZ:(e,t,r)=>t.sub(r).mul(e).sub(t),oscSawtooth:(e=wy)=>e.fract(),oscSine:(e=wy)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=wy)=>e.fract().round(),oscTriangle:(e=wy)=>e.add(.5).fract().mul(2).sub(1).abs(),output:Hn,outputStruct:gy,overlay:(...e)=>(console.warn('THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.'),Tp(e)),overloadingFn:Ay,parabola:_y,parallaxDirection:_c,parallaxUV:(e,t)=>e.sub(_c.mul(t)),parameter:(e,t)=>Gi(new uy(e,t)),pass:(e,t,r)=>Gi(new Wb(Wb.COLOR,e,t,r)),passTexture:(e,t)=>Gi(new $b(e,t)),pcurve:(e,t,r)=>Uo(xa(Uo(e,t),fa(Uo(e,t),Uo(ya(1,e),r))),1/t),perspectiveDepthToViewZ:np,pmremTexture:km,pointShadow:r_,pointUV:fb,pointWidth:jn,positionGeometry:ud,positionLocal:ld,positionPrevious:dd,positionView:pd,positionViewDirection:gd,positionWorld:cd,positionWorldDirection:hd,posterize:kb,pow:Uo,pow2:Vo,pow3:Oo,pow4:Go,premultiplyAlpha:vp,property:Sn,quadBroadcast:aT,quadSwapDiagonal:eT,quadSwapX:Zx,quadSwapY:Jx,radians:Ka,rand:Yo,range:_x,rangeFog:function(e,t,r){return console.warn('THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.'),yx(e,mx(t,r))},rangeFogFactor:mx,reciprocal:vo,reference:jd,referenceBuffer:Xd,reflect:Bo,reflectVector:Od,reflectView:Ud,reflector:e=>Gi(new Zy(e)),refract:jo,refractVector:Gd,refractView:Vd,reinhardToneMapping:Xb,remap:qu,remapClamp:ju,renderGroup:ia,renderOutput:Zu,rendererReference:Cu,rotate:of,rotateUV:Py,roughness:wn,round:_o,rtt:ab,sRGBTransferEOTF:Tu,sRGBTransferOETF:_u,sample:(e,t=null)=>Gi(new db(e,Gi(t))),sampler:e=>(!0===e.isNode?e:cl(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:cl(e)).convert("samplerComparison"),saturate:qo,saturation:Ib,screen:(...e)=>(console.warn('THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.'),xp(e)),screenCoordinate:El,screenDPR:vl,screenSize:Sl,screenUV:Nl,scriptable:px,scriptableValue:ux,select:iu,setCurrentStack:Yi,setName:uu,shaderStages:qs,shadow:qT,shadowPositionWorld:TT,shapeCircle:u_,sharedUniformGroup:ra,sheen:Bn,sheenRoughness:Ln,shiftLeft:Ia,shiftRight:Da,shininess:$n,sign:mo,sin:oo,sinc:(e,t)=>oo(Wa.mul(t.mul(e).sub(1))).div(Wa.mul(t.mul(e).sub(1))),skinning:Ih,smoothstep:Xo,smoothstepElement:Zo,specularColor:kn,specularF90:zn,spherizeUV:By,split:(e,t)=>Gi(new ri(Gi(e),t)),spritesheetUV:Dy,sqrt:to,stack:dy,step:Po,stepElement:Jo,storage:Bh,storageBarrier:()=>Cx("storage").toStack(),storageObject:(e,t,r)=>(console.warn('THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.'),Bh(e,t,r).setPBO(!0)),storageTexture:Sb,string:(e="")=>Gi(new oi(e,"string")),struct:(e,t=null)=>{const r=new cy(e,t),s=(...t)=>{let s=null;if(t.length>0)if(t[0].isNode){s={};const r=Object.keys(e);for(let e=0;eCx("texture").toStack(),textureBicubic:Ig,textureBicubicLevel:Fg,textureCubeUV:hm,textureLoad:hl,textureSize:nl,textureStore:(e,t,r)=>{const s=Sb(e,t,r);return null!==r&&s.toStack(),s},thickness:Yn,time:wy,toneMapping:Pu,toneMappingExposure:Bu,toonOutlinePass:(t,r,s=new e(0,0,0),i=.003,n=1)=>Gi(new qb(t,r,Gi(s),Gi(i),Gi(n))),transformDirection:ko,transformNormal:Ad,transformNormalToView:wd,transformedClearcoatNormalView:Pd,transformedNormalView:Cd,transformedNormalWorld:Md,transmission:Kn,transpose:Eo,triNoise3D:Sy,triplanarTexture:(...e)=>Uy(...e),triplanarTextures:Uy,trunc:No,uint:sn,uintBitsToFloat:e=>new by(e,"float","uint"),uniform:oa,uniformArray:yl,uniformCubeTexture:(e=kd)=>$d(e),uniformFlow:ou,uniformGroup:ta,uniformTexture:(e=ul)=>cl(e),unpremultiplyAlpha:Np,userData:(e,t,r)=>Gi(new wb(e,t,r)),uv:sl,uvec2:un,uvec3:hn,uvec4:fn,varying:bu,varyingProperty:En,vec2:an,vec3:dn,vec4:gn,vectorComponents:js,velocity:Lb,vertexColor:fp,vertexIndex:yh,vertexStage:xu,vibrance:Db,viewZToLogarithmicDepth:ap,viewZToOrthographicDepth:sp,viewZToPerspectiveDepth:ip,viewport:Rl,viewportCoordinate:wl,viewportDepthTexture:tp,viewportLinearDepth:dp,viewportMipTexture:Zh,viewportResolution:Ml,viewportSafeUV:Fy,viewportSharedTexture:Pp,viewportSize:Al,viewportTexture:Qh,viewportUV:Cl,wgsl:(e,t)=>ix(e,t,"wgsl"),wgslFn:(e,t)=>ax(e,t,"wgsl"),workgroupArray:(e,t)=>Gi(new Px("Workgroup",e,t)),workgroupBarrier:()=>Cx("workgroup").toStack(),workgroupId:Ex,workingToColorSpace:Su,xor:Ma});const iv=new oy;class nv extends wf{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,r){const s=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===i)s._clearColor.getRGB(iv),iv.a=s._clearColor.a;else if(!0===i.isColor)i.getRGB(iv),iv.a=1,n=!0;else if(!0===i.isNode){const o=this.get(e),u=i;iv.copy(s._clearColor);let l=o.backgroundMesh;if(void 0===l){const c=au(gn(u).mul(_b),{getUV:()=>vb.mul(Nd),getTextureLevel:()=>Tb});let h=mh;h=h.setZ(h.w);const p=new Sp;function g(){i.removeEventListener("dispose",g),l.material.dispose(),l.geometry.dispose()}p.name="Background.material",p.side=S,p.depthTest=!1,p.depthWrite=!1,p.allowOverride=!1,p.fog=!1,p.lights=!1,p.vertexNode=h,p.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=l=new X(new Ge(1,32,32),p),l.frustumCulled=!1,l.name="Background.mesh",l.onBeforeRender=function(e,t,r){this.matrixWorld.copyPosition(r.matrixWorld)},i.addEventListener("dispose",g)}const d=u.getCacheKey();o.backgroundCacheKey!==d&&(o.backgroundMeshNode.node=gn(u).mul(_b),o.backgroundMeshNode.needsUpdate=!0,l.material.needsUpdate=!0,o.backgroundCacheKey=d),t.unshift(l,l.geometry,l.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",i);const a=s.xr.getEnvironmentBlendMode();if("additive"===a?iv.set(0,0,0,1):"alpha-blend"===a&&iv.set(0,0,0,0),!0===s.autoClear||!0===n){const m=r.clearColorValue;m.r=iv.r,m.g=iv.g,m.b=iv.b,m.a=iv.a,!0!==s.backend.isWebGLBackend&&!0!==s.alpha||(m.r*=m.a,m.g*=m.a,m.b*=m.a),r.depthClearValue=s._clearDepth,r.stencilClearValue=s._clearStencil,r.clearColor=!0===s.autoClearColor,r.clearDepth=!0===s.autoClearDepth,r.clearStencil=!0===s.autoClearStencil}else r.clearColor=!1,r.clearDepth=!1,r.clearStencil=!1}}let av=0;class ov{constructor(e="",t=[],r=0,s=[]){this.name=e,this.bindings=t,this.index=r,this.bindingsReference=s,this.id=av++}}class uv{constructor(e,t,r,s,i,n,a,o,u,l=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=r,this.transforms=l,this.nodeAttributes=s,this.bindings=i,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=u,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const r=new ov(t.name,[],t.index,t.bindingsReference);e.push(r);for(const e of t.bindings)r.bindings.push(e.clone())}else e.push(t)}return e}}class lv{constructor(e,t,r=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=r}}class dv{constructor(e,t,r){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=r}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class cv{constructor(e,t,r=!1,s=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=r,this.count=s}}class hv extends cv{constructor(e,t,r=null,s=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=r,this.interpolationSampling=s}}class pv{constructor(e,t,r=""){this.name=e,this.type=t,this.code=r,Object.defineProperty(this,"isNodeCode",{value:!0})}}let gv=0;class mv{constructor(e=null){this.id=gv++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class fv{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class yv{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class bv extends yv{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class xv extends yv{constructor(e,r=new t){super(e,r),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class Tv extends yv{constructor(e,t=new r){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class _v extends yv{constructor(e,t=new s){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class vv extends yv{constructor(t,r=new e){super(t,r),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class Nv extends yv{constructor(e,t=new i){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class Sv extends yv{constructor(e,t=new n){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class Ev extends yv{constructor(e,t=new a){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Rv extends bv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Av extends xv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class wv extends Tv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Cv extends _v{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Mv extends vv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Pv extends Nv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Bv extends Sv{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Lv extends Ev{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const Fv=new WeakMap,Iv=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Dv=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class Uv{constructor(e,t,r){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=r,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=dy(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new mv,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.currentStack=null,this.subBuildFn=null}getBindGroupsCache(){let e=Fv.get(this.renderer);return void 0===e&&(e=new Nf,Fv.set(this.renderer,e)),e}createRenderTarget(e,t,r){return new ue(e,t,r)}createCubeRenderTarget(e,t){return new Vp(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const r=this.getBindGroupsCache(),s=[];let i,n=!0;for(const e of t)s.push(e),n=n&&!0!==e.groupNode.shared;return n?(i=r.get(s),void 0===i&&(i=new ov(e,s,this.bindingsIndexes[e].group,s),r.set(s,i))):i=new ov(e,s,this.bindingsIndexes[e].group,s),i}getBindGroupArray(e,t){const r=this.bindings[t];let s=r[e];return void 0===s&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),r[e]=s=[]),s}getBindings(){let e=this.bindGroups;if(null===e){const t={},r=this.bindings;for(const e of qs)for(const s in r[e]){const i=r[e][s];(t[s]||(t[s]=[])).push(...i)}e=[];for(const r in t){const s=t[r],i=this._getBindGroup(r,s);e.push(i)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t=0?`${Math.round(n)}u`:"0u";if("bool"===i)return n?"true":"false";if("color"===i)return`${this.getType("vec3")}( ${Dv(n.r)}, ${Dv(n.g)}, ${Dv(n.b)} )`;const a=this.getTypeLength(i),o=this.getComponentType(i),u=e=>this.generateConst(o,e);if(2===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)} )`;if(3===a)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)} )`;if(4===a&&"mat2"!==i)return`${this.getType(i)}( ${u(n.x)}, ${u(n.y)}, ${u(n.z)}, ${u(n.w)} )`;if(a>=4&&n&&(n.isMatrix2||n.isMatrix3||n.isMatrix4))return`${this.getType(i)}( ${n.elements.map(u).join(", ")} )`;if(a>4)return`${this.getType(i)}()`;throw new Error(`NodeBuilder: Type '${i}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const r=this.attributes;for(const t of r)if(t.name===e)return t;const s=new lv(e,t);return this.registerDeclaration(s),r.push(s),s}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===_)return"int";if(t===T)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let r=Cs(e);const s="float"===t?"":t[0];return!0===/mat2/.test(t)&&(r=r.replace("vec","mat")),s+r}getTypeFromArray(e){return Iv.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const r=t.array,s=e.itemSize,i=e.normalized;let n;return e instanceof $e||!0===i||(n=this.getTypeFromArray(r)),this.getTypeFromLength(s,n)}getTypeLength(e){const t=this.getVectorType(e),r=/vec([2-4])/.exec(t);return null!==r?Number(r[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}addStack(){this.stack=dy(this.stack);const e=Qi();return this.stacks.push(e),Yi(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Yi(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,r=null){let s=(r=null===r?e.isGlobal(this)?this.globalCache:this.cache:r).getData(e);void 0===s&&(s={},r.setData(e,s)),void 0===s[t]&&(s[t]={});let i=s[t];const n=s.any?s.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===i.subBuildsCache&&(i.subBuildsCache={}),i=i.subBuildsCache[a]||(i.subBuildsCache[a]={}),i.subBuilds=n),i}getNodeProperties(e,t="any"){const r=this.getDataFromNode(e,t);return r.properties||(r.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const r=this.getDataFromNode(e);let s=r.bufferAttribute;if(void 0===s){const i=this.uniforms.index++;s=new lv("nodeAttribute"+i,t,e),this.bufferAttributes.push(s),r.bufferAttribute=s}return s}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,r=null,s=this.shaderStage){const i=this.getDataFromNode(e,s,this.globalCache);let n=i.structType;if(void 0===n){const a=this.structs.index++;null===r&&(r="StructType"+a),n=new fv(r,t),this.structs[s].push(n),this.types[s][r]=e,i.structType=n}return n}getOutputStructTypeFromNode(e,t){const r=this.getStructTypeFromNode(e,t,"OutputType","fragment");return r.output=!0,r}getUniformFromNode(e,t,r=this.shaderStage,s=null){const i=this.getDataFromNode(e,r,this.globalCache);let n=i.uniform;if(void 0===n){const a=this.uniforms.index++;n=new dv(s||"nodeUniform"+a,t,e),this.uniforms[r].push(n),this.registerDeclaration(n),i.uniform=n}return n}getVarFromNode(e,t=null,r=e.getNodeType(this),s=this.shaderStage,i=!1){const n=this.getDataFromNode(e,s),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const u=i?"_const":"_var",l=this.vars[s]||(this.vars[s]=[]),d=this.vars[u]||(this.vars[u]=0);null===t&&(t=(i?"nodeConst":"nodeVar")+d,this.vars[u]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new cv(t,r,i,c),i||l.push(o),this.registerDeclaration(o),n[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,r=e.getNodeType(this),s=null,i=null){const n=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,u=e.length;null===t&&(t="nodeVarying"+u),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new hv(t,r,s,i),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,r=this.declarations[t]||(this.declarations[t]={}),s=this.getPropertyName(e);let i=1,n=s;for(;void 0!==r[n];)n=s+"_"+i++;i>1&&(e.name=n,console.warn(`THREE.TSL: Declaration name '${s}' of '${e.type}' already in use. Renamed to '${n}'.`)),r[n]=e}getCodeFromNode(e,t,r=this.shaderStage){const s=this.getDataFromNode(e);let i=s.code;if(void 0===i){const e=this.codes[r]||(this.codes[r]=[]),n=e.length;i=new pv("nodeCode"+n,t),e.push(i),s.code=i}return i}addFlowCodeHierarchy(e,t){const{flowCodes:r,flowCodeBlock:s}=this.getDataFromNode(e);let i=!0,n=t;for(;n;){if(!0===s.get(n)){i=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(i)for(const e of r)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,r){const s=this.getDataFromNode(e),i=s.flowCodes||(s.flowCodes=[]),n=s.flowCodeBlock||(s.flowCodeBlock=new WeakMap);i.push(t),n.set(r,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),r=this.flowChildNode(e,t);return this.flowsData.set(e,r),r}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new nx,r=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=r,t}flowShaderNode(e){const t=e.layout,r={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)r[e.name]=new uy(e.type,e.name);e.layout=null;const s=e.call(r),i=this.flowStagesNode(s,t.type);return e.layout=t,i}flowBuildStage(e,t,r=null){const s=this.getBuildStage();this.setBuildStage(t);const i=e.build(this,r);return this.setBuildStage(s),i}flowStagesNode(e,t=null){const r=this.flow,s=this.vars,i=this.declarations,n=this.cache,a=this.buildStage,o=this.stack,u={code:""};this.flow=u,this.vars={},this.declarations={},this.cache=new mv,this.stack=dy();for(const r of Ws)this.setBuildStage(r),u.result=e.build(this,t);return u.vars=this.getVars(this.shaderStage),this.flow=r,this.vars=s,this.declarations=i,this.cache=n,this.stack=o,this.setBuildStage(a),u}getFunctionOperator(){return null}buildFunctionCode(){console.warn("Abstract function.")}flowChildNode(e,t=null){const r=this.flow,s={code:""};return this.flow=s,s.result=e.build(this,t),this.flow=r,s}flowNodeFromShaderStage(e,t,r=null,s=null){const i=this.tab,n=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const u={...this.context};delete u.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=u;let l=null;if("generate"===this.buildStage){const i=this.flowChildNode(t,r);null!==s&&(i.code+=`${this.tab+s} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,l=i}else l=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=i,this.context=o,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,r=null){return`${null!==r?this.generateArrayDeclaration(e,r):this.getType(e)} ${t}`}getVars(e){let t="";const r=this.vars[e];if(void 0!==r)for(const e of r)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let r="";if(void 0!==t)for(const e of t)r+=e.code+"\n";return r}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){console.warn("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const r=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const s=t[e];if(r.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let r,s;return r=null!==t?this.getClosestSubBuild(t):this.subBuildFn,s=r?e?r+"_"+e:r:e,s}build(){const{object:e,material:t,renderer:r}=this;if(null!==t){let e=r.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new Sp),e.build(this)}else this.addFlow("compute",e);for(const e of Ws){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of qs){this.setShaderStage(t);const r=this.flowNodes[t];for(const t of r)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new Rv(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new Av(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new wv(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new Cv(e);if("color"===t)return new Mv(e);if("mat2"===t)return new Pv(e);if("mat3"===t)return new Bv(e);if("mat4"===t)return new Lv(e);throw new Error(`Uniform "${t}" not declared.`)}format(e,t,r){if((t=this.getVectorType(t))===(r=this.getVectorType(r))||null===r||this.isReference(r))return e;const s=this.getTypeLength(t),i=this.getTypeLength(r);return 16===s&&9===i?`${this.getType(r)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===s&&4===i?`${this.getType(r)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:s>4||i>4||0===i?e:s===i?`${this.getType(r)}( ${e} )`:s>i?(e="bool"===r?`all( ${e} )`:`${e}.${"xyz".slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),r)):4===i&&s>1?`${this.getType(r)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===s?`${this.getType(r)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===s&&i>1&&t!==this.getComponentType(r)&&(e=`${this.getType(this.getComponentType(r))}( ${e} )`),`${this.getType(r)}( ${e} )`)}getSignature(){return`// Three.js r${He} - Node System\n`}}class Vv{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let r=e.get(t);return void 0===r&&(r={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,r)),r}updateBeforeNode(e){const t=e.getUpdateBeforeType(),r=e.updateReference(this);if(t===ks.FRAME){const{frameMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(r,this.frameId)}else if(t===ks.RENDER){const{renderMap:t}=this._getMaps(this.updateBeforeMap,r);t.get(r)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(r,this.renderId)}else t===ks.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),r=e.updateReference(this);if(t===ks.FRAME){const{frameMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(r,this.frameId)}else if(t===ks.RENDER){const{renderMap:t}=this._getMaps(this.updateAfterMap,r);t.get(r)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(r,this.renderId)}else t===ks.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),r=e.updateReference(this);if(t===ks.FRAME){const{frameMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.frameId&&!1!==e.update(this)&&t.set(r,this.frameId)}else if(t===ks.RENDER){const{renderMap:t}=this._getMaps(this.updateMap,r);t.get(r)!==this.renderId&&!1!==e.update(this)&&t.set(r,this.renderId)}else t===ks.OBJECT&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class Ov{constructor(e,t,r=null,s="",i=!1){this.type=e,this.name=t,this.count=r,this.qualifier=s,this.isConst=i}}Ov.isNodeFunctionInput=!0;class Gv extends s_{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:gT(this.light),lightColor:e}}}const kv=new a,zv=new a;let $v=null;class Hv extends s_{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=oa(new r).setGroup(ia),this.halfWidth=oa(new r).setGroup(ia),this.updateType=ks.RENDER}update(e){super.update(e);const{light:t}=this,r=e.camera.matrixWorldInverse;zv.identity(),kv.copy(t.matrixWorld),kv.premultiply(r),zv.extractRotation(kv),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(zv),this.halfHeight.value.applyMatrix4(zv)}setupDirectRectArea(e){let t,r;e.isAvailable("float32Filterable")?(t=cl($v.LTC_FLOAT_1),r=cl($v.LTC_FLOAT_2)):(t=cl($v.LTC_HALF_1),r=cl($v.LTC_HALF_2));const{colorNode:s,light:i}=this;return{lightColor:s,lightPosition:pT(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:r}}static setLTC(e){$v=e}}class Wv extends s_{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=oa(0).setGroup(ia),this.penumbraCosNode=oa(0).setGroup(ia),this.cutoffDistanceNode=oa(0).setGroup(ia),this.decayExponentNode=oa(0).setGroup(ia),this.colorNode=oa(this.color).setGroup(ia)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:r,penumbraCosNode:s}=this;return Xo(r,s,t)}getLightCoord(e){const t=e.getNodeProperties(this);let r=t.projectionUV;return void 0===r&&(r=dT(this.light,e.context.positionWorld),t.projectionUV=r),r}setupDirect(e){const{colorNode:t,cutoffDistanceNode:r,decayExponentNode:s,light:i}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot(gT(i)),u=this.getSpotAttenuation(e,o),l=n.length(),d=i_({lightDistance:l,cutoffDistance:r,decayExponent:s});let c,h,p=t.mul(u).mul(d);if(i.colorNode?(h=this.getLightCoord(e),c=i.colorNode(h)):i.map&&(h=this.getLightCoord(e),c=cl(i.map,h.xy).onRenderUpdate(()=>i.map)),c){p=h.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:a}}}class qv extends Wv{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const r=this.light.iesMap;let s=null;if(r&&!0===r.isTexture){const e=t.acos().mul(1/Math.PI);s=cl(r,an(e,0),0).r}else s=super.getSpotAttenuation(t);return s}}const jv=Ki(([e,t])=>{const r=e.abs().sub(t);return fo(Mo(r,0)).add(Co(Mo(r.x,r.y),0))});class Xv extends Wv{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=tn(0),r=this.penumbraCosNode,s=lT(this.light).mul(e.context.positionWorld||cd);return Zi(s.w.greaterThan(0),()=>{const e=s.xyz.div(s.w),i=jv(e.xy.sub(an(.5)),an(.5)),n=xa(-1,ya(1,ho(r)).sub(1));t.assign(qo(i.mul(-2).mul(n)))}),t}}class Kv extends s_{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class Yv extends s_{static get type(){return"HemisphereLightNode"}constructor(t=null){super(t),this.lightPositionNode=cT(t),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=oa(new e).setGroup(ia)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:r,lightDirectionNode:s}=this,i=Ed.dot(s).mul(.5).add(.5),n=Ho(r,t,i);e.context.irradiance.addAssign(n)}}class Qv extends s_{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new r);this.lightProbe=yl(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=rv(Ed,this.lightProbe);e.context.irradiance.addAssign(t)}}class Zv{parseFunction(){console.warn("Abstract function.")}}class Jv{constructor(e,t,r="",s=""){this.type=e,this.inputs=t,this.name=r,this.precision=s}getCode(){console.warn("Abstract function.")}}Jv.isNodeFunction=!0;const eN=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,tN=/[a-z_0-9]+/gi,rN="#pragma main";class sN extends Jv{constructor(e){const{type:t,inputs:r,name:s,precision:i,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(rN),r=-1!==t?e.slice(t+12):e,s=r.match(eN);if(null!==s&&5===s.length){const i=s[4],n=[];let a=null;for(;null!==(a=tN.exec(i));)n.push(a);const o=[];let u=0;for(;u0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==r||s){const i=this.getCacheNode("background",r,()=>{if(!0===r.isCubeTexture||r.mapping===Z||r.mapping===J||r.mapping===he){if(e.backgroundBlurriness>0||r.mapping===he)return km(r);{let e;return e=!0===r.isCubeTexture?Hd(r):cl(r),$p(e)}}if(!0===r.isTexture)return cl(r,Nl.flipY()).setUpdateMatrix(!0);!0!==r.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",r)},s);t.backgroundNode=i,t.background=r,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,r,s=!1){const i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=i.get(t);return(void 0===n||s)&&(n=r(),i.set(t,n)),n}updateFog(e){const t=this.get(e),r=e.fog;if(r){if(t.fog!==r){const e=this.getCacheNode("fog",r,()=>{if(r.isFogExp2){const e=jd("color","color",r).setGroup(ia),t=jd("density","float",r).setGroup(ia);return yx(e,fx(t))}if(r.isFog){const e=jd("color","color",r).setGroup(ia),t=jd("near","float",r).setGroup(ia),s=jd("far","float",r).setGroup(ia);return yx(e,mx(t,s))}console.error("THREE.Renderer: Unsupported fog configuration.",r)});t.fogNode=e,t.fog=r}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),r=e.environment;if(r){if(t.environment!==r){const e=this.getCacheNode("environment",r,()=>!0===r.isCubeTexture?Hd(r):!0===r.isTexture?cl(r):void console.error("Nodes: Unsupported environment configuration.",r));t.environmentNode=e,t.environment=r}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,r=null,s=null,i=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=r,n.camera=s,n.material=i,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return nN.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,r=this.getOutputCacheKey(),s=e.isArrayTexture?Ab(e,dn(Nl,bl("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):cl(e,Nl).renderOutput(t.toneMapping,t.currentColorSpace);return nN.set(e,r),s}updateBefore(e){const t=e.getNodeBuilderState();for(const r of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(r)}updateAfter(e){const t=e.getNodeBuilderState();for(const r of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(r)}updateForCompute(e){const t=this.getNodeFrame(),r=this.getForCompute(e);for(const e of r.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),r=e.getNodeBuilderState();for(const e of r.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new Vv,this.nodeBuilderCache=new Map,this.cacheLib={}}}const lN=new Me;class dN{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new n,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,r){const s=e.length;for(let i=0;i0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,s,r);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new bN(i.framebufferWidth,i.framebufferHeight,{format:de,type:Ce,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===i.ignoreDepthValues,resolveStencilBuffer:!1===i.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const r=e.near,s=e.far,i=this._cameraXR,n=this._cameraL,a=this._cameraR;i.near=a.near=n.near=r,i.far=a.far=n.far=s,i.isMultiViewCamera=this._useMultiview,this._currentDepthNear===i.near&&this._currentDepthFar===i.far||(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),i.layers.mask=6|e.layers.mask,n.layers.mask=3&i.layers.mask,a.layers.mask=5&i.layers.mask;const o=e.parent,u=i.cameras;vN(i,o);for(let e=0;e=0&&(r[n]=null,t[n].disconnect(i))}for(let s=0;s=r.length){r.push(i),n=e;break}if(null===r[e]){r[e]=i,n=e;break}}if(-1===n)break}const a=t[n];a&&a.connect(i)}}function RN(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function AN(e,t){if(void 0===t)return;const r=this._cameraXR,i=this._renderer,n=i.backend,a=this._glBaseLayer,o=this.getReferenceSpace(),u=t.getViewerPose(o);if(this._xrFrame=t,null!==u){const e=u.views;null!==this._glBaseLayer&&n.setXRTarget(a.framebuffer);let t=!1;e.length!==r.cameras.length&&(r.cameras.length=0,t=!0);for(let i=0;i{await this.compileAsync(e,t);const s=this._renderLists.get(e,t),i=this._renderContexts.get(e,t,this._renderTarget),n=e.overrideMaterial||r.material,a=this._objects.get(r,n,e,t,s.lightsNode,i,i.clippingContext),{fragmentShader:o,vertexShader:u}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:u}}}}async init(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let r=this.backend;try{await r.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=r=this._getFallback(e),await r.init(this)}catch(e){return void t(e)}}this._nodes=new uN(this,r),this._animation=new vf(this._nodes,this.info),this._attributes=new Ff(r),this._background=new nv(this,this._nodes),this._geometries=new Uf(this._attributes,this.info),this._textures=new ay(this,r,this.info),this._pipelines=new Hf(r,this._nodes),this._bindings=new Wf(r,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Af(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Qf(this.lighting),this._bundles=new pN,this._renderContexts=new iy,this._animation.start(),this._initialized=!0,e(this)})),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,r=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const s=this._nodes.nodeFrame,i=s.renderId,n=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._compilationPromises,u=!0===e.isScene?e:wN;null===r&&(r=e);const l=this._renderTarget,d=this._renderContexts.get(r,t,l),c=this._activeMipmapLevel,h=[];this._currentRenderContext=d,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=h,s.renderId++,s.update(),d.depth=this.depth,d.stencil=this.stencil,d.clippingContext||(d.clippingContext=new dN),d.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,l);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,d.clippingContext),r!==e&&r.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)}),p.finish(),null!==l){this._textures.updateRenderTarget(l,c);const e=this._textures.get(l);d.textures=e.textures,d.depthTexture=e.depthTexture}else d.textures=null,d.depthTexture=null;this._background.update(u,p,d);const g=p.opaque,m=p.transparent,f=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&g.length>0&&this._renderObjects(g,t,u,y),!0===this.transparent&&m.length>0&&this._renderTransparents(m,f,t,u,y),s.renderId=i,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(h)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){!0===e?(this.overrideNodes.modelViewMatrix=ad,this.overrideNodes.modelNormalViewMatrix=od):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===ad&&this.overrideNodes.modelNormalViewMatrix===od}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,r){const{bundleGroup:s,camera:i,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(s,i),u=this.backend.get(o);void 0===u.renderContexts&&(u.renderContexts=new Set);const l=s.version!==u.version,d=!1===u.renderContexts.has(a)||l;if(u.renderContexts.add(a),d){this.backend.beginBundle(a),(void 0===u.renderObjects||l)&&(u.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:d,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,i,t,r),!0===this.transparent&&d.length>0&&this._renderTransparents(d,e,i,t,r),this._currentRenderBundle=null,this.backend.finishBundle(a,o),u.version=s.version}else{const{renderObjects:e}=u;for(let t=0,r=e.length;t>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=T,p.viewport=!1===p.viewportValue.equals(MN),p.scissorValue.copy(y).multiplyScalar(b).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(MN),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new dN),p.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,h);const _=t.isArrayCamera?BN:PN;t.isArrayCamera||(LN.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),_.setFromProjectionMatrix(LN,t.coordinateSystem,t.reversedDepth));const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v,p.clippingContext),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==h){this._textures.updateRenderTarget(h,c);const e=this._textures.get(h);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=h,p.depth=h.depthBuffer,p.stencil=h.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=CN.width,p.height=CN.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=d,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,p.scissorValue.max(FN.set(0,0,0,0)),p.scissorValue.x+p.scissorValue.width>p.width&&(p.scissorValue.width=Math.max(p.width-p.scissorValue.x,0)),p.scissorValue.y+p.scissorValue.height>p.height&&(p.scissorValue.height=Math.max(p.height-p.scissorValue.y,0)),this._background.update(u,v,p),p.camera=t,this.backend.beginRender(p);const{bundles:N,lightsNode:S,transparentDoublePass:E,transparent:R,opaque:A}=v;return N.length>0&&this._renderBundles(N,u,S),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,u,S),!0===this.transparent&&R.length>0&&this._renderTransparents(R,E,t,u,S),this.backend.finishRender(p),i.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==s&&(this.setRenderTarget(l,d,c),this._renderOutput(h)),u.onAfterRender(this,e,t,h),p}_setXRLayerSize(e,t){this._width=e,this._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const r=this.autoClear,s=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=r,this.xr.enabled=s}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,r){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=r,this.domElement.width=Math.floor(e*r),this.domElement.height=Math.floor(t*r),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setSize(e,t,r=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===r&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,r,s){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,r,s)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,r,s,i=0,n=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,r,s),a.minDepth=i,a.maxDepth=n}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,r=!0){if(!1===this._initialized)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,r);const s=this._renderTarget||this._getFrameBufferTarget();let i=null;if(null!==s){this._textures.updateRenderTarget(s);const e=this._textures.get(s);i=this._renderContexts.getForClear(s),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=s,i.depth=s.depthBuffer,i.stencil=s.stencilBuffer,i.clearColorValue=this.backend.getClearColor(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,r,i),null!==s&&null===this._renderTarget&&this._renderOutput(s)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,r=!0){!1===this._initialized&&await this.init(),this.clear(e,t,r)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:p}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:c.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){!0===this._initialized&&(this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,r=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=r}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const r=this._nodes.nodeFrame,s=r.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,r.renderId=this.info.calls;const i=this.backend,n=this._pipelines,a=this._bindings,o=this._nodes,u=Array.isArray(e)?e:[e];if(void 0===u[0]||!0!==u[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const r of u){if(!1===n.has(r)){const e=()=>{r.removeEventListener("dispose",e),n.delete(r),a.delete(r),o.delete(r)};r.addEventListener("dispose",e);const t=r.onInitFunction;null!==t&&t.call(r,{renderer:this})}o.updateForCompute(r),a.updateForCompute(r);const s=a.getForCompute(r),u=n.getForCompute(r,s);i.compute(e,r,s,u,t)}i.finishCompute(e),r.renderId=s}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=FN.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=FN.copy(t).floor()}else t=FN.set(0,0,e.image.width,e.image.height);let r,s=this._currentRenderContext;null!==s?r=s.renderTarget:(r=this._renderTarget||this._getFrameBufferTarget(),null!==r&&(this._textures.updateRenderTarget(r),s=this._textures.get(r))),this._textures.updateTexture(e,{renderTarget:r}),this.backend.copyFramebufferToTexture(e,s,t)}copyTextureToTexture(e,t,r=null,s=null,i=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,r,s,i,n)}async readRenderTargetPixelsAsync(e,t,r,s,i,n=0,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,r,s,i,a)}_projectObject(e,t,r,s,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)r=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)s.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?BN:PN;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&FN.setFromMatrixPosition(e.matrixWorld).applyMatrix4(LN);const{geometry:t,material:n}=e;n.visible&&s.push(e,t,n,r,FN.z,null,i)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?BN:PN;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),FN.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(LN)),Array.isArray(n)){const a=t.groups;for(let o=0,u=a.length;o0){for(const{material:e}of t)e.side=S;this._renderObjects(t,r,s,i,"backSide");for(const{material:e}of t)e.side=je;this._renderObjects(e,r,s,i);for(const{material:e}of t)e.side=E}else this._renderObjects(e,r,s,i)}_renderObjects(e,t,r,s,i=null){for(let n=0,a=e.length;n0,e.isShadowPassMaterial&&(e.side=null===i.shadowSide?i.side:i.shadowSide,i.depthNode&&i.depthNode.isNode&&(c=e.depthNode,e.depthNode=i.depthNode),i.castShadowNode&&i.castShadowNode.isNode&&(d=e.colorNode,e.colorNode=i.castShadowNode),i.castShadowPositionNode&&i.castShadowPositionNode.isNode&&(l=e.positionNode,e.positionNode=i.castShadowPositionNode)),i=e}!0===i.transparent&&i.side===E&&!1===i.forceSinglePass?(i.side=S,this._handleObjectFunction(e,i,t,r,a,n,o,"backSide"),i.side=je,this._handleObjectFunction(e,i,t,r,a,n,o,u),i.side=E):this._handleObjectFunction(e,i,t,r,a,n,o,u),void 0!==l&&(t.overrideMaterial.positionNode=l),void 0!==c&&(t.overrideMaterial.depthNode=c),void 0!==d&&(t.overrideMaterial.colorNode=d),e.onAfterRender(this,t,r,s,i,n)}_renderObjectDirect(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n;const l=this._nodes.needsRefresh(u);if(l&&(this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u)),this._pipelines.updateForRender(u),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(u),u.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(u,this.info),l&&this._nodes.updateAfter(u)}_createObjectPipeline(e,t,r,s,i,n,a,o){const u=this._objects.get(e,t,r,s,i,this._currentRenderContext,a,o);u.drawRange=e.geometry.drawRange,u.group=n,this._nodes.updateBefore(u),this._geometries.updateForRender(u),this._nodes.updateForRender(u),this._bindings.updateForRender(u),this._pipelines.getForRender(u,this._compilationPromises),this._nodes.updateAfter(u)}get compile(){return this.compileAsync}}class DN{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class UN extends DN{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(Lf-e%Lf)%Lf;var e}get buffer(){return this._buffer}update(){return!0}}class VN extends UN{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let ON=0;class GN extends VN{constructor(e,t){super("UniformBuffer_"+ON++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class kN extends VN{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let r=0,s=this.uniforms.length;r{this._texture=null,this.generation=null,this.version=0};this._texture&&this._texture.removeEventListener("dispose",t),this._texture=e,this.generation=null,this.version=0,this._texture&&this._texture.addEventListener("dispose",t)}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e.texture=this.texture,e}}let WN=0;class qN extends HN{constructor(e,t){super(e,t),this.id=WN++,this.store=!1,this.isSampledTexture=!0}}class jN extends qN{constructor(e,t,r,s=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r,this.access=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class XN extends jN{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledCubeTexture=!0}}class KN extends jN{constructor(e,t,r,s=null){super(e,t,r,s),this.isSampledTexture3D=!0}}const YN={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint"},QN={low:"lowp",medium:"mediump",high:"highp"},ZN={swizzleAssign:!0,storageBuffer:!1},JN={perspective:"smooth",linear:"noperspective"},eS={centroid:"centroid"},tS="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision lowp sampler2DShadow;\nprecision lowp sampler2DArrayShadow;\nprecision lowp samplerCubeShadow;\n";class rS extends Uv{constructor(e,t){super(e,t,new iN),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==b}getMethod(e){return YN[e]||e}getBitcastMethod(e,t){return YN[`bitcast_${t}_${e}`]}getTernary(e,t,r){return`${e} ? ${t} : ${r}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${s.join(", ")} ) {\n\n\t${r.vars}\n\n${r.code}\n\treturn ${r.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,r=t.count*t.itemSize,{itemSize:s}=t,i=t.array.constructor.name.toLowerCase().includes("int");let n=i?nt:at;2===s?n=i?dt:Ve:3===s?n=i?ct:ht:4===s&&(n=i?pt:de);const a={Float32Array:I,Uint8Array:Ce,Uint16Array:lt,Uint32Array:T,Int8Array:ut,Int16Array:ot,Int32Array:_,Uint8ClampedArray:Ce},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(r/s))));let u=Math.ceil(r/s/o);o*u*s0?s:"";t=`${e.name} {\n\t${r} ${i.name}[${n}];\n};\n`}else{t=`${this.getVectorType(i.type)} ${this.getPropertyName(i,e)};`,n=!0}const a=i.node.precision;if(null!==a&&(t=QN[a]+" "+t),n){t="\t"+t;const e=i.groupNode.name;(s[e]||(s[e]=[])).push(t)}else t="uniform "+t,r.push(t)}let i="";for(const t in s){const r=s[t];i+=this._getGLSLUniformStruct(e+"_"+t,r.join("\n"))+"\n"}return i+=r.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==_){let r=e;e.isInterleavedBufferAttribute&&(r=e.data);const s=r.array;!1==(s instanceof Uint32Array||s instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let r=0;for(const s of e)t+=`layout( location = ${r++} ) in ${s.type} ${s.name};\n`}return t}getStructMembers(e){const t=[];for(const r of e.members)t.push(`\t${r.type} ${r.name};`);return t.join("\n")}getStructs(e){const t=[],r=this.structs[e],s=[];for(const e of r)if(e.output)for(const t of e.members)s.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let r="struct "+e.name+" {\n";r+=this.getStructMembers(e),r+="\n};\n",t.push(r)}return 0===s.length&&s.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+s.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const r=this.varyings;if("vertex"===e||"compute"===e)for(const s of r){"compute"===e&&(s.needsInterpolation=!0);const r=this.getType(s.type);if(s.needsInterpolation)if(s.interpolationType){t+=`${JN[s.interpolationType]||s.interpolationType} ${eS[s.interpolationSampling]||""} out ${r} ${s.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}out ${r} ${s.name};\n`}else t+=`${r} ${s.name};\n`}else if("fragment"===e)for(const e of r)if(e.needsInterpolation){const r=this.getType(e.type);if(e.interpolationType){t+=`${JN[e.interpolationType]||e.interpolationType} ${eS[e.interpolationSampling]||""} in ${r} ${e.name};\n`}else{t+=`${r.includes("int")||r.includes("uv")||r.includes("iv")?"flat ":""}in ${r} ${e.name};\n`}}for(const r of this.builtins[e])t+=`${r};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,r=this.shaderStage){const s=this.extensions[r]||(this.extensions[r]=new Map);!1===s.has(e)&&s.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const r=this.extensions[e];if(void 0!==r)for(const{name:e,behavior:s}of r.values())t.push(`#extension ${e} : ${s}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=ZN[e];if(void 0===t){let r;switch(t=!1,e){case"float32Filterable":r="OES_texture_float_linear";break;case"clipDistance":r="WEBGL_clip_cull_distance"}if(void 0!==r){const e=this.renderer.backend.extensions;e.has(r)&&(e.get(r),t=!0)}ZN[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let r=0;r0&&(r+="\n"),r+=`\t// flow -> ${n}\n\t`),r+=`${s.code}\n\t`,e===i&&"compute"!==t&&(r+="// result\n\t","vertex"===t?(r+="gl_Position = ",r+=`${s.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(r+="fragColor = ",r+=`${s.result};`)))}const n=e[t];n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=r}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);let a=n.uniformGPU;if(void 0===a){const s=e.groupNode,o=s.name,u=this.getBindGroupArray(o,r);if("texture"===t)a=new jN(i.name,i.node,s),u.push(a);else if("cubeTexture"===t)a=new XN(i.name,i.node,s),u.push(a);else if("texture3D"===t)a=new KN(i.name,i.node,s),u.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,i.name=`buffer${e.id}`;const t=new GN(e,s);t.name=e.name,u.push(t),a=t}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let n=e[o];void 0===n&&(n=new $N(r+"_"+o,s),e[o]=n,u.push(n)),a=this.getNodeUniform(i,t),n.addUniform(a)}n.uniformGPU=a}return i}}let sS=null,iS=null;class nS{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}getTimestampUID(e){const t=this.get(e);let r=!0===e.isComputeNode?"c":"r";return r+=":"+t.frameCalls+":"+e.id,r}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Be("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void Be(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const r=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=r,r}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return sS=sS||new t,this.renderer.getDrawingBufferSize(sS)}setScissorTest(){}getClearColor(){const e=this.renderer;return iS=iS||new oy,e.getClearColor(iS),iS.getRGB(iS),iS}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:gt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${He} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let aS,oS,uS=0;class lS{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class dS{constructor(e){this.backend=e}createAttribute(e,t){const r=this.backend,{gl:s}=r,i=e.array,n=e.usage||s.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a);let u,l=o.bufferGPU;if(void 0===l&&(l=this._createBuffer(s,t,i,n),o.bufferGPU=l,o.bufferType=t,o.version=a.version),i instanceof Float32Array)u=s.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)u=s.HALF_FLOAT;else if(i instanceof Uint16Array)u=e.isFloat16BufferAttribute?s.HALF_FLOAT:s.UNSIGNED_SHORT;else if(i instanceof Int16Array)u=s.SHORT;else if(i instanceof Uint32Array)u=s.UNSIGNED_INT;else if(i instanceof Int32Array)u=s.INT;else if(i instanceof Int8Array)u=s.BYTE;else if(i instanceof Uint8Array)u=s.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);u=s.UNSIGNED_BYTE}let d={bufferGPU:l,bufferType:t,type:u,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===s.INT||u===s.UNSIGNED_INT||e.gpuType===_,id:uS++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(s,t,i,n);d=new lS(d,e)}r.set(e,d)}updateAttribute(e){const t=this.backend,{gl:r}=t,s=e.array,i=e.isInterleavedBufferAttribute?e.data:e,n=t.get(i),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(r.bindBuffer(a,n.bufferGPU),0===o.length)r.bufferSubData(a,0,s);else{for(let e=0,t=o.length;e1?this.enable(s.SAMPLE_ALPHA_TO_COVERAGE):this.disable(s.SAMPLE_ALPHA_TO_COVERAGE),r>0&&this.currentClippingPlanes!==r){const e=12288;for(let t=0;t<8;t++)t{!function i(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void s();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),r()):requestAnimationFrame(i)}()})}}let pS,gS,mS,fS=!1;class yS{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===fS&&(this._init(),fS=!0)}_init(){const e=this.gl;pS={[Sr]:e.REPEAT,[Nr]:e.CLAMP_TO_EDGE,[vr]:e.MIRRORED_REPEAT},gS={[v]:e.NEAREST,[Er]:e.NEAREST_MIPMAP_NEAREST,[ze]:e.NEAREST_MIPMAP_LINEAR,[Y]:e.LINEAR,[ke]:e.LINEAR_MIPMAP_NEAREST,[U]:e.LINEAR_MIPMAP_LINEAR},mS={[Br]:e.NEVER,[Pr]:e.ALWAYS,[Ue]:e.LESS,[Mr]:e.LEQUAL,[Cr]:e.EQUAL,[wr]:e.GEQUAL,[Ar]:e.GREATER,[Rr]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let r;return r=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,r}getInternalFormat(e,t,r,s,i=!1){const{gl:n,extensions:a}=this;if(null!==e){if(void 0!==n[e])return n[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===n.RED&&(r===n.FLOAT&&(o=n.R32F),r===n.HALF_FLOAT&&(o=n.R16F),r===n.UNSIGNED_BYTE&&(o=n.R8),r===n.UNSIGNED_SHORT&&(o=n.R16),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RED_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.R8UI),r===n.UNSIGNED_SHORT&&(o=n.R16UI),r===n.UNSIGNED_INT&&(o=n.R32UI),r===n.BYTE&&(o=n.R8I),r===n.SHORT&&(o=n.R16I),r===n.INT&&(o=n.R32I)),t===n.RG&&(r===n.FLOAT&&(o=n.RG32F),r===n.HALF_FLOAT&&(o=n.RG16F),r===n.UNSIGNED_BYTE&&(o=n.RG8),r===n.UNSIGNED_SHORT&&(o=n.RG16),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RG_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RG8UI),r===n.UNSIGNED_SHORT&&(o=n.RG16UI),r===n.UNSIGNED_INT&&(o=n.RG32UI),r===n.BYTE&&(o=n.RG8I),r===n.SHORT&&(o=n.RG16I),r===n.INT&&(o=n.RG32I)),t===n.RGB){const e=i?Lr:c.getTransfer(s);r===n.FLOAT&&(o=n.RGB32F),r===n.HALF_FLOAT&&(o=n.RGB16F),r===n.UNSIGNED_BYTE&&(o=n.RGB8),r===n.UNSIGNED_SHORT&&(o=n.RGB16),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8:n.RGB8),r===n.UNSIGNED_SHORT_5_6_5&&(o=n.RGB565),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGB4),r===n.UNSIGNED_INT_5_9_9_9_REV&&(o=n.RGB9_E5),r===n.UNSIGNED_INT_10F_11F_11F_REV&&(o=n.R11F_G11F_B10F)}if(t===n.RGB_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGB8UI),r===n.UNSIGNED_SHORT&&(o=n.RGB16UI),r===n.UNSIGNED_INT&&(o=n.RGB32UI),r===n.BYTE&&(o=n.RGB8I),r===n.SHORT&&(o=n.RGB16I),r===n.INT&&(o=n.RGB32I)),t===n.RGBA){const e=i?Lr:c.getTransfer(s);r===n.FLOAT&&(o=n.RGBA32F),r===n.HALF_FLOAT&&(o=n.RGBA16F),r===n.UNSIGNED_BYTE&&(o=n.RGBA8),r===n.UNSIGNED_SHORT&&(o=n.RGBA16),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I),r===n.UNSIGNED_BYTE&&(o=e===h?n.SRGB8_ALPHA8:n.RGBA8),r===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGBA4),r===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1)}return t===n.RGBA_INTEGER&&(r===n.UNSIGNED_BYTE&&(o=n.RGBA8UI),r===n.UNSIGNED_SHORT&&(o=n.RGBA16UI),r===n.UNSIGNED_INT&&(o=n.RGBA32UI),r===n.BYTE&&(o=n.RGBA8I),r===n.SHORT&&(o=n.RGBA16I),r===n.INT&&(o=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(r===n.UNSIGNED_SHORT&&(o=n.DEPTH_COMPONENT16),r===n.UNSIGNED_INT&&(o=n.DEPTH_COMPONENT24),r===n.FLOAT&&(o=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&r===n.UNSIGNED_INT_24_8&&(o=n.DEPTH24_STENCIL8),o!==n.R16F&&o!==n.R32F&&o!==n.RG16F&&o!==n.RG32F&&o!==n.RGBA16F&&o!==n.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:r,extensions:s,backend:i}=this,n=c.getPrimaries(c.workingColorSpace),a=t.colorSpace===b?null:c.getPrimaries(t.colorSpace),o=t.colorSpace===b||n===a?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,t.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,t.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),r.texParameteri(e,r.TEXTURE_WRAP_S,pS[t.wrapS]),r.texParameteri(e,r.TEXTURE_WRAP_T,pS[t.wrapT]),e!==r.TEXTURE_3D&&e!==r.TEXTURE_2D_ARRAY||t.isArrayTexture||r.texParameteri(e,r.TEXTURE_WRAP_R,pS[t.wrapR]),r.texParameteri(e,r.TEXTURE_MAG_FILTER,gS[t.magFilter]);const u=void 0!==t.mipmaps&&t.mipmaps.length>0,l=t.minFilter===Y&&u?U:t.minFilter;if(r.texParameteri(e,r.TEXTURE_MIN_FILTER,gS[l]),t.compareFunction&&(r.texParameteri(e,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(e,r.TEXTURE_COMPARE_FUNC,mS[t.compareFunction])),!0===s.has("EXT_texture_filter_anisotropic")){if(t.magFilter===v)return;if(t.minFilter!==ze&&t.minFilter!==U)return;if(t.type===I&&!1===s.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=s.get("EXT_texture_filter_anisotropic");r.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:r,defaultTextures:s}=this,i=this.getGLTextureType(e);let n=s[i];void 0===n&&(n=t.createTexture(),r.state.bindTexture(i,n),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),s[i]=n),r.set(e,{textureGPU:n,glTextureType:i,isDefault:!0})}createTexture(e,t){const{gl:r,backend:s}=this,{levels:i,width:n,height:a,depth:o}=t,u=s.utils.convert(e.format,e.colorSpace),l=s.utils.convert(e.type),d=this.getInternalFormat(e.internalFormat,u,l,e.colorSpace,e.isVideoTexture),c=r.createTexture(),h=this.getGLTextureType(e);s.state.bindTexture(h,c),this.setTextureParameters(h,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?r.texStorage3D(r.TEXTURE_2D_ARRAY,i,d,n,a,o):e.isData3DTexture?r.texStorage3D(r.TEXTURE_3D,i,d,n,a,o):e.isVideoTexture||r.texStorage2D(h,i,d,n,a),s.set(e,{textureGPU:c,glTextureType:h,glFormat:u,glType:l,glInternalFormat:d})}copyBufferToTexture(e,t){const{gl:r,backend:s}=this,{textureGPU:i,glTextureType:n,glFormat:a,glType:o}=s.get(t),{width:u,height:l}=t.source.data;r.bindBuffer(r.PIXEL_UNPACK_BUFFER,e),s.state.bindTexture(n,i),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.texSubImage2D(n,0,0,0,u,l,a,o,0),r.bindBuffer(r.PIXEL_UNPACK_BUFFER,null),s.state.unbindTexture()}updateTexture(e,t){const{gl:r}=this,{width:s,height:i}=t,{textureGPU:n,glTextureType:a,glFormat:o,glType:u,glInternalFormat:l}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const s=e.mipmaps,i=t.image;for(let t=0;t0){const t=Fr(s.width,s.height,e.format,e.type);for(const i of e.layerUpdates){const e=s.data.subarray(i*t/s.data.BYTES_PER_ELEMENT,(i+1)*t/s.data.BYTES_PER_ELEMENT);r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,i,s.width,s.height,1,o,u,e)}e.clearLayerUpdates()}else r.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,s.width,s.height,s.depth,o,u,s.data)}else if(e.isData3DTexture){const e=t.image;r.texSubImage3D(r.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,u,e.data)}else if(e.isVideoTexture)e.update(),r.texImage2D(a,0,l,o,u,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(d){const r=0!==a||0!==o;let d,h;if(!0===e.isDepthTexture?(d=s.DEPTH_BUFFER_BIT,h=s.DEPTH_ATTACHMENT,t.stencil&&(d|=s.STENCIL_BUFFER_BIT)):(d=s.COLOR_BUFFER_BIT,h=s.COLOR_ATTACHMENT0),r){const e=this.backend.get(t.renderTarget),r=e.framebuffers[t.getCacheKey()],h=e.msaaFrameBuffer;i.bindFramebuffer(s.DRAW_FRAMEBUFFER,r),i.bindFramebuffer(s.READ_FRAMEBUFFER,h);const p=c-o-l;s.blitFramebuffer(a,p,a+u,p+l,a,p,a+u,p+l,d,s.NEAREST),i.bindFramebuffer(s.READ_FRAMEBUFFER,r),i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,p,u,l),i.unbindTexture()}else{const e=s.createFramebuffer();i.bindFramebuffer(s.DRAW_FRAMEBUFFER,e),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,h,s.TEXTURE_2D,n,0),s.blitFramebuffer(0,0,u,l,0,0,u,l,d,s.NEAREST),s.deleteFramebuffer(e)}}else i.bindTexture(s.TEXTURE_2D,n),s.copyTexSubImage2D(s.TEXTURE_2D,0,0,0,a,c-l-o,u,l),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,r,s=!1){const{gl:i}=this,n=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:u,width:l,height:d}=n;if(i.bindRenderbuffer(i.RENDERBUFFER,e),o&&!u){let t=i.DEPTH_COMPONENT24;if(!0===s){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(i.RENDERBUFFER,n.samples,t,l,d)}else r>0?(a&&a.isDepthTexture&&a.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,r,t,l,d)):i.renderbufferStorage(i.RENDERBUFFER,t,l,d);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else o&&u&&(r>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,r,i.DEPTH24_STENCIL8,l,d):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,l,d),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,r,s,i,n){const{backend:a,gl:o}=this,{textureGPU:u,glFormat:l,glType:d}=this.backend.get(e),c=o.createFramebuffer();o.bindFramebuffer(o.READ_FRAMEBUFFER,c);const h=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,u,0);const p=this._getTypedArrayType(d),g=s*i*this._getBytesPerTexel(d,l),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,g,o.STREAM_READ),o.readPixels(t,r,s,i,l,d,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(g/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteFramebuffer(c),f}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:r}=this;let s=0;return e===r.UNSIGNED_BYTE&&(s=1),e!==r.UNSIGNED_SHORT_4_4_4_4&&e!==r.UNSIGNED_SHORT_5_5_5_1&&e!==r.UNSIGNED_SHORT_5_6_5&&e!==r.UNSIGNED_SHORT&&e!==r.HALF_FLOAT||(s=2),e!==r.UNSIGNED_INT&&e!==r.FLOAT||(s=4),t===r.RGBA?4*s:t===r.RGB?3*s:t===r.ALPHA?s:void 0}}function bS(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class xS{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class TS{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const r=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const _S={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class vS{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:r,mode:s,object:i,type:n,info:a,index:o}=this;0!==o?r.drawElements(s,t,n,e):r.drawArrays(s,e,t),a.update(i,t,1)}renderInstances(e,t,r){const{gl:s,mode:i,type:n,index:a,object:o,info:u}=this;0!==r&&(0!==a?s.drawElementsInstanced(i,t,n,e,r):s.drawArraysInstanced(i,e,t,r),u.update(o,t,r))}renderMultiDraw(e,t,r){const{extensions:s,mode:i,object:n,info:a}=this;if(0===r)return;const o=s.get("WEBGL_multi_draw");if(null===o)for(let s=0;sthis.maxQueries)return Be(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const r=this.queries[t];if(r)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,r),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){console.error("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){console.error("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=[];for(const[t,r]of this.queryStates)if("ended"===r){const r=this.queries[t];e.push(this.resolveQuery(r))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce((e,t)=>e+t,0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed)return void t(this.lastValue);let r,s=!1;const i=e=>{s||(s=!0,r&&(clearTimeout(r),r=null),t(e))},n=()=>{if(this.isDisposed)i(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void i(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(r=setTimeout(n,1));const s=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(s)/1e6)}catch(e){console.error("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class ES extends nS{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,r={antialias:e.samples>0,alpha:!0,depth:e.depth,stencil:e.stencil},s=void 0!==t.context?t.context:e.domElement.getContext("webgl2",r);function i(t){t.preventDefault();const r={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(r)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=s,this.extensions=new xS(this),this.capabilities=new TS(this),this.attributeUtils=new dS(this),this.textureUtils=new yS(this),this.bufferRenderer=new vS(this),this.state=new cS(this),this.utils=new hS(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return l}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,r=null){const s=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:s.RGBA8}),null!==r){const t=e.stencilBuffer?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:r,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new SS(this.gl,e,2048));const r=this.timestampQueryPool[e];null!==r.allocateQueriesForContext(t)&&r.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,r=this.get(e);if(r.frameCalls=this.renderer.info.render.frameCalls,e.viewport)this.updateViewport(e);else{const{width:e,height:r}=this.getDrawingBufferSize();t.viewport(0,0,e,r)}if(e.scissor){const{x:r,y:s,width:i,height:n}=e.scissorValue;t.scissor(r,e.height-n-s,i,n)}this.initTimestampQuery(Ir.RENDER,this.getTimestampUID(e)),r.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const s=e.occlusionQueryCount;s>0&&(r.currentOcclusionQueries=r.occlusionQueries,r.currentOcclusionQueryObjects=r.occlusionQueryObjects,r.lastOcclusionObject=null,r.occlusionQueries=new Array(s),r.occlusionQueryObjects=new Array(s),r.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:r}=this,s=this.get(e),i=s.previousContext;r.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>s.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e{let a=0;for(let t=0;t{t.isBatchedMesh?null!==t._multiDrawInstances?(Be("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),b.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?b.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):Be("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):T>1?b.renderInstances(_,x,T):b.render(_,x)};if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const r=this.get(e.camera),s=e.camera.cameras,i=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===r.indexesGPU||r.indexesGPU.length!==s.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let r=0,i=s.length;r{const i=this.parallel,n=()=>{r.getProgramParameter(a,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,s),t()):requestAnimationFrame(n)};n()});return void t.push(i)}this._completeCompile(e,s)}_handleSource(e,t){const r=e.split("\n"),s=[],i=Math.max(t-6,0),n=Math.min(t+6,r.length);for(let e=i;e":" "} ${i}: ${r[e]}`)}return s.join("\n")}_getShaderErrors(e,t,r){const s=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||"").trim();if(s&&""===i)return"";const n=/ERROR: 0:(\d+)/.exec(i);if(n){const s=parseInt(n[1]);return r.toUpperCase()+"\n\n"+i+"\n\n"+this._handleSource(e.getShaderSource(t),s)}return i}_logProgramError(e,t,r){if(this.renderer.debug.checkShaderErrors){const s=this.gl,i=(s.getProgramInfoLog(e)||"").trim();if(!1===s.getProgramParameter(e,s.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(s,e,r,t);else{const n=this._getShaderErrors(s,r,"vertex"),a=this._getShaderErrors(s,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(e,s.VALIDATE_STATUS)+"\n\nProgram Info Log: "+i+"\n"+n+"\n"+a)}else""!==i&&console.warn("THREE.WebGLProgram: Program Info Log:",i)}}_completeCompile(e,t){const{state:r,gl:s}=this,i=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=i;!1===s.getProgramParameter(n,s.LINK_STATUS)&&this._logProgramError(n,a,o),r.useProgram(n);const u=e.getBindings();this._setupBindings(u,n),this.set(t,{programGPU:n})}createComputePipeline(e,t){const{state:r,gl:s}=this,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:n}=e,a=s.createProgram(),o=this.get(i).shaderGPU,u=this.get(n).shaderGPU,l=n.transforms,d=[],c=[];for(let e=0;e_S[t]===e),r=this.extensions;for(let e=0;e1,h=!0===i.isXRRenderTarget,p=!0===h&&!0===i._hasExternalTextures;let g=n.msaaFrameBuffer,m=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(i),x=ey(e);let T;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),T=n.cubeFramebuffers[x]):h&&!1===p?T=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),T=n.framebuffers[x]),void 0===T){T=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,T);const s=e.textures,o=[];if(l){n.cubeFramebuffers[x]=T;const{textureGPU:e}=this.get(s[0]),r=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+r,e,i)}else{n.framebuffers[x]=T;for(let r=0;r0&&!1===b&&!i.multiview){if(void 0===g){const s=[];g=t.createFramebuffer(),r.bindFramebuffer(t.FRAMEBUFFER,g);const i=[],l=e.textures;for(let r=0;r0&&!1===this._useMultisampledExtension(s)){const n=i.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;s.resolveDepthBuffer&&(s.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),s.stencilBuffer&&s.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=i.msaaFrameBuffer,u=i.msaaRenderbuffers,l=e.textures,d=l.length>1;if(r.bindFramebuffer(t.READ_FRAMEBUFFER,o),r.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),d)for(let e=0;e0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const RS="point-list",AS="line-list",wS="line-strip",CS="triangle-list",MS="triangle-strip",PS="never",BS="less",LS="equal",FS="less-equal",IS="greater",DS="not-equal",US="greater-equal",VS="always",OS="store",GS="load",kS="clear",zS="ccw",$S="cw",HS="none",WS="back",qS="uint16",jS="uint32",XS="r8unorm",KS="r8snorm",YS="r8uint",QS="r8sint",ZS="r16uint",JS="r16sint",eE="r16float",tE="rg8unorm",rE="rg8snorm",sE="rg8uint",iE="rg8sint",nE="r32uint",aE="r32sint",oE="r32float",uE="rg16uint",lE="rg16sint",dE="rg16float",cE="rgba8unorm",hE="rgba8unorm-srgb",pE="rgba8snorm",gE="rgba8uint",mE="rgba8sint",fE="bgra8unorm",yE="bgra8unorm-srgb",bE="rgb9e5ufloat",xE="rgb10a2unorm",TE="rg11b10ufloat",_E="rg32uint",vE="rg32sint",NE="rg32float",SE="rgba16uint",EE="rgba16sint",RE="rgba16float",AE="rgba32uint",wE="rgba32sint",CE="rgba32float",ME="depth16unorm",PE="depth24plus",BE="depth24plus-stencil8",LE="depth32float",FE="depth32float-stencil8",IE="bc1-rgba-unorm",DE="bc1-rgba-unorm-srgb",UE="bc2-rgba-unorm",VE="bc2-rgba-unorm-srgb",OE="bc3-rgba-unorm",GE="bc3-rgba-unorm-srgb",kE="bc4-r-unorm",zE="bc4-r-snorm",$E="bc5-rg-unorm",HE="bc5-rg-snorm",WE="bc6h-rgb-ufloat",qE="bc6h-rgb-float",jE="bc7-rgba-unorm",XE="bc7-rgba-unorm-srgb",KE="etc2-rgb8unorm",YE="etc2-rgb8unorm-srgb",QE="etc2-rgb8a1unorm",ZE="etc2-rgb8a1unorm-srgb",JE="etc2-rgba8unorm",eR="etc2-rgba8unorm-srgb",tR="eac-r11unorm",rR="eac-r11snorm",sR="eac-rg11unorm",iR="eac-rg11snorm",nR="astc-4x4-unorm",aR="astc-4x4-unorm-srgb",oR="astc-5x4-unorm",uR="astc-5x4-unorm-srgb",lR="astc-5x5-unorm",dR="astc-5x5-unorm-srgb",cR="astc-6x5-unorm",hR="astc-6x5-unorm-srgb",pR="astc-6x6-unorm",gR="astc-6x6-unorm-srgb",mR="astc-8x5-unorm",fR="astc-8x5-unorm-srgb",yR="astc-8x6-unorm",bR="astc-8x6-unorm-srgb",xR="astc-8x8-unorm",TR="astc-8x8-unorm-srgb",_R="astc-10x5-unorm",vR="astc-10x5-unorm-srgb",NR="astc-10x6-unorm",SR="astc-10x6-unorm-srgb",ER="astc-10x8-unorm",RR="astc-10x8-unorm-srgb",AR="astc-10x10-unorm",wR="astc-10x10-unorm-srgb",CR="astc-12x10-unorm",MR="astc-12x10-unorm-srgb",PR="astc-12x12-unorm",BR="astc-12x12-unorm-srgb",LR="clamp-to-edge",FR="repeat",IR="mirror-repeat",DR="linear",UR="nearest",VR="zero",OR="one",GR="src",kR="one-minus-src",zR="src-alpha",$R="one-minus-src-alpha",HR="dst",WR="one-minus-dst",qR="dst-alpha",jR="one-minus-dst-alpha",XR="src-alpha-saturated",KR="constant",YR="one-minus-constant",QR="add",ZR="subtract",JR="reverse-subtract",eA="min",tA="max",rA=0,sA=15,iA="keep",nA="zero",aA="replace",oA="invert",uA="increment-clamp",lA="decrement-clamp",dA="increment-wrap",cA="decrement-wrap",hA="storage",pA="read-only-storage",gA="write-only",mA="read-only",fA="read-write",yA="non-filtering",bA="comparison",xA="float",TA="unfilterable-float",_A="depth",vA="sint",NA="uint",SA="2d",EA="3d",RA="2d",AA="2d-array",wA="cube",CA="3d",MA="all",PA="vertex",BA="instance",LA={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"};class FA extends HN{constructor(e,t,r){super(e,t?t.value:null),this.textureNode=t,this.groupNode=r}update(){this.texture=this.textureNode.value}}class IA extends UN{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let DA=0;class UA extends IA{constructor(e,t){super("StorageBuffer_"+DA++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:$s.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class VA extends wf{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:DR}),this.flipYSampler=e.createSampler({minFilter:UR}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4,\n\t@location( 0 ) vTex : vec2\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2, 4 >(\n\t\tvec2( -1.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 ),\n\t\tvec2( -1.0, -1.0 ),\n\t\tvec2( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2, 4 >(\n\t\tvec2( 0.0, 0.0 ),\n\t\tvec2( 1.0, 0.0 ),\n\t\tvec2( 0.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:MS,stripIndexFormat:jS},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:MS,stripIndexFormat:jS},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,r=0){const s=t.format,{width:i,height:n}=t.size,a=this.getTransferPipeline(s),o=this.getFlipYPipeline(s),u=this.device.createTexture({size:{width:i,height:n,depthOrArrayLayers:1},format:s,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:RA,baseArrayLayer:r}),d=u.createView({baseMipLevel:0,mipLevelCount:1,dimension:RA,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),h=(e,t,r)=>{const s=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:s,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:r,loadOp:kS,storeOp:OS,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,i),n.draw(4,1,0,0),n.end()};h(a,l,d),h(o,d,l),this.device.queue.submit([c.finish()]),u.destroy()}generateMipmaps(e,t,r=0){const s=this.get(e);void 0===s.useCount&&(s.useCount=0,s.layers=[]);const i=s.layers[r]||this._mipmapCreateBundles(e,t,r),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,i),this.device.queue.submit([n.finish()]),0!==s.useCount&&(s.layers[r]=i),s.useCount++}_mipmapCreateBundles(e,t,r){const s=this.getTransferPipeline(t.format),i=s.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:RA,baseArrayLayer:r});const a=[];for(let o=1;o0)for(let t=0,n=s.length;t0)for(let t=0,n=s.length;t0?e.width:r.size.width,l=a>0?e.height:r.size.height;o.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:t,mipLevel:a,origin:{x:0,y:0,z:s},premultipliedAlpha:n},{width:u,height:l,depthOrArrayLayers:1})}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new VA(this.backend.device)),e}_generateMipmaps(e,t,r=0){this._getPassUtils().generateMipmaps(e,t,r)}_flipY(e,t,r=0){this._getPassUtils().flipY(e,t,r)}_copyBufferToTexture(e,t,r,s,i,n=0,a=0){const o=this.backend.device,u=e.data,l=this._getBytesPerTexel(r.format),d=e.width*l;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:s}},u,{offset:e.width*e.height*l*n,bytesPerRow:d},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===i&&this._flipY(t,r,s)}_copyCompressedBufferToTexture(e,t,r){const s=this.backend.device,i=this._getBlockData(r.format),n=r.size.depthOrArrayLayers>1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,HA=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,WA={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class qA extends Jv{constructor(e){const{type:t,inputs:r,name:s,inputsCode:i,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match($A);if(null!==t&&4===t.length){const r=t[2],s=[];let i=null;for(;null!==(i=HA.exec(r));)s.push({name:i[1],type:i[2]});const n=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class jA extends Zv{parseFunction(e){return new qA(e)}}const XA="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},KA={[$s.READ_ONLY]:"read",[$s.WRITE_ONLY]:"write",[$s.READ_WRITE]:"read_write"},YA={[Sr]:"repeat",[Nr]:"clamp",[vr]:"mirror"},QA={vertex:XA?XA.VERTEX:1,fragment:XA?XA.FRAGMENT:2,compute:XA?XA.COMPUTE:4},ZA={instance:!0,swizzleAssign:!1,storageBuffer:!0},JA={"^^":"tsl_xor"},ew={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},tw={},rw={tsl_xor:new sx("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new sx("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new sx("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new sx("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new sx("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new sx("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new sx("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new sx("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new sx("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new sx("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new sx("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new sx("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new sx("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},sw={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast"};let iw="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(iw+="diagnostic( off, derivative_uniformity );\n");class nw extends Uv{constructor(e,t){super(e,t,new jA),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,r,s,i,n=this.shaderStage){return"fragment"===n?s?i?`textureSample( ${t}, ${t}_sampler, ${r}, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r}, ${s} )`:i?`textureSample( ${t}, ${t}_sampler, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${r} )`:this.generateTextureSampleLevel(e,t,r,"0",s)}generateTextureSampleLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s):this.generateTextureLod(e,t,r,i,n,s)}generateWrapFunction(e){const t=`tsl_coord_${YA[e.wrapS]}S_${YA[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let r=tw[t];if(void 0===r){const s=[],i=e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===Sr?(s.push(rw.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===Nr?(s.push(rw.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===vr?(s.push(rw.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",tw[t]=r=new sx(n,s)}return r.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,r){const s=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===s.dimensionsSnippet&&(s.dimensionsSnippet={});let i=s.dimensionsSnippet[r];if(void 0===s.dimensionsSnippet[r]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),u=o>1;a=e.isData3DTexture?"vec3":"vec2",n=u||e.isStorageTexture?t:`${t}${r?`, u32( ${r} )`:""}`,i=new du(new Xu(`textureDimensions( ${n} )`,a)),s.dimensionsSnippet[r]=i,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(s.arrayLayerCount=new du(new Xu(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(s.cubeFaceCount=new du(new Xu("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,r,s,i="0u"){this._include("biquadraticTexture");const n=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,i);return s&&(r=`${r} + vec2(${s}) / ${a}`),`tsl_biquadraticTexture( ${t}, ${n}( ${r} ), ${a}, u32( ${i} ) )`}generateTextureLod(e,t,r,s,i,n="0u"){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),u=e.isData3DTexture?"vec3":"vec2";i&&(r=`${r} + ${u}(${i}) / ${u}( ${o} )`);const l=`${u}( ${a}( ${r} ) * ${u}( ${o} ) )`;return this.generateTextureLoad(e,t,l,s,null,n)}generateTextureLoad(e,t,r,s,i,n="0u"){let a;return i&&(r=`${r} + ${i}`),s?a=`textureLoad( ${t}, ${r}, ${s}, u32( ${n} ) )`:(a=`textureLoad( ${t}, ${r}, u32( ${n} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,r,s,i){let n;return n=s?`textureStore( ${t}, ${r}, ${s}, ${i} )`:`textureStore( ${t}, ${r}, ${i} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===I||!1===this.isSampleCompare(e)&&e.minFilter===v&&e.magFilter===v||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,r,s,i,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,r,s,i,"0",n):this._generateTextureSample(e,t,r,s,i,n),a}generateTextureGrad(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return n?`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${r}, ${s[0]}, ${s[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${i}, ${s} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,r,s,i,n){return!1===this.isUnfilterable(e)?n?`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${r}, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,r,n,s):this.generateTextureLod(e,t,r,i,n,s)}generateTextureBias(e,t,r,s,i,n,a=this.shaderStage){if("fragment"===a)return n?`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${r}, ${s} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,r=e.type;return"texture"===r||"cubeTexture"===r||"storageTexture"===r||"texture3D"===r?t:"buffer"===r||"storageBuffer"===r||"indirectStorageBuffer"===r?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=JA[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(console.warn("WebGPURenderer: Atomic operations are only supported in compute shaders."),$s.READ_WRITE):$s.READ_ONLY:e.access}getStorageAccess(e,t){return KA[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,r,s=null){const i=super.getUniformFromNode(e,t,r,s),n=this.getDataFromNode(e,r,this.globalCache);if(void 0===n.uniformGPU){let a;const o=e.groupNode,u=o.name,l=this.getBindGroupArray(u,r);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let s=null;const n=this.getNodeAccess(e,r);if("texture"===t||"storageTexture"===t?s=!0===e.value.is3DTexture?new KN(i.name,i.node,o,n):new jN(i.name,i.node,o,n):"cubeTexture"===t?s=new XN(i.name,i.node,o,n):"texture3D"===t&&(s=new KN(i.name,i.node,o,n)),s.store=!0===e.isStorageTextureNode,s.setVisibility(QA[r]),!1===this.isUnfilterable(e.value)&&!1===s.store){const e=new FA(`${i.name}_sampler`,i.node,o);e.setVisibility(QA[r]),l.push(e,s),a=[e,s]}else l.push(s),a=[s]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=new("buffer"===t?GN:UA)(e,o);n.setVisibility(QA[r]),l.push(n),a=n,i.name=s||"NodeBuffer_"+i.id}else{const e=this.uniformGroups[r]||(this.uniformGroups[r]={});let s=e[u];void 0===s&&(s=new $N(u,o),s.setVisibility(QA[r]),e[u]=s,l.push(s)),a=this.getNodeUniform(i,t),s.addUniform(a)}n.uniformGPU=a}return i}getBuiltin(e,t,r,s=this.shaderStage){const i=this.builtins[s]||(this.builtins[s]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:r}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,r=this.flowShaderNode(e),s=[];for(const e of t.inputs)s.push(e.name+" : "+this.getType(e.type));let i=`fn ${t.name}( ${s.join(", ")} ) -> ${this.getType(t.type)} {\n${r.vars}\n${r.code}\n`;return r.result&&(i+=`\treturn ${r.result};\n`),i+="\n}\n",i}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],r=this.directives[e];if(void 0!==r)for(const e of r)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array`,"vertex")}getBuiltins(e){const t=[],r=this.builtins[e];if(void 0!==r)for(const{name:e,property:s,type:i}of r.values())t.push(`@builtin( ${e} ) ${s} : ${i}`);return t.join(",\n\t")}getScopedArray(e,t,r,s){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:r,bufferCount:s}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:r,bufferType:s,bufferCount:i}of this.scopedArrays.values()){const n=this.getType(s);t.push(`var<${r}> ${e}: array< ${n}, ${i} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const r=this.getAttributesArray();for(let e=0,s=r.length;e"),t.push(`\t${s+r.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const r=this.structs[e];if(r.length>0){const e=[];for(const t of r){let r=`struct ${t.name} {\n`;r+=this.getStructMembers(t),r+="\n};",e.push(r)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,r=null){let s=`var ${t} : `;return s+=null!==r?this.generateArrayDeclaration(e,r):this.getType(e),s}getVars(e){const t=[],r=this.vars[e];if(void 0!==r)for(const e of r)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const r=this.varyings,s=this.vars[e];for(let i=0;ir.value.itemSize;return s&&!i}getUniforms(e){const t=this.uniforms[e],r=[],s=[],i=[],n={};for(const i of t){const t=i.groupNode.name,a=this.bindingsIndexes[t];if("texture"===i.type||"cubeTexture"===i.type||"storageTexture"===i.type||"texture3D"===i.type){const t=i.node.value;let s;!1===this.isUnfilterable(t)&&!0!==i.node.isStorageTextureNode&&(this.isSampleCompare(t)?r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler_comparison;`):r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler;`));let n="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(n="_multisampled"),!0===t.isCubeTexture)s="texture_cube";else if(!0===t.isDepthTexture)s=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d`:`texture_depth${n}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===i.node.isStorageTextureNode){const r=zA(t),n=this.getStorageAccess(i.node,e),a=i.node.value.is3DTexture,o=i.node.value.isArrayTexture;s=`texture_storage_${a?"3d":"2d"+(o?"_array":"")}<${r}, ${n}>`}else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)s="texture_2d_array";else if(!0===t.is3DTexture||!0===t.isData3DTexture)s="texture_3d";else{s=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name} : ${s};`)}else if("buffer"===i.type||"storageBuffer"===i.type||"indirectStorageBuffer"===i.type){const t=i.node,r=this.getType(t.getNodeType(this)),n=t.bufferCount,o=n>0&&"buffer"===i.type?", "+n:"",u=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(i))s.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${u}> ${i.name} : ${r};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${r}>`:`${r}`}${o} >`;s.push(this._getWGSLStructBinding(i.name,e,u,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name;(n[t]||(n[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${i.name} : ${e}`)}}for(const e in n){const t=n[e];i.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=r.join("\n");return a+=s.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const r=e[t];r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.structs=this.getStructs(t),r.vars=this.getVars(t),r.codes=this.getCodes(t),r.directives=this.getDirectives(t),r.scopedArrays=this.getScopedArrays(t);let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],n=i[i.length-1],a=n.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),u=e.name;if(u&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${u}\n`),s+=`${i.code}\n\t`,e===n&&"compute"!==t)if(s+="// result\n\n\t","vertex"===t)s+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(o)r.returnType=a.getNodeType(this),r.structs+="var output : "+r.returnType+";",s+=`return ${i.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),r.returnType="OutputStruct",r.structs+=this._getWGSLStruct("OutputStruct",e),r.structs+="\nvar output : OutputStruct;",s+=`output.color = ${i.result};\n\n\treturn output;`}}r.flow=s}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let r;return null!==t&&(r=this._getWGSLMethod(e+"_"+t)),void 0===r&&(r=this._getWGSLMethod(e)),r||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getTernary(e,t,r){return`select( ${r}, ${t}, ${e} )`}getType(e){return ew[e]||e}isAvailable(e){let t=ZA[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),ZA[e]=t),t}_getWGSLMethod(e){return void 0!==rw[e]&&this._include(e),sw[e]}_include(e){const t=rw[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${iw}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[r,s,i]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${r}, ${s}, ${i} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${r} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${r} * numWorkgroups.x ) * ( ${s} * numWorkgroups.y );\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,r,s=0,i=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${s} ) @group( ${i} )\nvar<${r}> ${e} : ${n};`}}class aw{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=BE:e.depth&&(t=PE),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,r=e.getRenderTarget();t=r?r.samples:e.samples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const r=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:r?1:t,isMSAA:r}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?RS:e.isLineSegments||e.isMesh&&!0===t.wireframe?AS:e.isLine?wS:e.isMesh?CS:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===Ce)return fE;if(e===ce)return RE;throw new Error("Unsupported outputType")}}const ow=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&ow.set(Float16Array,["float16"]);const uw=new Map([[$e,["float16"]]]),lw=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class dw{constructor(e){this.backend=e}createAttribute(e,t){const r=this._getBufferAttribute(e),s=this.backend,i=s.get(r);let n=i.buffer;if(void 0===n){const a=s.device;let o=r.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e1&&(s.multisampled=!0,r.texture.isDepthTexture||(s.sampleType=TA)),r.texture.isDepthTexture)t.compatibilityMode&&null===r.texture.compareFunction?s.sampleType=TA:s.sampleType=_A;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const e=r.texture.type;e===_?s.sampleType=vA:e===T?s.sampleType=NA:e===I&&(this.backend.hasFeature("float32-filterable")?s.sampleType=xA:s.sampleType=TA)}r.isSampledCubeTexture?s.viewDimension=wA:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?s.viewDimension=AA:r.isSampledTexture3D&&(s.viewDimension=CA),e.texture=s}else if(r.isSampler){const s={};r.texture.isDepthTexture&&(null!==r.texture.compareFunction?s.type=bA:t.compatibilityMode&&(s.type=yA)),e.sampler=s}else console.error(`WebGPUBindingUtils: Unsupported binding "${r}".`);s.push(e)}return r.createBindGroupLayout({entries:s})}createBindings(e,t,r,s=0){const{backend:i,bindGroupLayoutCache:n}=this,a=i.get(e);let o,u=n.get(e.bindingsReference);void 0===u&&(u=this.createBindingsLayout(e),n.set(e.bindingsReference,u)),r>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[r]===s&&(o=a.groups[r])),void 0===o&&(o=this.createBindGroup(e,u),r>0&&(a.groups[r]=o,a.versions[r]=s)),a.group=o,a.layout=u}updateBinding(e){const t=this.backend,r=t.device,s=e.buffer,i=t.get(e).buffer;r.queue.writeBuffer(i,0,s,0)}createBindGroupIndex(e,t){const r=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0],n=r.createBuffer({label:"bindingCameraIndex_"+i,size:16,usage:s});r.queue.writeBuffer(n,0,e,0);const a=[{binding:0,resource:{buffer:n}}];return r.createBindGroup({label:"bindGroupCameraIndex_"+i,layout:t,entries:a})}createBindGroup(e,t){const r=this.backend,s=r.device;let i=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=r.get(t);if(void 0===e.buffer){const r=t.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=s.createBuffer({label:"bindingBuffer_"+t.name,size:r,usage:i});e.buffer=n}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=r.get(t);if(void 0===e.buffer){const s=t.attribute;e.buffer=r.get(s).buffer}n.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isSampledTexture){const e=r.get(t.texture);let a;if(void 0!==e.externalTexture)a=s.importExternalTexture({source:e.externalTexture});else{const r=t.store?1:e.texture.mipLevelCount;let s=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(s+=`-${e.texture.depthOrArrayLayers}`),s+=`-${r}`,a=e[s],void 0===a){const i=MA;let n;n=t.isSampledCubeTexture?wA:t.isSampledTexture3D?CA:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?AA:RA,a=e[s]=e.texture.createView({aspect:i,dimension:n,mipLevelCount:r})}}n.push({binding:i,resource:a})}else if(t.isSampler){const e=r.get(t.texture);n.push({binding:i,resource:e.sampler})}i++}return s.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}}class hw{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:r,material:s,geometry:i,pipeline:n}=e,{vertexProgram:a,fragmentProgram:o}=n,u=this.backend,l=u.device,d=u.utils,c=u.get(n),h=[];for(const t of e.getBindings()){const e=u.get(t);h.push(e.layout)}const p=u.attributeUtils.createShaderVertexBuffers(e);let g;s.blending===$||s.blending===G&&!1===s.transparent||(g=this._getBlending(s));let m={};!0===s.stencilWrite&&(m={compare:this._getStencilCompare(s),failOp:this._getStencilOperation(s.stencilFail),depthFailOp:this._getStencilOperation(s.stencilZFail),passOp:this._getStencilOperation(s.stencilZPass)});const f=this._getColorWriteMask(s),y=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e1},layout:l.createPipelineLayout({bindGroupLayouts:h})},E={},R=e.context.depth,A=e.context.stencil;if(!0!==R&&!0!==A||(!0===R&&(E.format=v,E.depthWriteEnabled=s.depthWrite,E.depthCompare=_),!0===A&&(E.stencilFront=m,E.stencilBack={},E.stencilReadMask=s.stencilFuncMask,E.stencilWriteMask=s.stencilWriteMask),!0===s.polygonOffset&&(E.depthBias=s.polygonOffsetUnits,E.depthBiasSlopeScale=s.polygonOffsetFactor,E.depthBiasClamp=0),S.depthStencil=E),null===t)c.pipeline=l.createRenderPipeline(S);else{const e=new Promise(e=>{l.createRenderPipelineAsync(S).then(t=>{c.pipeline=t,e()})});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const r=this.backend,{utils:s,device:i}=r,n=s.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:[s.getCurrentColorFormat(e)],depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(a)}createComputePipeline(e,t){const r=this.backend,s=r.device,i=r.get(e.computeProgram).module,n=r.get(e),a=[];for(const e of t){const t=r.get(e);a.push(t.layout)}n.pipeline=s.createComputePipeline({compute:i,layout:s.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,r;const s=e.blending,i=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(s===Xe){const s=null!==e.blendSrcAlpha?e.blendSrcAlpha:i,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,u=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},r={srcFactor:this._getBlendFactor(s),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(u)}}else{const i=(e,s,i,n)=>{t={srcFactor:e,dstFactor:s,operation:QR},r={srcFactor:i,dstFactor:n,operation:QR}};if(e.premultipliedAlpha)switch(s){case G:i(OR,$R,OR,$R);break;case Bt:i(OR,OR,OR,OR);break;case Pt:i(VR,kR,VR,OR);break;case Mt:i(HR,$R,VR,OR)}else switch(s){case G:i(zR,$R,OR,$R);break;case Bt:i(zR,OR,OR,OR);break;case Pt:console.error("THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Mt:console.error("THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==r)return{color:t,alpha:r};console.error("THREE.WebGPURenderer: Invalid blending: ",s)}_getBlendFactor(e){let t;switch(e){case Ye:t=VR;break;case Rt:t=OR;break;case Et:t=GR;break;case Tt:t=kR;break;case St:t=zR;break;case xt:t=$R;break;case vt:t=HR;break;case bt:t=WR;break;case _t:t=qR;break;case yt:t=jR;break;case Nt:t=XR;break;case 211:t=KR;break;case 212:t=YR;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const r=e.stencilFunc;switch(r){case $r:t=PS;break;case zr:t=VS;break;case kr:t=BS;break;case Gr:t=FS;break;case Or:t=LS;break;case Vr:t=US;break;case Ur:t=IS;break;case Dr:t=DS;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",r)}return t}_getStencilOperation(e){let t;switch(e){case Qr:t=iA;break;case Yr:t=nA;break;case Kr:t=aA;break;case Xr:t=oA;break;case jr:t=uA;break;case qr:t=lA;break;case Wr:t=dA;break;case Hr:t=cA;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Ke:t=QR;break;case ft:t=ZR;break;case mt:t=JR;break;case Jr:t=eA;break;case Zr:t=tA;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,r){const s={},i=this.backend.utils;s.topology=i.getPrimitiveTopology(e,r),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(s.stripIndexFormat=t.index.array instanceof Uint16Array?qS:jS);let n=r.side===S;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),s.frontFace=!0===n?$S:zS,s.cullMode=r.side===E?HS:WS,s}_getColorWriteMask(e){return!0===e.colorWrite?sA:rA}_getDepthCompare(e){let t;if(!1===e.depthTest)t=VS;else{const r=e.depthFunc;switch(r){case Gt:t=PS;break;case Ot:t=VS;break;case Vt:t=BS;break;case Ut:t=FS;break;case Dt:t=LS;break;case It:t=US;break;case Ft:t=IS;break;case Lt:t=DS;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",r)}}return t}}class pw extends NS{constructor(e,t,r=2048){super(r),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const s=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Be(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,r=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const s=this.device.createCommandEncoder();s.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),s.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,r);const i=s.finish();if(this.device.queue.submit([i]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,r),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,r));let a=0;for(const[,t]of e){const e=n[t],r=n[t+1];a+=Number(r-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class gw extends nS{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new aw(this),this.attributeUtils=new dw(this),this.bindingUtils=new cw(this),this.pipelineUtils=new hw(this),this.textureUtils=new kA(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let r;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},s="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===s)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(LA),n=[];for(const e of i)s.features.has(e)&&n.push(e);const a={requiredFeatures:n,requiredLimits:t.requiredLimits};r=await s.requestDevice(a)}else r=t.device;r.lost.then(t=>{const r={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(r)});const s=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=r,this.context=s;const i=t.alpha?"premultiplied":"opaque",n=c.getToneMappingMode(this.renderer.outputColorSpace);this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:n}}),this.trackTimestamp=this.trackTimestamp&&this.hasFeature(LA.TimestampQuery),this.updateSize()}get coordinateSystem(){return d}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const r=e.colorAttachments[0];this.renderer.samples>0?r.view=this.colorBuffer.createView():r.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const r=e.renderTarget,s=this.get(r);let i=s.descriptors;void 0!==i&&s.width===r.width&&s.height===r.height&&s.samples===r.samples||(i={},s.descriptors=i);const n=e.getCacheKey();let a=i[n];if(void 0===a){const t=e.textures,o=[];let u;const l=this._isRenderCameraDepthArray(e);for(let s=0;s1)if(!0===l){const t=e.camera.cameras;for(let e=0;e0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=r.createQuerySet({type:"occlusion",count:s,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(s),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:GS}),this.initTimestampQuery(Ir.RENDER,this.getTimestampUID(e),n),n.occlusionQuerySet=i;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let r=0;r0&&t.currentPass.executeBundles(t.renderBundles),r>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const s=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const r=[];for(let e=0;e0){const s=8*r;let i=this.occludedResolveCache.get(s);void 0===i&&(i=this.device.createBuffer({size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(s,i));const n=this.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,r,i,0),t.encoder.copyBufferToBuffer(i,0,n,0,s),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;ea&&(u[0]=Math.min(i,a),u[1]=Math.ceil(i/a)),n.dispatchSize=u}u=n.dispatchSize}else u=i;a.dispatchWorkgroups(u[0],u[1]||1,u[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:r,material:s,context:i,pipeline:n}=e,a=e.getBindings(),o=this.get(i),u=this.get(n).pipeline,l=e.getIndex(),d=null!==l,c=e.getDrawParameters();if(null===c)return;const h=(t,r)=>{this.pipelineUtils.setPipeline(t,u),r.pipeline=u;const n=r.bindingGroups;for(let e=0,r=a.length;e{if(h(s,i),!0===r.isBatchedMesh){const e=r._multiDrawStarts,i=r._multiDrawCounts,n=r._multiDrawCount,a=r._multiDrawInstances;null!==a&&Be("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o1?0:o;!0===d?s.drawIndexed(i[o],n,e[o]/l.array.BYTES_PER_ELEMENT,0,u):s.draw(i[o],n,e[o],u),t.update(r,i[o],n)}}else if(!0===d){const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndexedIndirect(e,0)}else s.drawIndexed(i,n,a,0,0);t.update(r,i,n)}else{const{vertexCount:i,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;s.drawIndirect(e,0)}else s.draw(i,n,a,0);t.update(r,i,n)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),s=e.camera.cameras,n=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==s.length){const e=this.get(n),r=[],i=new Uint32Array([0,0,0,0]);for(let t=0,n=s.length;t(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new ES(e)));super(new t(e),e),this.library=new yw,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}class xw extends ps{constructor(){super(),this.isBundleGroup=!0,this.type="BundleGroup",this.static=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}}class Tw{constructor(e,t=gn(0,0,1,1)){this.renderer=e,this.outputNode=t,this.outputColorTransform=!0,this.needsUpdate=!0;const r=new Sp;r.name="PostProcessing",this._quadMesh=new sb(r),this._context=null}render(){const e=this.renderer;this._update(),null!==this._context.onBeforePostProcessing&&this._context.onBeforePostProcessing();const t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=c.workingColorSpace;const s=e.xr.enabled;e.xr.enabled=!1,this._quadMesh.render(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r,null!==this._context.onAfterPostProcessing&&this._context.onAfterPostProcessing()}get context(){return this._context}dispose(){this._quadMesh.material.dispose()}_update(){if(!0===this.needsUpdate){const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace,s={postProcessing:this,onBeforePostProcessing:null,onAfterPostProcessing:null};let i=this.outputNode;!0===this.outputColorTransform?(i=i.context(s),i=Zu(i,t,r)):(s.toneMapping=t,s.outputColorSpace=r,i=i.context(s)),this._context=s,this._quadMesh.material.fragmentNode=i,this._quadMesh.material.needsUpdate=!0,this.needsUpdate=!1}}async renderAsync(){this._update(),null!==this._context.onBeforePostProcessing&&this._context.onBeforePostProcessing();const e=this.renderer,t=e.toneMapping,r=e.outputColorSpace;e.toneMapping=p,e.outputColorSpace=c.workingColorSpace;const s=e.xr.enabled;e.xr.enabled=!1,await this._quadMesh.renderAsync(e),e.xr.enabled=s,e.toneMapping=t,e.outputColorSpace=r,null!==this._context.onAfterPostProcessing&&this._context.onAfterPostProcessing()}}class _w extends x{constructor(e=1,t=1){super(),this.image={width:e,height:t},this.magFilter=Y,this.minFilter=Y,this.isStorageTexture=!0}setSize(e,t){this.image.width===e&&this.image.height===t||(this.image.width=e,this.image.height=t,this.dispose())}}class vw extends x{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!1,this.image={width:e,height:t,depth:r},this.magFilter=Y,this.minFilter=Y,this.wrapR=Nr,this.isStorageTexture=!0,this.is3DTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class Nw extends x{constructor(e=1,t=1,r=1){super(),this.isArrayTexture=!0,this.image={width:e,height:t,depth:r},this.magFilter=Y,this.minFilter=Y,this.isStorageTexture=!0}setSize(e,t,r){this.image.width===e&&this.image.height===t&&this.image.depth===r||(this.image.width=e,this.image.height=t,this.image.depth=r,this.dispose())}}class Sw extends gb{constructor(e,t){super(e,t,Uint32Array),this.isIndirectStorageBufferAttribute=!0}}class Ew extends gs{constructor(e){super(e),this.textures={},this.nodes={}}load(e,t,r,s){const i=new ms(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,r=>{try{t(this.parse(JSON.parse(r)))}catch(t){s?s(t):console.error(t),this.manager.itemError(e)}},r,s)}parseNodes(e){const t={};if(void 0!==e){for(const r of e){const{uuid:e,type:s}=r;t[e]=this.createNodeFromType(s),t[e].uuid=e}const r={nodes:t,textures:this.textures};for(const s of e){s.meta=r;t[s.uuid].deserialize(s),delete s.meta}}return t}parse(e){const t=this.createNodeFromType(e.type);t.uuid=e.uuid;const r={nodes:this.parseNodes(e.nodes),textures:this.textures};return e.meta=r,t.deserialize(e),delete e.meta,t}setTextures(e){return this.textures=e,this}setNodes(e){return this.nodes=e,this}createNodeFromType(e){return void 0===this.nodes[e]?(console.error("THREE.NodeLoader: Node type not found:",e),tn()):Gi(new this.nodes[e])}}class Rw extends fs{constructor(e){super(e),this.nodes={},this.nodeMaterials={}}parse(e){const t=super.parse(e),r=this.nodes,s=e.inputNodes;for(const e in s){const i=s[e];t[e]=r[i]}return t}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}createMaterialFromType(e){const t=this.nodeMaterials[e];return void 0!==t?new t:super.createMaterialFromType(e)}}class Aw extends ys{constructor(e){super(e),this.nodes={},this.nodeMaterials={},this._nodesJSON=null}setNodes(e){return this.nodes=e,this}setNodeMaterials(e){return this.nodeMaterials=e,this}parse(e,t){this._nodesJSON=e.nodes;const r=super.parse(e,t);return this._nodesJSON=null,r}parseNodes(e,t){if(void 0!==e){const r=new Ew;return r.setNodes(this.nodes),r.setTextures(t),r.parseNodes(e)}return{}}parseMaterials(e,t){const r={};if(void 0!==e){const s=this.parseNodes(this._nodesJSON,t),i=new Rw;i.setTextures(t),i.setNodes(s),i.setNodeMaterials(this.nodeMaterials);for(let t=0,s=e.length;t